diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md index 54aac66..eb50a9c 100644 --- a/.github/ISSUE_TEMPLATE/bug-report.md +++ b/.github/ISSUE_TEMPLATE/bug-report.md @@ -1,6 +1,6 @@ --- name: Bug Report -about: Report a problem encountered while using hami-dra-lib +about: Report a problem encountered while using dra-lib labels: bug --- diff --git a/.github/ISSUE_TEMPLATE/enhancement.md b/.github/ISSUE_TEMPLATE/enhancement.md index 8671685..093bf6e 100644 --- a/.github/ISSUE_TEMPLATE/enhancement.md +++ b/.github/ISSUE_TEMPLATE/enhancement.md @@ -1,6 +1,6 @@ --- name: Enhancement Request -about: Suggest an improvement to hami-dra-lib +about: Suggest an improvement to dra-lib labels: enhancement --- diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md index 469e37a..8c628bc 100644 --- a/.github/ISSUE_TEMPLATE/question.md +++ b/.github/ISSUE_TEMPLATE/question.md @@ -1,6 +1,6 @@ --- name: Question -about: Ask a question about hami-dra-lib +about: Ask a question about dra-lib labels: question --- diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..b1069d5 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,68 @@ +name: CI + +on: + push: + branches: [master] + pull_request: + branches: [master] + +permissions: + contents: read + +jobs: + test: + name: Build, vet and test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version: '1.26' + check-latest: true + - run: make fmt-check build vet test + + generate: + name: Generated code is up to date + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version: '1.26' + check-latest: true + - run: make tools verify-generate + + govulncheck: + name: govulncheck + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version: '1.26' + check-latest: true + - run: go run golang.org/x/vuln/cmd/govulncheck@v1.10.0 ./... + + fuzz: + name: Fuzz (${{ matrix.target }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + target: [FuzzDecodeV1, FuzzLegacy, FuzzRoundTrip] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version: '1.26' + check-latest: true + - name: Run ${{ matrix.target }} for 60s + run: go test ./checkpoint/ -run '^$' -fuzz '^${{ matrix.target }}$' -fuzztime 60s diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..e58b70f --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,44 @@ +name: CodeQL + +on: + push: + branches: [master] + pull_request: + branches: [master] + schedule: + - cron: '30 3 * * 1' + +permissions: + contents: read + +jobs: + analyze: + name: Analyze (${{ matrix.language }}) + runs-on: ubuntu-latest + permissions: + contents: read + security-events: write + strategy: + fail-fast: false + matrix: + include: + - language: go + build-mode: autobuild + - language: actions + build-mode: none + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Initialize CodeQL + uses: github/codeql-action/init@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea # v4 + with: + languages: ${{ matrix.language }} + build-mode: ${{ matrix.build-mode }} + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea # v4 + with: + category: "/language:${{ matrix.language }}" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..c9d2508 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,27 @@ +name: Release + +on: + push: + tags: ['v*.*.*'] + +permissions: + contents: read + +jobs: + release: + name: GitHub release + runs-on: ubuntu-latest + permissions: + contents: write # to create the release + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Create release with the CHANGELOG section as notes + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ github.ref_name }} + run: | + awk -v tag="## [${TAG#v}]" 'index($0, tag) == 1 {found=1; next} found && /^## /{exit} found' CHANGELOG.md > notes.md + test -s notes.md || { echo "CHANGELOG.md has no section for ${TAG}" >&2; exit 1; } + gh release create "$TAG" --verify-tag --title "$TAG" --notes-file notes.md diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml new file mode 100644 index 0000000..6756b8e --- /dev/null +++ b/.github/workflows/scorecard.yml @@ -0,0 +1,34 @@ +name: OpenSSF Scorecard + +on: + branch_protection_rule: + schedule: + - cron: '30 2 * * 1' + push: + branches: [master] + +permissions: read-all + +jobs: + analysis: + name: Scorecard analysis + runs-on: ubuntu-latest + permissions: + contents: read + security-events: write # to upload SARIF results + id-token: write # to publish results to the OpenSSF REST API + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Run analysis + uses: ossf/scorecard-action@23f22cd43608bae7a1f1fa2603d7314dee9538a5 # v2.6.0 + with: + results_file: results.sarif + results_format: sarif + publish_results: true + - name: Upload SARIF results + uses: github/codeql-action/upload-sarif@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea # v4 + with: + sarif_file: results.sarif diff --git a/.gitignore b/.gitignore index e6aeb81..74e1d76 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,5 @@ coverage.* # editors .idea/ .vscode/ +go.work +go.work.sum diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..321013c --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,29 @@ +# Changelog + +All notable changes to this module are documented here. Versions follow +[semantic versioning](https://semver.org); while the module is v0, breaking Go +API changes bump the minor version. A change to the on-disk checkpoint format +needs a new checkpoint API version (with conversion), not just a new release. + +## [Unreleased] + +## [0.1.0] - 2026-12-01 + +### Added + +- `api/checkpoint/v1`: DRA kubelet plugin checkpoint API (kind `Checkpoint`, + version `v1`, API group chosen by the caller), the only version: the store + reads and writes it directly, without an internal version, with a common + core (claims, prepared devices, CDI container edits, soft/hard partitions, + node partition modes) and optional AMD and NVIDIA sections. +- `checkpoint`: `Store` with atomic writes, a `driverName` ownership check, and + migration from the legacy kubelet checkpointmanager format (deprecated, will + be removed in a future version). +- `Store.Update`: apply all claim changes of one kubelet call and write once + (one encode, one fsync) instead of once per claim. +- Compact JSON on disk, and an fsync of the parent directory after the rename so + the rename survives a power loss. +- Benchmarks for the legacy and v1 formats. Against the kubelet + checkpointmanager, a Prepare call adding 10 claims is 40x to 55x faster from + 100 claims on the node upward; see + [#1](https://github.com/Project-HAMi/dra-lib/issues/1). diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..5eed08a --- /dev/null +++ b/Makefile @@ -0,0 +1,33 @@ +CONTROLLER_GEN_VERSION ?= v0.17.0 +GOBIN ?= $(shell go env GOPATH)/bin + +CHECKPOINT_APIS := $(CURDIR)/api/checkpoint/v1 +HEADER := $(CURDIR)/.license-header.txt + +.PHONY: build vet test fmt-check tools generate generate-deepcopy verify-generate + +build: + go build ./... + +vet: + go vet ./... + +test: + go test ./... + +fmt-check: + @test -z "$$(gofmt -s -l .)" || { gofmt -s -l .; exit 1; } + +tools: + go install sigs.k8s.io/controller-tools/cmd/controller-gen@$(CONTROLLER_GEN_VERSION) + +generate: generate-deepcopy + +generate-deepcopy: + for api in $(CHECKPOINT_APIS); do \ + rm -f $${api}/zz_generated.deepcopy.go; \ + $(GOBIN)/controller-gen object:headerFile=$(HEADER) paths=$${api}/ output:object:dir=$${api}; \ + done + +verify-generate: generate + git diff --exit-code -- api diff --git a/README.md b/README.md index 3570d6a..f6f08f3 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,30 @@ -# hami-dra-lib +# dra-lib -Shared Go library for the [HAMi](https://project-hami.io) DRA drivers -(amd-dra-driver, ascend-dra-driver, k8s-dra-driver). +Shared Go library for Kubernetes DRA (Dynamic Resource Allocation) drivers. -- `checkpoint`: versioned kubelet plugin checkpoint API - (`checkpoint.internal.project-hami.io/v1`), atomic read/write, and migration - from the legacy kubelet checkpointmanager format (removed in HAMi 2.13). -- Common partition model (soft and hard partitions, vendor details per vendor). +- `api/checkpoint`: versioned kubelet plugin checkpoint API: kind `Checkpoint`, + version `v1`, in an API group the driver chooses (for example + `checkpoint.internal.example.com`). A common core (claims, prepared devices, + CDI container edits, soft/hard partitions, node partition modes) plus + optional vendor sections. +- `checkpoint`: `Store` reads and atomically writes the checkpoint, refuses a + checkpoint owned by another driver, and migrates the legacy kubelet + checkpointmanager format (deprecated, will be removed in a future version). -Depends only on k8s.io/apimachinery and the CDI spec, so drivers don't pull in -k8s.io/kubernetes. +```go +store, err := checkpoint.NewStore(path, checkpoint.Options{ + Group: "checkpoint.internal.example.com", + DriverName: "gpu.example.com", +}) +cp, err := store.Read() +err = store.Write(cp) +``` + +Depends on k8s.io/apimachinery, k8s.io/api and the CDI spec only, so drivers +don't need k8s.io/kubernetes. + +Releases are semver tags; see [CHANGELOG.md](CHANGELOG.md). `make generate` +regenerates the deepcopy code (`make tools` installs the generator). ## Contributing diff --git a/SECURITY-INSIGHTS.yml b/SECURITY-INSIGHTS.yml index 22371e8..840afe3 100644 --- a/SECURITY-INSIGHTS.yml +++ b/SECURITY-INSIGHTS.yml @@ -2,24 +2,24 @@ header: schema-version: 2.0.0 last-updated: '2026-12-01' last-reviewed: '2026-12-01' - url: https://github.com/Project-HAMi/hami-dra-lib/blob/master/SECURITY-INSIGHTS.yml + url: https://github.com/Project-HAMi/dra-lib/blob/master/SECURITY-INSIGHTS.yml comment: | - Security metadata for hami-dra-lib, following the OpenSSF + Security metadata for dra-lib, following the OpenSSF Security Insights specification. project: - name: hami-dra-lib + name: dra-lib homepage: https://project-hami.io documentation: - code-of-conduct: https://github.com/Project-HAMi/hami-dra-lib/blob/master/CODE_OF_CONDUCT.md + code-of-conduct: https://github.com/Project-HAMi/dra-lib/blob/master/CODE_OF_CONDUCT.md administrators: - name: Reza Jelveh affiliation: dynamia.ai email: reza@dynamia.ai primary: true repositories: - - name: hami-dra-lib - url: https://github.com/Project-HAMi/hami-dra-lib + - name: dra-lib + url: https://github.com/Project-HAMi/dra-lib comment: | Shared Go library for the HAMi DRA drivers: versioned checkpoint API and common partition model, subproject of HAMi. @@ -27,16 +27,16 @@ project: reports-accepted: true bug-bounty-available: false contact: - name: hami-dra-lib maintainers + name: dra-lib maintainers primary: true - security-policy: https://github.com/Project-HAMi/hami-dra-lib/blob/master/SECURITY.md + security-policy: https://github.com/Project-HAMi/dra-lib/blob/master/SECURITY.md comment: | Report vulnerabilities privately via GitHub Security Advisories: - https://github.com/Project-HAMi/hami-dra-lib/security/advisories/new + https://github.com/Project-HAMi/dra-lib/security/advisories/new See SECURITY.md for the full policy and response process. repository: - url: https://github.com/Project-HAMi/hami-dra-lib + url: https://github.com/Project-HAMi/dra-lib status: active accepts-change-request: true accepts-automated-change-request: true @@ -48,11 +48,11 @@ repository: email: reza@dynamia.ai primary: true documentation: - contributing-guide: https://github.com/Project-HAMi/hami-dra-lib/blob/master/CONTRIBUTING.md - security-policy: https://github.com/Project-HAMi/hami-dra-lib/blob/master/SECURITY.md + contributing-guide: https://github.com/Project-HAMi/dra-lib/blob/master/CONTRIBUTING.md + security-policy: https://github.com/Project-HAMi/dra-lib/blob/master/SECURITY.md governance: https://github.com/Project-HAMi/community/blob/master/governance.md license: - url: https://github.com/Project-HAMi/hami-dra-lib/blob/master/LICENSE + url: https://github.com/Project-HAMi/dra-lib/blob/master/LICENSE expression: Apache-2.0 security: assessments: diff --git a/api/checkpoint/install/install.go b/api/checkpoint/install/install.go new file mode 100644 index 0000000..14705d4 --- /dev/null +++ b/api/checkpoint/install/install.go @@ -0,0 +1,38 @@ +/* +Copyright 2026 The HAMi Authors. + +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. +*/ + +// Package install registers the checkpoint types with a runtime.Scheme. +package install + +import ( + "k8s.io/apimachinery/pkg/runtime" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + + v1 "github.com/Project-HAMi/dra-lib/api/checkpoint/v1" +) + +// Install registers all checkpoint versions under group. +func Install(scheme *runtime.Scheme, group string) { + utilruntime.Must(v1.AddToScheme(scheme, group)) +} + +// NewScheme returns a scheme that decodes any supported checkpoint version +// under group. +func NewScheme(group string) *runtime.Scheme { + scheme := runtime.NewScheme() + Install(scheme, group) + return scheme +} diff --git a/api/checkpoint/install/roundtrip_test.go b/api/checkpoint/install/roundtrip_test.go new file mode 100644 index 0000000..4bdb5ea --- /dev/null +++ b/api/checkpoint/install/roundtrip_test.go @@ -0,0 +1,37 @@ +/* +Copyright 2026 The HAMi Authors. + +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. +*/ + +package install + +import ( + "math/rand" + "testing" + + "k8s.io/apimachinery/pkg/api/apitesting/fuzzer" + "k8s.io/apimachinery/pkg/api/apitesting/roundtrip" + metafuzzer "k8s.io/apimachinery/pkg/apis/meta/fuzzer" + "k8s.io/apimachinery/pkg/runtime/serializer" +) + +// TestRoundTrip fuzz-tests the v1 types through the scheme. v1 is the only +// version, so the external-types variant is needed: the API group variant +// only covers internal types. +func TestRoundTrip(t *testing.T) { + scheme := NewScheme("checkpoint.internal.example.com") + codecs := serializer.NewCodecFactory(scheme) + f := fuzzer.FuzzerFor(metafuzzer.Funcs, rand.NewSource(rand.Int63()), codecs) + roundtrip.RoundTripExternalTypesWithoutProtobuf(t, scheme, codecs, f, nil) +} diff --git a/api/checkpoint/v1/cdi.go b/api/checkpoint/v1/cdi.go new file mode 100644 index 0000000..7d5624a --- /dev/null +++ b/api/checkpoint/v1/cdi.go @@ -0,0 +1,41 @@ +/* +Copyright 2026 The HAMi Authors. + +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. +*/ + +package v1 + +import "encoding/json" + +// DeepCopyInto copies the CDI container edits, which have no generated deep +// copy, through a JSON round trip. +func (in *ContainerEdits) DeepCopyInto(out *ContainerEdits) { + data, err := json.Marshal(in) + if err != nil { + panic(err) + } + *out = ContainerEdits{} + if err := json.Unmarshal(data, out); err != nil { + panic(err) + } +} + +func (in *ContainerEdits) DeepCopy() *ContainerEdits { + if in == nil { + return nil + } + out := new(ContainerEdits) + in.DeepCopyInto(out) + return out +} diff --git a/api/checkpoint/v1/doc.go b/api/checkpoint/v1/doc.go new file mode 100644 index 0000000..43a7e5f --- /dev/null +++ b/api/checkpoint/v1/doc.go @@ -0,0 +1,33 @@ +/* +Copyright 2026 The HAMi Authors. + +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. +*/ + +// +k8s:deepcopy-gen=package + +// Package v1 is the checkpoint API: kind Checkpoint, version v1, in an API +// group the caller chooses. Changes follow the Kubernetes [API changes] +// guidelines. +// +// v1 is the only version on purpose, so the store reads and writes v1 directly +// with no internal version or conversion. When a v2 is needed, add the v2 +// types with generated conversion to and from v1, register both in +// install.NewScheme, and have the store decode either version into the newest +// one, so existing v1 files keep reading. If more than two versions have to +// coexist, reintroduce an internal hub version then (the Kubernetes +// internal+versioned pattern). A driver-visible type change is a minor +// version bump while dra-lib is v0. There is no type-alias package. +// +// [API changes]: https://github.com/kubernetes/community/blob/047598ce8b0932b9be921471dd301b6a82db210f/contributors/devel/sig-architecture/api_changes.md +package v1 diff --git a/api/checkpoint/v1/register.go b/api/checkpoint/v1/register.go new file mode 100644 index 0000000..21692f4 --- /dev/null +++ b/api/checkpoint/v1/register.go @@ -0,0 +1,36 @@ +/* +Copyright 2026 The HAMi Authors. + +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. +*/ + +package v1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +const ( + Version = "v1" + Kind = "Checkpoint" +) + +// AddToScheme registers the v1 types under group. +func AddToScheme(scheme *runtime.Scheme, group string) error { + gv := schema.GroupVersion{Group: group, Version: Version} + scheme.AddKnownTypes(gv, &Checkpoint{}) + metav1.AddToGroupVersion(scheme, gv) + return nil +} diff --git a/api/checkpoint/v1/types.go b/api/checkpoint/v1/types.go new file mode 100644 index 0000000..91d4d38 --- /dev/null +++ b/api/checkpoint/v1/types.go @@ -0,0 +1,230 @@ +/* +Copyright 2026 The HAMi Authors. + +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. +*/ + +package v1 + +import ( + resourcev1 "k8s.io/api/resource/v1" + "k8s.io/apimachinery/pkg/api/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + cdispec "tags.cncf.io/container-device-interface/specs-go" +) + +// Checkpoint is the persisted state of a DRA kubelet plugin: the devices +// prepared for each ResourceClaim and the node-level partition configuration +// the driver applied. +// +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +type Checkpoint struct { + metav1.TypeMeta `json:",inline"` + + // DriverName is the DRA driver that owns the checkpoint. + DriverName string `json:"driverName"` + // NodeBootID is the Linux boot ID of the node when the checkpoint was last + // validated; prepared claims from another boot are invalid. + // +optional + NodeBootID string `json:"nodeBootID,omitempty"` + // +optional + Partitioning *NodePartitioning `json:"partitioning,omitempty"` + // +optional + // +listType=map + // +listMapKey=uid + PreparedClaims []PreparedClaim `json:"preparedClaims,omitempty"` +} + +type PreparedClaim struct { + UID types.UID `json:"uid"` + // +optional + Name string `json:"name,omitempty"` + // +optional + Namespace string `json:"namespace,omitempty"` + // +optional + State PrepareState `json:"state,omitempty"` + // +optional + Status *resourcev1.ResourceClaimStatus `json:"status,omitempty"` + // +optional + // +listType=atomic + Devices []PreparedDevice `json:"devices,omitempty"` + // +optional + NVIDIA *NVIDIAClaim `json:"nvidia,omitempty"` +} + +type PrepareState string + +const ( + PrepareStateStarted PrepareState = "PrepareStarted" + PrepareStateCompleted PrepareState = "PrepareCompleted" +) + +type PreparedDevice struct { + Device Device `json:"device"` + // +optional + ContainerEdits *ContainerEdits `json:"containerEdits,omitempty"` + // +optional + Partition *Partition `json:"partition,omitempty"` + // +optional + AMD *AMDDevice `json:"amd,omitempty"` + // +optional + NVIDIA *NVIDIADevice `json:"nvidia,omitempty"` +} + +// Device references the device in the kubelet DRA API. +type Device struct { + // +optional + // +listType=atomic + Requests []string `json:"requests,omitempty"` + PoolName string `json:"poolName"` + DeviceName string `json:"deviceName"` + // +optional + // +listType=atomic + CDIDeviceIDs []string `json:"cdiDeviceIDs,omitempty"` +} + +// +k8s:deepcopy-gen=false +type ContainerEdits struct { + cdispec.ContainerEdits `json:",inline"` +} + +type PartitionType string + +const ( + // PartitionTypeSoft is a share enforced by software limits, such as + // memory and core percent of the parent device. + PartitionTypeSoft PartitionType = "Soft" + // PartitionTypeHard is a partition created by the device itself (NVIDIA + // MIG, AMD compute/memory partition, Ascend vNPU template). + PartitionTypeHard PartitionType = "Hard" +) + +// Partition describes the part of a parent device a prepared device represents. +type Partition struct { + Type PartitionType `json:"type"` + // +optional + Profile string `json:"profile,omitempty"` + // +optional + ParentDevice string `json:"parentDevice,omitempty"` + // +optional + Memory *resource.Quantity `json:"memory,omitempty"` + // Cores is the percentage of the parent device's cores. + // +optional + Cores *int32 `json:"cores,omitempty"` + // +optional + AMD *AMDPartition `json:"amd,omitempty"` + // +optional + NVIDIA *NVIDIAPartition `json:"nvidia,omitempty"` +} + +type PartitionModeKind string + +const ( + PartitionModeKindCompute PartitionModeKind = "compute" + PartitionModeKindMemory PartitionModeKind = "memory" + PartitionModeKindMIG PartitionModeKind = "mig" +) + +type NodePartitioning struct { + // +optional + // +listType=map + // +listMapKey=device + // +listMapKey=kind + Modes []PartitionMode `json:"modes,omitempty"` + // +optional + AMD *AMDNodePartitioning `json:"amd,omitempty"` +} + +type PartitionMode struct { + // Device is the parent device ID; empty means node-wide. + // +optional + Device string `json:"device,omitempty"` + Kind PartitionModeKind `json:"kind"` + Mode string `json:"mode"` +} + +type AMDDevice struct { + // ShareKey identifies the allocation share this device represents. + // +optional + ShareKey string `json:"shareKey,omitempty"` +} + +type AMDPartition struct { + // Slot is the partition slot this share was assigned on its GPU. + // +optional + Slot *int32 `json:"slot,omitempty"` + // ComputeUnits are the CUs given to this share of a whole GPU. + // +optional + // +listType=atomic + ComputeUnits []int32 `json:"computeUnits,omitempty"` +} + +type AMDNodePartitioning struct { + // +optional + MemoryReload *AMDMemoryReload `json:"memoryReload,omitempty"` + // +optional + // +listType=atomic + AssignedSlots []AMDAssignedSlot `json:"assignedSlots,omitempty"` +} + +// AMDMemoryReload records an in-flight KMM driver reload for a memory partition change. +type AMDMemoryReload struct { + Mode string `json:"mode"` + TriggeredAt metav1.Time `json:"triggeredAt"` +} + +// AMDAssignedSlot records the partition slot an allocation share holds. +type AMDAssignedSlot struct { + GPUIndex int32 `json:"gpuIndex"` + ShareKey string `json:"shareKey"` + Slot int32 `json:"slot"` +} + +type NVIDIAClaim struct { + // Groups are the device groups of the claim that share a configuration, + // in prepare order. NVIDIADevice.Group indexes this list. + // +optional + // +listType=atomic + Groups []NVIDIADeviceGroup `json:"groups,omitempty"` +} + +type NVIDIADeviceGroup struct { + // +optional + MPSControlDaemonID string `json:"mpsControlDaemonID,omitempty"` +} + +type NVIDIADeviceType string + +const ( + NVIDIADeviceTypeGPU NVIDIADeviceType = "gpu" + NVIDIADeviceTypeMIG NVIDIADeviceType = "mig" + NVIDIADeviceTypeVFIO NVIDIADeviceType = "vfio" +) + +type NVIDIADevice struct { + // Group is the index of the device's group in NVIDIAClaim.Groups. + Group int32 `json:"group"` + Type NVIDIADeviceType `json:"type"` + // UUID is the GPU UUID of gpu and vfio devices. + // +optional + UUID string `json:"uuid,omitempty"` +} + +// NVIDIAPartition holds the MIG device identity of a hard partition. +type NVIDIAPartition struct { + ParentMinor int32 `json:"parentMinor"` + GIID int32 `json:"giID"` + CIID int32 `json:"ciID"` + MIGUUID string `json:"migUUID"` +} diff --git a/api/checkpoint/v1/zz_generated.deepcopy.go b/api/checkpoint/v1/zz_generated.deepcopy.go new file mode 100644 index 0000000..bee1a86 --- /dev/null +++ b/api/checkpoint/v1/zz_generated.deepcopy.go @@ -0,0 +1,390 @@ +//go:build !ignore_autogenerated + +/* +Copyright 2026 The HAMi Authors. + +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. +*/ + +// Code generated by controller-gen. DO NOT EDIT. + +package v1 + +import ( + resourcev1 "k8s.io/api/resource/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AMDAssignedSlot) DeepCopyInto(out *AMDAssignedSlot) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AMDAssignedSlot. +func (in *AMDAssignedSlot) DeepCopy() *AMDAssignedSlot { + if in == nil { + return nil + } + out := new(AMDAssignedSlot) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AMDDevice) DeepCopyInto(out *AMDDevice) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AMDDevice. +func (in *AMDDevice) DeepCopy() *AMDDevice { + if in == nil { + return nil + } + out := new(AMDDevice) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AMDMemoryReload) DeepCopyInto(out *AMDMemoryReload) { + *out = *in + in.TriggeredAt.DeepCopyInto(&out.TriggeredAt) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AMDMemoryReload. +func (in *AMDMemoryReload) DeepCopy() *AMDMemoryReload { + if in == nil { + return nil + } + out := new(AMDMemoryReload) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AMDNodePartitioning) DeepCopyInto(out *AMDNodePartitioning) { + *out = *in + if in.MemoryReload != nil { + in, out := &in.MemoryReload, &out.MemoryReload + *out = new(AMDMemoryReload) + (*in).DeepCopyInto(*out) + } + if in.AssignedSlots != nil { + in, out := &in.AssignedSlots, &out.AssignedSlots + *out = make([]AMDAssignedSlot, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AMDNodePartitioning. +func (in *AMDNodePartitioning) DeepCopy() *AMDNodePartitioning { + if in == nil { + return nil + } + out := new(AMDNodePartitioning) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AMDPartition) DeepCopyInto(out *AMDPartition) { + *out = *in + if in.Slot != nil { + in, out := &in.Slot, &out.Slot + *out = new(int32) + **out = **in + } + if in.ComputeUnits != nil { + in, out := &in.ComputeUnits, &out.ComputeUnits + *out = make([]int32, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AMDPartition. +func (in *AMDPartition) DeepCopy() *AMDPartition { + if in == nil { + return nil + } + out := new(AMDPartition) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Checkpoint) DeepCopyInto(out *Checkpoint) { + *out = *in + out.TypeMeta = in.TypeMeta + if in.Partitioning != nil { + in, out := &in.Partitioning, &out.Partitioning + *out = new(NodePartitioning) + (*in).DeepCopyInto(*out) + } + if in.PreparedClaims != nil { + in, out := &in.PreparedClaims, &out.PreparedClaims + *out = make([]PreparedClaim, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Checkpoint. +func (in *Checkpoint) DeepCopy() *Checkpoint { + if in == nil { + return nil + } + out := new(Checkpoint) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Checkpoint) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Device) DeepCopyInto(out *Device) { + *out = *in + if in.Requests != nil { + in, out := &in.Requests, &out.Requests + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.CDIDeviceIDs != nil { + in, out := &in.CDIDeviceIDs, &out.CDIDeviceIDs + *out = make([]string, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Device. +func (in *Device) DeepCopy() *Device { + if in == nil { + return nil + } + out := new(Device) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *NVIDIAClaim) DeepCopyInto(out *NVIDIAClaim) { + *out = *in + if in.Groups != nil { + in, out := &in.Groups, &out.Groups + *out = make([]NVIDIADeviceGroup, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NVIDIAClaim. +func (in *NVIDIAClaim) DeepCopy() *NVIDIAClaim { + if in == nil { + return nil + } + out := new(NVIDIAClaim) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *NVIDIADevice) DeepCopyInto(out *NVIDIADevice) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NVIDIADevice. +func (in *NVIDIADevice) DeepCopy() *NVIDIADevice { + if in == nil { + return nil + } + out := new(NVIDIADevice) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *NVIDIADeviceGroup) DeepCopyInto(out *NVIDIADeviceGroup) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NVIDIADeviceGroup. +func (in *NVIDIADeviceGroup) DeepCopy() *NVIDIADeviceGroup { + if in == nil { + return nil + } + out := new(NVIDIADeviceGroup) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *NVIDIAPartition) DeepCopyInto(out *NVIDIAPartition) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NVIDIAPartition. +func (in *NVIDIAPartition) DeepCopy() *NVIDIAPartition { + if in == nil { + return nil + } + out := new(NVIDIAPartition) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *NodePartitioning) DeepCopyInto(out *NodePartitioning) { + *out = *in + if in.Modes != nil { + in, out := &in.Modes, &out.Modes + *out = make([]PartitionMode, len(*in)) + copy(*out, *in) + } + if in.AMD != nil { + in, out := &in.AMD, &out.AMD + *out = new(AMDNodePartitioning) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodePartitioning. +func (in *NodePartitioning) DeepCopy() *NodePartitioning { + if in == nil { + return nil + } + out := new(NodePartitioning) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Partition) DeepCopyInto(out *Partition) { + *out = *in + if in.Memory != nil { + in, out := &in.Memory, &out.Memory + x := (*in).DeepCopy() + *out = &x + } + if in.Cores != nil { + in, out := &in.Cores, &out.Cores + *out = new(int32) + **out = **in + } + if in.AMD != nil { + in, out := &in.AMD, &out.AMD + *out = new(AMDPartition) + (*in).DeepCopyInto(*out) + } + if in.NVIDIA != nil { + in, out := &in.NVIDIA, &out.NVIDIA + *out = new(NVIDIAPartition) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Partition. +func (in *Partition) DeepCopy() *Partition { + if in == nil { + return nil + } + out := new(Partition) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PartitionMode) DeepCopyInto(out *PartitionMode) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PartitionMode. +func (in *PartitionMode) DeepCopy() *PartitionMode { + if in == nil { + return nil + } + out := new(PartitionMode) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PreparedClaim) DeepCopyInto(out *PreparedClaim) { + *out = *in + if in.Status != nil { + in, out := &in.Status, &out.Status + *out = new(resourcev1.ResourceClaimStatus) + (*in).DeepCopyInto(*out) + } + if in.Devices != nil { + in, out := &in.Devices, &out.Devices + *out = make([]PreparedDevice, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.NVIDIA != nil { + in, out := &in.NVIDIA, &out.NVIDIA + *out = new(NVIDIAClaim) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PreparedClaim. +func (in *PreparedClaim) DeepCopy() *PreparedClaim { + if in == nil { + return nil + } + out := new(PreparedClaim) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PreparedDevice) DeepCopyInto(out *PreparedDevice) { + *out = *in + in.Device.DeepCopyInto(&out.Device) + if in.ContainerEdits != nil { + in, out := &in.ContainerEdits, &out.ContainerEdits + *out = (*in).DeepCopy() + } + if in.Partition != nil { + in, out := &in.Partition, &out.Partition + *out = new(Partition) + (*in).DeepCopyInto(*out) + } + if in.AMD != nil { + in, out := &in.AMD, &out.AMD + *out = new(AMDDevice) + **out = **in + } + if in.NVIDIA != nil { + in, out := &in.NVIDIA, &out.NVIDIA + *out = new(NVIDIADevice) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PreparedDevice. +func (in *PreparedDevice) DeepCopy() *PreparedDevice { + if in == nil { + return nil + } + out := new(PreparedDevice) + in.DeepCopyInto(out) + return out +} diff --git a/checkpoint/bench_test.go b/checkpoint/bench_test.go new file mode 100644 index 0000000..45a5901 --- /dev/null +++ b/checkpoint/bench_test.go @@ -0,0 +1,263 @@ +/* +Copyright 2026 The HAMi Authors. + +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. +*/ + +package checkpoint + +import ( + "fmt" + "os" + "path/filepath" + "testing" + + "k8s.io/apimachinery/pkg/types" + cdispec "tags.cncf.io/container-device-interface/specs-go" + + api "github.com/Project-HAMi/dra-lib/api/checkpoint/v1" +) + +// The legacy side is what the kubelet checkpointmanager did for the AMD and +// Ascend drivers: legacyTestCheckpoint (marshal, hash, marshal again on write; +// unmarshal, marshal, hash on read) and a temp file that is fsynced and +// renamed. + +func benchEdits(i int) cdispec.ContainerEdits { + return cdispec.ContainerEdits{ + Env: []string{ + fmt.Sprintf("HIP_VISIBLE_DEVICES=%d", i), fmt.Sprintf("ROCR_VISIBLE_DEVICES=GPU-%016x", i), + "HSA_CU_MASK=0:0-59", "GPU_DEVICE_ORDINAL=0", + }, + DeviceNodes: []*cdispec.DeviceNode{ + {Path: "/dev/kfd"}, + {Path: fmt.Sprintf("/dev/dri/card%d", i%8)}, + {Path: fmt.Sprintf("/dev/dri/renderD%d", 128+i%8)}, + }, + Mounts: []*cdispec.Mount{ + {HostPath: "/usr/local/vgpu/libvgpu.so", ContainerPath: "/usr/local/vgpu/libvgpu.so", Options: []string{"ro", "nosuid", "nodev", "bind"}}, + {HostPath: fmt.Sprintf("/var/lib/dra/claims/%d", i), ContainerPath: "/var/lib/dra/claim", Options: []string{"rw", "bind"}}, + }, + Hooks: []*cdispec.Hook{{HookName: "createContainer", Path: "/usr/bin/cdi-hook", Args: []string{"cdi-hook", "update-ldcache", "--folder", "/usr/local/vgpu"}}}, + } +} + +type benchCase struct { + claims, devices int +} + +func (c benchCase) String() string { + return fmt.Sprintf("claims=%d/devices=%d", c.claims, c.devices) +} + +// Claims per node are bounded only by the split count and maxPods: soft slices +// can be as small as 1 MB. +var benchCases = []benchCase{{1, 1}, {10, 1}, {100, 1}, {1000, 1}, {10000, 1}, {100, 8}} + +func benchUID(i int) string { + return fmt.Sprintf("8d4b5c2e-%04d-4a5b-9c1d-%012d", i%10000, i) +} + +// benchClaim returns claim i with its devices in both formats. +func benchClaim(i, devices int) ([]*legacyTestDevice, api.PreparedClaim) { + uid := benchUID(i) + var legacy []*legacyTestDevice + claim := api.PreparedClaim{UID: types.UID(uid)} + for d := range devices { + edits := benchEdits(i*devices + d) + device := api.Device{ + Requests: []string{"gpu"}, PoolName: "node-a", DeviceName: fmt.Sprintf("gpu-%d", d), + CDIDeviceIDs: []string{fmt.Sprintf("example.com/gpu=%s-gpu-%d", uid, d)}, + } + legacy = append(legacy, &legacyTestDevice{ + RequestNames: device.Requests, PoolName: device.PoolName, DeviceName: device.DeviceName, + CDIDeviceIDs: device.CDIDeviceIDs, ContainerEdits: &edits, + }) + claim.Devices = append(claim.Devices, api.PreparedDevice{Device: device, ContainerEdits: &api.ContainerEdits{ContainerEdits: edits}}) + } + return legacy, claim +} + +func benchCheckpoints(c benchCase) (*legacyTestCheckpoint, *api.Checkpoint) { + legacy := &legacyTestCheckpoint{V1: &legacyTestClaimsV1{PreparedClaims: map[string][]*legacyTestDevice{}}} + current := &api.Checkpoint{DriverName: testDriver} + for i := range c.claims { + legacyDevices, claim := benchClaim(i, c.devices) + legacy.V1.PreparedClaims[benchUID(i)] = legacyDevices + current.PreparedClaims = append(current.PreparedClaims, claim) + } + return legacy, current +} + +// benchLegacyWriteFile is kubelet's filestore write: temp file, fsync, rename. +func benchLegacyWriteFile(path string, data []byte) error { + tmp := path + ".tmp" + f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) + if err != nil { + return err + } + if _, err := f.Write(data); err != nil { + _ = f.Close() + return err + } + if err := f.Sync(); err != nil { + _ = f.Close() + return err + } + if err := f.Close(); err != nil { + return err + } + return os.Rename(tmp, path) +} + +func benchLegacyRead(path string) (*legacyTestCheckpoint, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + cp := &legacyTestCheckpoint{} + return cp, cp.unmarshal(data) +} + +func benchLegacyWrite(path string, cp *legacyTestCheckpoint) error { + data, err := cp.marshal() + if err != nil { + return err + } + return benchLegacyWriteFile(path, data) +} + +func reportFileSize(b *testing.B, path string) { + b.Helper() + info, err := os.Stat(path) + if err != nil { + b.Fatal(err) + } + b.ReportMetric(float64(info.Size()), "file-bytes") +} + +// Run with TMPDIR on a real filesystem; on tmpfs fsync costs nothing. + +func BenchmarkWrite(b *testing.B) { + for _, c := range benchCases { + legacy, current := benchCheckpoints(c) + b.Run("legacy/"+c.String(), func(b *testing.B) { + path := filepath.Join(b.TempDir(), "checkpoint.json") + b.ReportAllocs() + for b.Loop() { + if err := benchLegacyWrite(path, legacy); err != nil { + b.Fatal(err) + } + } + reportFileSize(b, path) + }) + b.Run("v1/"+c.String(), func(b *testing.B) { + s := benchStore(b) + b.ReportAllocs() + for b.Loop() { + if err := s.Write(current); err != nil { + b.Fatal(err) + } + } + reportFileSize(b, s.path) + }) + } +} + +func BenchmarkRead(b *testing.B) { + for _, c := range benchCases { + legacy, current := benchCheckpoints(c) + b.Run("legacy/"+c.String(), func(b *testing.B) { + path := filepath.Join(b.TempDir(), "checkpoint.json") + if err := benchLegacyWrite(path, legacy); err != nil { + b.Fatal(err) + } + b.ReportAllocs() + for b.Loop() { + if _, err := benchLegacyRead(path); err != nil { + b.Fatal(err) + } + } + reportFileSize(b, path) + }) + b.Run("v1/"+c.String(), func(b *testing.B) { + s := benchStore(b) + if err := s.Write(current); err != nil { + b.Fatal(err) + } + b.ReportAllocs() + for b.Loop() { + if _, err := s.Read(); err != nil { + b.Fatal(err) + } + } + reportFileSize(b, s.path) + }) + } +} + +// BenchmarkPrepareCycle is one Prepare: read the checkpoint, record one more +// claim, write it. +func BenchmarkPrepareCycle(b *testing.B) { + for _, c := range benchCases { + legacy, current := benchCheckpoints(c) + legacyClaim, claim := benchClaim(c.claims, c.devices) + b.Run("legacy/"+c.String(), func(b *testing.B) { + path := filepath.Join(b.TempDir(), "checkpoint.json") + if err := benchLegacyWrite(path, legacy); err != nil { + b.Fatal(err) + } + b.ReportAllocs() + for b.Loop() { + cp, err := benchLegacyRead(path) + if err != nil { + b.Fatal(err) + } + cp.V1.PreparedClaims[string(claim.UID)] = legacyClaim + if err := benchLegacyWrite(path, cp); err != nil { + b.Fatal(err) + } + } + reportFileSize(b, path) + }) + b.Run("v1/"+c.String(), func(b *testing.B) { + s := benchStore(b) + if err := s.Write(current); err != nil { + b.Fatal(err) + } + b.ReportAllocs() + for b.Loop() { + err := s.Update(func(cp *api.Checkpoint) error { + if last := len(cp.PreparedClaims) - 1; cp.PreparedClaims[last].UID == claim.UID { + cp.PreparedClaims[last] = claim + return nil + } + cp.PreparedClaims = append(cp.PreparedClaims, claim) + return nil + }) + if err != nil { + b.Fatal(err) + } + } + reportFileSize(b, s.path) + }) + } +} + +func benchStore(b *testing.B) *Store { + s, err := NewStore(filepath.Join(b.TempDir(), "checkpoint.json"), Options{Group: testGroup, DriverName: testDriver}) + if err != nil { + b.Fatal(err) + } + return s +} diff --git a/checkpoint/fuzz_test.go b/checkpoint/fuzz_test.go new file mode 100644 index 0000000..d17c5e9 --- /dev/null +++ b/checkpoint/fuzz_test.go @@ -0,0 +1,239 @@ +/* +Copyright 2026 The HAMi Authors. + +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. +*/ + +package checkpoint + +import ( + "bytes" + "os" + "path/filepath" + "regexp" + "strings" + "testing" + "unicode/utf8" + + "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/api/resource" + "k8s.io/apimachinery/pkg/types" + cdispec "tags.cncf.io/container-device-interface/specs-go" + + api "github.com/Project-HAMi/dra-lib/api/checkpoint/v1" +) + +// slowQuantity matches quantities with a large negative exponent, for which +// resource.ParseQuantity in k8s.io/apimachinery takes minutes: a JSON decode of +// "1e-2100000000" does not finish. Such inputs are skipped so the fuzz +// workers keep running. +var slowQuantity = regexp.MustCompile(`[eE]-0*[0-9]{6,}`) + +var legacyFixtures = []string{ + "testdata/legacy-amd.json", + "testdata/legacy-ascend.json", + "testdata/legacy-nvidia.json", + "testdata/legacy-nvidia-v1.json", +} + +func fuzzStore(t testing.TB, driverName string) *Store { + t.Helper() + s, err := NewStore(filepath.Join(t.TempDir(), "checkpoint.json"), Options{Group: testGroup, DriverName: driverName}) + if err != nil { + t.Fatal(err) + } + return s +} + +// FuzzDecodeV1 decodes arbitrary bytes as a v1 checkpoint: it must not panic, +// and a decoded checkpoint must survive encode+decode unchanged. +func FuzzDecodeV1(f *testing.F) { + s := fuzzStore(f, testDriver) + for _, fixture := range legacyFixtures { + legacy, err := os.ReadFile(fixture) + if err != nil { + f.Fatal(err) + } + cp, err := readLegacy(legacy) + if err != nil { + f.Fatal(err) + } + cp.DriverName = testDriver + var buf bytes.Buffer + if err := s.encoder.Encode(cp, &buf); err != nil { + f.Fatal(err) + } + f.Add(buf.Bytes()) + } + f.Add([]byte(`{"apiVersion":"` + testGroup + `/v1","kind":"Checkpoint","driverName":"` + testDriver + `"}`)) + f.Add([]byte(`{}`)) + // A quantity for which Quantity.Cmp does not finish. + f.Add([]byte(`{"apiVersion":"` + testGroup + `/v1","kind":"Checkpoint","driverName":"` + testDriver + `","preparedClaims":[{"uid":"a","devices":[{"device":{"poolName":"p","deviceName":"d"},"partition":{"type":"Soft","memory":"e2100000000"}}]}]}`)) + f.Add([]byte(`null`)) + + f.Fuzz(func(t *testing.T, data []byte) { + if isLegacy(data) || slowQuantity.Match(data) { + return // FuzzLegacy covers legacy input. + } + first, err := s.decode(data) + if err != nil { + return + } + // Compare encoded bytes, not objects: Quantity.Cmp does not finish + // for quantities with huge exponents. + var once, twice bytes.Buffer + if err := s.encoder.Encode(first, &once); err != nil { + t.Fatalf("encode a decoded checkpoint: %v", err) + } + second, err := s.decode(once.Bytes()) + if err != nil { + t.Fatalf("decode an encoded checkpoint: %v\n%s", err, once.Bytes()) + } + if err := s.encoder.Encode(second, &twice); err != nil { + t.Fatalf("encode the round-tripped checkpoint: %v", err) + } + if !bytes.Equal(once.Bytes(), twice.Bytes()) { + t.Fatalf("round trip changed the checkpoint:\n%s\n%s", once.Bytes(), twice.Bytes()) + } + }) +} + +// FuzzLegacy reads arbitrary bytes as a legacy checkpointmanager file: it +// must not panic, a bad checksum or bad JSON is an error and leaves the file +// alone, and valid input is migrated to the current format. +func FuzzLegacy(f *testing.F) { + for _, fixture := range legacyFixtures { + legacy, err := os.ReadFile(fixture) + if err != nil { + f.Fatal(err) + } + f.Add(legacy) + f.Add(bytes.Replace(legacy, []byte(`"pool_name":"node-a"`), []byte(`"pool_name":"node-b"`), 1)) + } + helper := &legacyTestCheckpoint{V1: &legacyTestClaimsV1{PreparedClaims: map[string][]*legacyTestDevice{ + "uid-a": {{RequestNames: []string{"gpu"}, PoolName: "node-a", DeviceName: "gpu-0", ContainerEdits: &cdispec.ContainerEdits{Env: []string{"A=1"}}}}, + }}} + if data, err := helper.marshal(); err == nil { + f.Add(data) + } + f.Add([]byte(`{"checksum":0}`)) + f.Add([]byte(`{"checksum":"x","v1":[]}`)) + + f.Fuzz(func(t *testing.T, data []byte) { + if !isLegacy(data) || slowQuantity.Match(data) { + return + } + s := fuzzStore(t, testDriver) + if err := os.WriteFile(s.path, data, 0o600); err != nil { + t.Fatal(err) + } + verifyErr := verifyLegacyChecksums(data) + got, err := s.Read() + if err != nil { + after, readErr := os.ReadFile(s.path) + if readErr != nil || !bytes.Equal(after, data) { + t.Fatalf("a rejected legacy checkpoint was modified: %v", err) + } + return + } + if verifyErr != nil { + t.Fatalf("legacy checkpoint with a bad checksum was accepted: %v", verifyErr) + } + again, err := s.Read() + if err != nil { + t.Fatalf("read the migrated checkpoint: %v", err) + } + // Compare encoded bytes: Quantity.Cmp does not finish for quantities + // with huge exponents, which a legacy claim status can carry. + var gotData, againData bytes.Buffer + if err := s.encoder.Encode(got, &gotData); err != nil { + t.Fatal(err) + } + if err := s.encoder.Encode(again, &againData); err != nil { + t.Fatal(err) + } + if !bytes.Equal(gotData.Bytes(), againData.Bytes()) { + t.Fatalf("migrated checkpoint reads back differently:\n%s\n%s", gotData.Bytes(), againData.Bytes()) + } + }) +} + +// FuzzRoundTrip writes a checkpoint built from fuzzed fields and reads it +// back; a store for another driver must refuse it. +func FuzzRoundTrip(f *testing.F) { + f.Add("uid-1", "uid-2", testDriver, "gpu-0", "gpu-1", int32(1), int32(50), "1g.10gb", int64(4<<30), "A=1", "/dev/nvidia0", "nps4") + f.Add("", "", "x", "", "", int32(-1), int32(0), "", int64(0), "", "", "") + + f.Fuzz(func(t *testing.T, uid1, uid2, driverName, device1, device2 string, slot, cores int32, profile string, memory int64, env, devicePath, mode string) { + // Kubernetes API strings are UTF-8; JSON replaces invalid bytes. + for _, s := range []string{uid1, uid2, driverName, device1, device2, profile, env, devicePath, mode} { + if !utf8.ValidString(s) { + return + } + } + if driverName == "" { + return + } + checkpoint := &api.Checkpoint{ + DriverName: driverName, + NodeBootID: uid2, + Partitioning: &api.NodePartitioning{ + Modes: []api.PartitionMode{{Device: device1, Kind: api.PartitionModeKindMemory, Mode: mode}}, + AMD: &api.AMDNodePartitioning{AssignedSlots: []api.AMDAssignedSlot{{GPUIndex: slot, ShareKey: uid1, Slot: slot}}}, + }, + PreparedClaims: []api.PreparedClaim{ + { + UID: types.UID(uid1), + State: api.PrepareStateCompleted, + Devices: []api.PreparedDevice{{ + Device: api.Device{Requests: []string{profile}, PoolName: driverName, DeviceName: device1, CDIDeviceIDs: []string{device2}}, + ContainerEdits: &api.ContainerEdits{ContainerEdits: cdispec.ContainerEdits{Env: []string{env}, DeviceNodes: []*cdispec.DeviceNode{{Path: devicePath}}}}, + Partition: &api.Partition{Type: api.PartitionTypeHard, Profile: profile, ParentDevice: device2, Cores: &cores, AMD: &api.AMDPartition{Slot: &slot}}, + AMD: &api.AMDDevice{ShareKey: uid2}, + }}, + }, + { + UID: types.UID(uid2), + Devices: []api.PreparedDevice{{ + Device: api.Device{DeviceName: device2}, + Partition: &api.Partition{Type: api.PartitionTypeSoft, NVIDIA: &api.NVIDIAPartition{GIID: slot, CIID: cores, MIGUUID: uid1}}, + NVIDIA: &api.NVIDIADevice{Group: slot, Type: api.NVIDIADeviceTypeMIG, UUID: device1}, + }}, + }, + }, + } + // Memory is built from bytes: quantities parsed from arbitrary strings + // can have exponents for which Quantity.Cmp does not finish. + checkpoint.PreparedClaims[0].Devices[0].Partition.Memory = resource.NewQuantity(memory, resource.BinarySI) + + s := fuzzStore(t, driverName) + if err := s.Write(checkpoint); err != nil { + t.Fatalf("write: %v", err) + } + got, err := s.Read() + if err != nil { + t.Fatalf("read: %v", err) + } + if !equality.Semantic.DeepEqual(checkpoint, got) { + t.Fatalf("round trip changed the checkpoint:\n%#v\n%#v", checkpoint, got) + } + + other, err := NewStore(s.path, Options{Group: testGroup, DriverName: driverName + "-other"}) + if err != nil { + t.Fatal(err) + } + if _, err := other.Read(); err == nil || !strings.Contains(err.Error(), "driverName") { + t.Fatalf("a checkpoint of driver %q was not refused by another driver: %v", driverName, err) + } + }) +} diff --git a/checkpoint/legacy.go b/checkpoint/legacy.go new file mode 100644 index 0000000..c8eecb9 --- /dev/null +++ b/checkpoint/legacy.go @@ -0,0 +1,386 @@ +/* +Copyright 2026 The HAMi Authors. + +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. +*/ + +// Deprecated: legacy kubelet checkpointmanager format, will be removed in a future version. +// Everything in this file reads that format and goes when support ends. +// +// The checksum follows k8s.io/kubernetes pkg/kubelet/checkpointmanager/checksum +// (Copyright The Kubernetes Authors, Apache-2.0). + +package checkpoint + +import ( + "bytes" + "cmp" + "encoding/json" + "errors" + "fmt" + "hash/fnv" + "maps" + "reflect" + "slices" + "strconv" + + resourcev1 "k8s.io/api/resource/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/dump" + "k8s.io/klog/v2" + cdispec "tags.cncf.io/container-device-interface/specs-go" + + api "github.com/Project-HAMi/dra-lib/api/checkpoint/v1" +) + +// legacyFile is the union of the checksum-wrapped JSON layouts that DRA +// drivers wrote through the kubelet checkpointmanager: v1 claims as device +// lists (AMD, Ascend) or as claim objects (NVIDIA), and NVIDIA's v2. +type legacyFile struct { + V1 *struct { + PreparedClaims map[string]json.RawMessage `json:"preparedClaims"` + ActiveMemoryMode string `json:"activeMemoryMode"` + GPUComputeModes map[int]string `json:"gpuComputeModes"` + MemoryReload *struct { + Mode string `json:"mode"` + TriggeredAtUnix int64 `json:"triggeredAtUnix"` + } `json:"memoryReload"` + AssignedSlots map[int]map[string]int32 `json:"assignedSlots"` + } `json:"v1"` + V2 *struct { + PreparedClaims map[string]legacyClaim `json:"preparedClaims"` + NodeBootID string `json:"nodeBootID"` + } `json:"v2"` +} + +type legacyListDevice struct { + RequestNames []string `json:"request_names"` + PoolName string `json:"pool_name"` + DeviceName string `json:"device_name"` + CDIDeviceIDs []string `json:"cdi_device_ids"` + ContainerEdits *cdispec.ContainerEdits `json:"ContainerEdits"` + PartitionSlot *int32 `json:"partitionSlot"` + ShareKey string `json:"shareKey"` + ComputeUnits []int32 `json:"computeUnits"` +} + +type legacyClaim struct { + CheckpointState string `json:"checkpointState"` + Status resourcev1.ResourceClaimStatus `json:"status"` + PreparedDevices []*struct { + Devices []struct { + HAMiGPU *legacyUUIDDevice `json:"hami-gpu"` + GPU *legacyUUIDDevice `json:"gpu"` + VFIO *legacyUUIDDevice `json:"vfio"` + MIG *struct { + Concrete *struct { + ParentMinor int32 `json:"parentMinor"` + GIID int32 `json:"giId"` + CIID int32 `json:"ciId"` + MIGUUID string `json:"migUUID"` + ParentUUID string `json:"parentUUID"` + } `json:"concrete"` + Device legacyDevice `json:"device"` + } `json:"mig"` + } `json:"devices"` + ConfigState struct { + MPSControlDaemonID string `json:"mpsControlDaemonID"` + } `json:"configState"` + } `json:"preparedDevices"` + Name string `json:"name"` + Namespace string `json:"namespace"` +} + +type legacyUUIDDevice struct { + Info *struct { + UUID string `json:"uuid"` + } `json:"info"` + Device legacyDevice `json:"device"` +} + +// legacyDevice is k8s.io/dynamic-resource-allocation/kubeletplugin.Device, +// which has no JSON tags. +type legacyDevice struct { + Requests []string + PoolName string + DeviceName string + CDIDeviceIDs []string +} + +func isLegacy(data []byte) bool { + var probe struct { + APIVersion string `json:"apiVersion"` + Checksum *json.RawMessage `json:"checksum"` + } + return json.Unmarshal(data, &probe) == nil && probe.APIVersion == "" && probe.Checksum != nil +} + +// migrateLegacy converts a legacy checkpoint and writes it in the current +// format. A legacy file with a bad checksum is an error and is not modified. +func (s *Store) migrateLegacy(data []byte) (*api.Checkpoint, error) { + checkpoint, err := readLegacy(data) + if err != nil { + return nil, fmt.Errorf("read legacy checkpoint %s: %w", s.path, err) + } + checkpoint.DriverName = s.driverName + klog.Warningf("Checkpoint %s is in the legacy kubelet checkpointmanager format, which is deprecated and will be removed in a future version; migrating it to %s/%s.", s.path, s.gvk.Group, "v1") + if err := s.Write(checkpoint); err != nil { + return nil, err + } + return checkpoint, nil +} + +func readLegacy(data []byte) (*api.Checkpoint, error) { + if err := verifyLegacyChecksums(data); err != nil { + return nil, err + } + var file legacyFile + if err := json.Unmarshal(data, &file); err != nil { + return nil, err + } + checkpoint := &api.Checkpoint{} + switch { + case file.V2 != nil: + checkpoint.NodeBootID = file.V2.NodeBootID + for _, uid := range slices.Sorted(maps.Keys(file.V2.PreparedClaims)) { + checkpoint.PreparedClaims = append(checkpoint.PreparedClaims, legacyClaimToAPI(uid, file.V2.PreparedClaims[uid], false)) + } + case file.V1 != nil: + v1 := file.V1 + for _, uid := range slices.Sorted(maps.Keys(v1.PreparedClaims)) { + claim, err := legacyV1ClaimToAPI(uid, v1.PreparedClaims[uid]) + if err != nil { + return nil, fmt.Errorf("claim %s: %w", uid, err) + } + checkpoint.PreparedClaims = append(checkpoint.PreparedClaims, claim) + } + partitioning := &api.NodePartitioning{} + if v1.ActiveMemoryMode != "" { + partitioning.Modes = append(partitioning.Modes, api.PartitionMode{Kind: api.PartitionModeKindMemory, Mode: v1.ActiveMemoryMode}) + } + for _, gpu := range slices.Sorted(maps.Keys(v1.GPUComputeModes)) { + partitioning.Modes = append(partitioning.Modes, api.PartitionMode{ + Device: strconv.Itoa(gpu), Kind: api.PartitionModeKindCompute, Mode: v1.GPUComputeModes[gpu], + }) + } + amd := &api.AMDNodePartitioning{} + if r := v1.MemoryReload; r != nil { + amd.MemoryReload = &api.AMDMemoryReload{Mode: r.Mode, TriggeredAt: metav1.Unix(r.TriggeredAtUnix, 0)} + } + for gpu, slots := range v1.AssignedSlots { + for key, slot := range slots { + amd.AssignedSlots = append(amd.AssignedSlots, api.AMDAssignedSlot{GPUIndex: int32(gpu), ShareKey: key, Slot: slot}) + } + } + slices.SortFunc(amd.AssignedSlots, func(a, b api.AMDAssignedSlot) int { + return cmp.Or(cmp.Compare(a.GPUIndex, b.GPUIndex), cmp.Compare(a.ShareKey, b.ShareKey)) + }) + if amd.MemoryReload != nil || amd.AssignedSlots != nil { + partitioning.AMD = amd + } + if partitioning.Modes != nil || partitioning.AMD != nil { + checkpoint.Partitioning = partitioning + } + } + return checkpoint, nil +} + +func legacyV1ClaimToAPI(uid string, raw json.RawMessage) (api.PreparedClaim, error) { + if raw = bytes.TrimSpace(raw); len(raw) > 0 && raw[0] == '{' { + var claim legacyClaim + if err := json.Unmarshal(raw, &claim); err != nil { + return api.PreparedClaim{}, err + } + return legacyClaimToAPI(uid, claim, true), nil + } + var devices []legacyListDevice + if err := json.Unmarshal(raw, &devices); err != nil { + return api.PreparedClaim{}, err + } + claim := api.PreparedClaim{UID: types.UID(uid)} + for _, d := range devices { + device := api.PreparedDevice{ + Device: api.Device{Requests: d.RequestNames, PoolName: d.PoolName, DeviceName: d.DeviceName, CDIDeviceIDs: d.CDIDeviceIDs}, + } + if d.ContainerEdits != nil { + device.ContainerEdits = &api.ContainerEdits{ContainerEdits: *d.ContainerEdits} + } + if d.PartitionSlot != nil || len(d.ComputeUnits) > 0 { + device.Partition = &api.Partition{Type: api.PartitionTypeSoft, AMD: &api.AMDPartition{Slot: d.PartitionSlot, ComputeUnits: d.ComputeUnits}} + if d.PartitionSlot != nil { + device.Partition.Type = api.PartitionTypeHard + } + } + if d.ShareKey != "" { + device.AMD = &api.AMDDevice{ShareKey: d.ShareKey} + } + claim.Devices = append(claim.Devices, device) + } + return claim, nil +} + +// legacyClaimToAPI converts an NVIDIA claim. v1 claims carry no state and +// were always completed. +func legacyClaimToAPI(uid string, c legacyClaim, v1 bool) api.PreparedClaim { + claim := api.PreparedClaim{ + UID: types.UID(uid), + Name: c.Name, + Namespace: c.Namespace, + State: api.PrepareState(c.CheckpointState), + } + if status := c.Status; !reflect.DeepEqual(status, resourcev1.ResourceClaimStatus{}) { + claim.Status = &status + } + if v1 { + claim.State = api.PrepareStateCompleted + } + for _, group := range c.PreparedDevices { + if group == nil { + continue + } + if claim.NVIDIA == nil { + claim.NVIDIA = &api.NVIDIAClaim{} + } + index := int32(len(claim.NVIDIA.Groups)) + claim.NVIDIA.Groups = append(claim.NVIDIA.Groups, api.NVIDIADeviceGroup{MPSControlDaemonID: group.ConfigState.MPSControlDaemonID}) + for _, d := range group.Devices { + nvidia := &api.NVIDIADevice{Group: index} + device := api.PreparedDevice{NVIDIA: nvidia} + uuidDevice := func(t api.NVIDIADeviceType, u *legacyUUIDDevice) { + nvidia.Type = t + if u.Info != nil { + nvidia.UUID = u.Info.UUID + } + device.Device = api.Device(u.Device) + } + switch { + case d.HAMiGPU != nil: + uuidDevice(api.NVIDIADeviceTypeGPU, d.HAMiGPU) + device.Partition = &api.Partition{Type: api.PartitionTypeSoft} + case d.GPU != nil: + uuidDevice(api.NVIDIADeviceTypeGPU, d.GPU) + case d.VFIO != nil: + uuidDevice(api.NVIDIADeviceTypeVFIO, d.VFIO) + case d.MIG != nil: + nvidia.Type = api.NVIDIADeviceTypeMIG + device.Device = api.Device(d.MIG.Device) + device.Partition = &api.Partition{Type: api.PartitionTypeHard} + if m := d.MIG.Concrete; m != nil { + device.Partition.ParentDevice = m.ParentUUID + device.Partition.NVIDIA = &api.NVIDIAPartition{ParentMinor: m.ParentMinor, GIID: m.GIID, CIID: m.CIID, MIGUUID: m.MIGUUID} + } + } + claim.Devices = append(claim.Devices, device) + } + } + return claim +} + +// verifyLegacyChecksums checks the checksums the checkpointmanager stored. +// Each covers the compact JSON of its object with the checksum set to 0; the +// top-level one excludes the separately checksummed v2 section. +func verifyLegacyChecksums(data []byte) error { + var compact bytes.Buffer + if err := json.Compact(&compact, data); err != nil { + return err + } + top, err := legacyMembers(compact.Bytes()) + if err != nil { + return err + } + var v2 json.RawMessage + outer := top[:0:0] + for _, m := range top { + if m.key == "v2" { + v2 = m.value + continue + } + outer = append(outer, m) + } + if err := verifyLegacyChecksum(outer); err != nil { + return err + } + if v2 == nil { + return nil + } + members, err := legacyMembers(v2) + if err != nil { + return err + } + if err := verifyLegacyChecksum(members); err != nil { + return fmt.Errorf("v2: %w", err) + } + return nil +} + +type legacyMember struct { + key string + value json.RawMessage +} + +// legacyMembers returns the members of a JSON object in file order. +func legacyMembers(object []byte) ([]legacyMember, error) { + dec := json.NewDecoder(bytes.NewReader(object)) + if tok, err := dec.Token(); err != nil || tok != json.Delim('{') { + return nil, errors.New("checkpoint is not a JSON object") + } + var members []legacyMember + for dec.More() { + tok, err := dec.Token() + if err != nil { + return nil, err + } + var value json.RawMessage + if err := dec.Decode(&value); err != nil { + return nil, err + } + members = append(members, legacyMember{key: tok.(string), value: value}) + } + return members, nil +} + +func verifyLegacyChecksum(members []legacyMember) error { + var buf bytes.Buffer + var expected *uint64 + buf.WriteByte('{') + for i, m := range members { + if i > 0 { + buf.WriteByte(',') + } + key, _ := json.Marshal(m.key) + buf.Write(key) + buf.WriteByte(':') + if m.key != "checksum" { + buf.Write(m.value) + continue + } + sum, err := strconv.ParseUint(string(m.value), 10, 64) + if err != nil { + return fmt.Errorf("checksum: %w", err) + } + expected = &sum + buf.WriteByte('0') + } + buf.WriteByte('}') + if expected == nil { + return errors.New("checkpoint has no checksum") + } + // FNV-32a over the spew dump, as checkpointmanager/checksum.New does. + hash := fnv.New32a() + _, _ = fmt.Fprintf(hash, "%v", dump.ForHash(buf.Bytes())) // hash.Hash.Write never fails + if actual := uint64(hash.Sum32()); actual != *expected { + return fmt.Errorf("checkpoint is corrupted: checksum %d, expected %d", actual, *expected) + } + return nil +} diff --git a/checkpoint/legacy_helper_test.go b/checkpoint/legacy_helper_test.go new file mode 100644 index 0000000..596e724 --- /dev/null +++ b/checkpoint/legacy_helper_test.go @@ -0,0 +1,85 @@ +/* +Copyright 2026 The HAMi Authors. + +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. +*/ + +package checkpoint + +import ( + "encoding/json" + "fmt" + "hash/fnv" + + "k8s.io/apimachinery/pkg/util/dump" + cdispec "tags.cncf.io/container-device-interface/specs-go" +) + +// legacyTestCheckpoint writes and reads the kubelet checkpointmanager format the +// way the drivers used it: the driver's v1 payload wrapped with a checksum, +// which is FNV-32a over the spew dump of the JSON marshalled with checksum 0. +// It is written independently of legacy.go so tests can check that reader. +type legacyTestCheckpoint struct { + Checksum uint64 `json:"checksum"` + V1 *legacyTestClaimsV1 `json:"v1,omitempty"` +} + +// legacyTestClaimsV1 is the AMD and Ascend payload: claims as device lists. +type legacyTestClaimsV1 struct { + PreparedClaims map[string][]*legacyTestDevice `json:"preparedClaims,omitempty"` +} + +type legacyTestDevice struct { + RequestNames []string `json:"request_names,omitempty"` + PoolName string `json:"pool_name,omitempty"` + DeviceName string `json:"device_name,omitempty"` + CDIDeviceIDs []string `json:"cdi_device_ids,omitempty"` + ContainerEdits *cdispec.ContainerEdits `json:"ContainerEdits"` +} + +func legacyTestChecksum(data []byte) uint64 { + hash := fnv.New32a() + _, _ = fmt.Fprintf(hash, "%v", dump.ForHash(data)) + return uint64(hash.Sum32()) +} + +// marshal returns the checkpoint with its checksum set, as checkpointmanager +// CreateCheckpoint does: marshal with checksum 0, hash, marshal again. +func (cp *legacyTestCheckpoint) marshal() ([]byte, error) { + cp.Checksum = 0 + out, err := json.Marshal(cp) + if err != nil { + return nil, err + } + cp.Checksum = legacyTestChecksum(out) + return json.Marshal(cp) +} + +// unmarshal reads data and verifies its checksum, as checkpointmanager +// GetCheckpoint does. +func (cp *legacyTestCheckpoint) unmarshal(data []byte) error { + if err := json.Unmarshal(data, cp); err != nil { + return err + } + sum := cp.Checksum + cp.Checksum = 0 + out, err := json.Marshal(cp) + cp.Checksum = sum + if err != nil { + return err + } + if legacyTestChecksum(out) != sum { + return fmt.Errorf("checksum mismatch") + } + return nil +} diff --git a/checkpoint/store.go b/checkpoint/store.go new file mode 100644 index 0000000..4d03b4e --- /dev/null +++ b/checkpoint/store.go @@ -0,0 +1,187 @@ +/* +Copyright 2026 The HAMi Authors. + +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. +*/ + +// Package checkpoint reads and writes DRA kubelet plugin checkpoints as +// versioned Kubernetes API objects. +package checkpoint + +import ( + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/runtime/serializer" + "k8s.io/apimachinery/pkg/runtime/serializer/json" + + "github.com/Project-HAMi/dra-lib/api/checkpoint/install" + api "github.com/Project-HAMi/dra-lib/api/checkpoint/v1" +) + +// Options configure a Store. +type Options struct { + // Group is the API group of the checkpoint, e.g. + // checkpoint.internal.example.com. + Group string + // DriverName is the DRA driver that owns the checkpoint. Reading a + // checkpoint of another driver fails. + DriverName string +} + +// Store reads and writes the checkpoint file at one path. +type Store struct { + path string + driverName string + gvk schema.GroupVersionKind + decoder runtime.Decoder + encoder runtime.Encoder +} + +func NewStore(path string, opts Options) (*Store, error) { + if opts.Group == "" || opts.DriverName == "" { + return nil, errors.New("checkpoint store needs a group and a driver name") + } + scheme := install.NewScheme(opts.Group) + // Checkpoints are only read and written by the driver, so strict decoding + // would catch little; performance is the better trade-off. + serializerJSON := json.NewSerializerWithOptions(json.DefaultMetaFactory, scheme, scheme, + json.SerializerOptions{Pretty: false, Strict: false}) + codecs := serializer.NewCodecFactory(scheme) + versioned := schema.GroupVersion{Group: opts.Group, Version: api.Version} + return &Store{ + path: path, + driverName: opts.DriverName, + // A file without apiVersion is read as v1. + gvk: versioned.WithKind(api.Kind), + decoder: codecs.UniversalDecoder(versioned), + encoder: codecs.EncoderForVersion(serializerJSON, versioned), + }, nil +} + +// Read returns the checkpoint. A missing file is an empty checkpoint. A +// checkpoint in the legacy kubelet checkpointmanager format is migrated and +// written back in the current format. +// +// The store keeps no cache: every Read and Update reads the file, so the +// caller only needs to hold its own lock around them. +func (s *Store) Read() (*api.Checkpoint, error) { + data, err := os.ReadFile(s.path) + if errors.Is(err, fs.ErrNotExist) { + return &api.Checkpoint{DriverName: s.driverName}, nil + } + if err != nil { + return nil, err + } + if isLegacy(data) { + return s.migrateLegacy(data) + } + checkpoint, err := s.decode(data) + if err != nil { + return nil, fmt.Errorf("decode checkpoint %s: %w", s.path, err) + } + if checkpoint.DriverName != s.driverName { + return nil, fmt.Errorf("checkpoint %s has driverName %q, expected %q", s.path, checkpoint.DriverName, s.driverName) + } + return checkpoint, nil +} + +// decode decodes a checkpoint in the current format. The returned object has no +// TypeMeta; the store sets it when writing. +func (s *Store) decode(data []byte) (*api.Checkpoint, error) { + checkpoint := new(api.Checkpoint) + gvk := s.gvk + if _, _, err := s.decoder.Decode(data, &gvk, checkpoint); err != nil { + return nil, err + } + checkpoint.TypeMeta = metav1.TypeMeta{} + return checkpoint, nil +} + +// Update reads the checkpoint, applies mutate and writes the result once, so a +// driver can record all claims of one kubelet call with one write. Nothing is +// written if mutate returns an error. +func (s *Store) Update(mutate func(*api.Checkpoint) error) error { + checkpoint, err := s.Read() + if err != nil { + return err + } + if err := mutate(checkpoint); err != nil { + return err + } + return s.Write(checkpoint) +} + +// Write atomically replaces the checkpoint file: it writes a temp file in the +// same directory, syncs it, renames it over the checkpoint and syncs the +// directory. An empty DriverName is set to the store's driver. +func (s *Store) Write(checkpoint *api.Checkpoint) (err error) { + switch checkpoint.DriverName { + case "": + checkpoint.DriverName = s.driverName + case s.driverName: + default: + return fmt.Errorf("checkpoint has driverName %q, expected %q", checkpoint.DriverName, s.driverName) + } + dir := filepath.Dir(s.path) + tmp, err := os.CreateTemp(dir, "tmp-checkpoint-*") + if err != nil { + return fmt.Errorf("create temp file in %s: %w", dir, err) + } + defer func() { + if err1 := tmp.Close(); err1 != nil && !errors.Is(err1, fs.ErrClosed) && err == nil { + err = fmt.Errorf("close temp file: %w", err1) + } + if err != nil { + _ = os.Remove(tmp.Name()) + } + }() + if err := s.encoder.Encode(checkpoint, tmp); err != nil { + return fmt.Errorf("encode to temp file %s: %w", tmp.Name(), err) + } + if err := tmp.Sync(); err != nil { + return fmt.Errorf("sync temp file: %w", err) + } + if err := tmp.Close(); err != nil { + return fmt.Errorf("close temp file: %w", err) + } + if err := os.Rename(tmp.Name(), s.path); err != nil { + return fmt.Errorf("rename %s to %s: %w", tmp.Name(), s.path, err) + } + // The new content is visible now; an error here means the rename may + // not survive a power loss. + if err := syncDir(dir); err != nil { + return fmt.Errorf("sync directory %s: %w", dir, err) + } + return nil +} + +// syncDir fsyncs a directory so a rename in it is durable. A variable so +// tests can observe it. +var syncDir = func(dir string) error { + d, err := os.Open(dir) + if err != nil { + return err + } + if err := d.Sync(); err != nil { + _ = d.Close() + return err + } + return d.Close() +} diff --git a/checkpoint/store_test.go b/checkpoint/store_test.go new file mode 100644 index 0000000..303ce0e --- /dev/null +++ b/checkpoint/store_test.go @@ -0,0 +1,444 @@ +/* +Copyright 2026 The HAMi Authors. + +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. +*/ + +package checkpoint + +import ( + "bytes" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + resourcev1 "k8s.io/api/resource/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/utils/ptr" + cdispec "tags.cncf.io/container-device-interface/specs-go" + + api "github.com/Project-HAMi/dra-lib/api/checkpoint/v1" +) + +const ( + testGroup = "checkpoint.internal.example.com" + testDriver = "gpu.example.com" +) + +func newTestStore(t *testing.T) (*Store, string) { + t.Helper() + path := filepath.Join(t.TempDir(), "checkpoint.json") + s, err := NewStore(path, Options{Group: testGroup, DriverName: testDriver}) + require.NoError(t, err) + return s, path +} + +func sampleCheckpoint() *api.Checkpoint { + return &api.Checkpoint{ + DriverName: testDriver, + NodeBootID: "boot-1", + Partitioning: &api.NodePartitioning{ + Modes: []api.PartitionMode{{Kind: api.PartitionModeKindMemory, Mode: "nps4"}}, + }, + PreparedClaims: []api.PreparedClaim{{ + UID: "uid-1", + State: api.PrepareStateCompleted, + Devices: []api.PreparedDevice{{ + Device: api.Device{Requests: []string{"gpu"}, PoolName: "node-a", DeviceName: "gpu-0", CDIDeviceIDs: []string{"example.com/gpu=uid-1-gpu-0"}}, + ContainerEdits: &api.ContainerEdits{ContainerEdits: cdispec.ContainerEdits{Env: []string{"A=1"}}}, + Partition: &api.Partition{Type: api.PartitionTypeSoft, Cores: ptr.To[int32](50)}, + }}, + }}, + } +} + +func TestReadMissingFile(t *testing.T) { + s, path := newTestStore(t) + cp, err := s.Read() + require.NoError(t, err) + assert.Equal(t, &api.Checkpoint{DriverName: testDriver}, cp) + assert.NoFileExists(t, path) +} + +func TestWriteReadRoundTrip(t *testing.T) { + s, path := newTestStore(t) + want := sampleCheckpoint() + require.NoError(t, s.Write(want)) + data, err := os.ReadFile(path) + require.NoError(t, err) + assert.Contains(t, string(data), `"apiVersion":"`+testGroup+`/v1"`) + assert.Contains(t, string(data), `"kind":"Checkpoint"`) + got, err := s.Read() + require.NoError(t, err) + assert.Equal(t, want, got) + + entries, err := os.ReadDir(filepath.Dir(path)) + require.NoError(t, err) + assert.Len(t, entries, 1, "temp files must not be left behind") +} + +func TestWriteIsCompact(t *testing.T) { + s, path := newTestStore(t) + require.NoError(t, s.Write(sampleCheckpoint())) + data, err := os.ReadFile(path) + require.NoError(t, err) + assert.NotContains(t, strings.TrimSuffix(string(data), "\n"), "\n", "checkpoint must be written on a single line") +} + +func TestWriteSetsDriverName(t *testing.T) { + s, _ := newTestStore(t) + cp := sampleCheckpoint() + cp.DriverName = "" + require.NoError(t, s.Write(cp)) + got, err := s.Read() + require.NoError(t, err) + assert.Equal(t, testDriver, got.DriverName) +} + +func TestWriteRejectsOtherDriver(t *testing.T) { + s, path := newTestStore(t) + cp := sampleCheckpoint() + cp.DriverName = "other.example.com" + assert.ErrorContains(t, s.Write(cp), "other.example.com") + assert.NoFileExists(t, path) +} + +func TestReadRejectsOtherDriver(t *testing.T) { + s, path := newTestStore(t) + require.NoError(t, s.Write(sampleCheckpoint())) + other, err := NewStore(path, Options{Group: testGroup, DriverName: "other.example.com"}) + require.NoError(t, err) + _, err = other.Read() + assert.ErrorContains(t, err, testDriver) + assert.ErrorContains(t, err, "other.example.com") +} + +func TestReadRejectsMissingDriverName(t *testing.T) { + s, path := newTestStore(t) + require.NoError(t, os.WriteFile(path, []byte(`{"apiVersion":"`+testGroup+`/v1","kind":"Checkpoint"}`), 0o600)) + _, err := s.Read() + assert.ErrorContains(t, err, "driverName") +} + +func TestReadRejectsOtherGroup(t *testing.T) { + s, path := newTestStore(t) + require.NoError(t, os.WriteFile(path, []byte(`{"apiVersion":"checkpoint.internal.other.com/v1","kind":"Checkpoint","driverName":"`+testDriver+`"}`), 0o600)) + _, err := s.Read() + assert.Error(t, err) +} + +func TestReadCorrupt(t *testing.T) { + s, path := newTestStore(t) + require.NoError(t, os.WriteFile(path, []byte(`{"apiVersion":"`+testGroup+`/v1","kind":"Checkpoint","preparedClaims":`), 0o600)) + _, err := s.Read() + assert.Error(t, err) +} + +func TestNewStoreValidatesOptions(t *testing.T) { + _, err := NewStore("checkpoint.json", Options{DriverName: testDriver}) + assert.Error(t, err) + _, err = NewStore("checkpoint.json", Options{Group: testGroup}) + assert.Error(t, err) +} + +func amdLegacyCheckpoint() *api.Checkpoint { + return &api.Checkpoint{ + DriverName: testDriver, + Partitioning: &api.NodePartitioning{ + Modes: []api.PartitionMode{ + {Kind: api.PartitionModeKindMemory, Mode: "nps4"}, + {Device: "0", Kind: api.PartitionModeKindCompute, Mode: "spx"}, + {Device: "1", Kind: api.PartitionModeKindCompute, Mode: "cpx"}, + }, + AMD: &api.AMDNodePartitioning{ + MemoryReload: &api.AMDMemoryReload{Mode: "nps4", TriggeredAt: metav1.Unix(1764460800, 0)}, + AssignedSlots: []api.AMDAssignedSlot{{GPUIndex: 1, ShareKey: "claim-uid-1/part/gpu-1-cpx-nps4-0/", Slot: 1}}, + }, + }, + PreparedClaims: []api.PreparedClaim{{ + UID: "claim-uid-1", + Devices: []api.PreparedDevice{ + { + Device: api.Device{Requests: []string{"gpu"}, PoolName: "node-a", DeviceName: "gpu-0-129", CDIDeviceIDs: []string{"amd.com/gpu=claim-uid-1-gpu-0-129"}}, + ContainerEdits: &api.ContainerEdits{ContainerEdits: cdispec.ContainerEdits{ + Env: []string{"AMD_VISIBLE_DEVICES=0"}, + DeviceNodes: []*cdispec.DeviceNode{{Path: "/dev/dri/renderD128"}}, + Mounts: []*cdispec.Mount{{HostPath: "/opt/hook", ContainerPath: "/opt/hook", Options: []string{"ro", "bind"}}}, + }}, + Partition: &api.Partition{Type: api.PartitionTypeSoft, AMD: &api.AMDPartition{ComputeUnits: []int32{0, 1, 2, 3}}}, + AMD: &api.AMDDevice{ShareKey: "claim-uid-1/gpu/gpu-0-129/"}, + }, + { + Device: api.Device{Requests: []string{"part"}, PoolName: "node-a", DeviceName: "gpu-1-cpx-nps4-0", CDIDeviceIDs: []string{"amd.com/gpu=claim-uid-1-gpu-1-cpx-nps4-0-1"}}, + Partition: &api.Partition{Type: api.PartitionTypeHard, AMD: &api.AMDPartition{Slot: ptr.To[int32](1)}}, + AMD: &api.AMDDevice{ShareKey: "claim-uid-1/part/gpu-1-cpx-nps4-0/"}, + }, + }, + }}, + } +} + +func ascendLegacyCheckpoint() *api.Checkpoint { + return &api.Checkpoint{ + DriverName: testDriver, + PreparedClaims: []api.PreparedClaim{ + {UID: "claim-uid-1", Devices: []api.PreparedDevice{ + { + Device: api.Device{Requests: []string{"npu"}, PoolName: "node-a", DeviceName: "npu-0", CDIDeviceIDs: []string{"ascend.project-hami.io/npu=claim-uid-1-npu-0"}}, + ContainerEdits: &api.ContainerEdits{ContainerEdits: cdispec.ContainerEdits{ + Env: []string{"ASCEND_VISIBLE_DEVICES=0"}, + DeviceNodes: []*cdispec.DeviceNode{{Path: "/dev/davinci0"}}, + }}, + }, + {Device: api.Device{Requests: []string{"vnpu"}, PoolName: "node-a", DeviceName: "npu-1-vir02", CDIDeviceIDs: []string{"ascend.project-hami.io/npu=claim-uid-1-npu-1-vir02"}}}, + }}, + {UID: "claim-uid-2", Devices: []api.PreparedDevice{{Device: api.Device{PoolName: "node-a", DeviceName: "npu-2"}}}}, + }, + } +} + +func nvidiaLegacyCheckpoint() *api.Checkpoint { + dev := func(req, name string) api.Device { + return api.Device{Requests: []string{req}, PoolName: "node-a", DeviceName: name, CDIDeviceIDs: []string{"k8s.gpu.nvidia.com/device=" + name}} + } + return &api.Checkpoint{ + DriverName: testDriver, + NodeBootID: "boot-id-1", + PreparedClaims: []api.PreparedClaim{ + { + UID: "claim-uid-1", + Name: "claim-1", + Namespace: "default", + State: api.PrepareStateCompleted, + Status: &resourcev1.ResourceClaimStatus{Allocation: &resourcev1.AllocationResult{Devices: resourcev1.DeviceAllocationResult{ + Results: []resourcev1.DeviceRequestAllocationResult{{Request: "gpu", Driver: "hami-core-gpu.project-hami.io", Pool: "node-a", Device: "gpu-0"}}, + }}}, + Devices: []api.PreparedDevice{ + {Device: dev("hami", "hami-gpu-1"), Partition: &api.Partition{Type: api.PartitionTypeSoft}, NVIDIA: &api.NVIDIADevice{Group: 0, Type: api.NVIDIADeviceTypeGPU, UUID: "GPU-bbbb"}}, + {Device: dev("gpu", "gpu-0"), NVIDIA: &api.NVIDIADevice{Group: 0, Type: api.NVIDIADeviceTypeGPU, UUID: "GPU-aaaa"}}, + { + Device: dev("mig", "gpu-1-mig-1g10gb-2"), + Partition: &api.Partition{Type: api.PartitionTypeHard, ParentDevice: "GPU-dddd", + NVIDIA: &api.NVIDIAPartition{ParentMinor: 1, GIID: 2, CIID: 0, MIGUUID: "MIG-cccc"}}, + NVIDIA: &api.NVIDIADevice{Group: 1, Type: api.NVIDIADeviceTypeMIG}, + }, + {Device: dev("vfio", "gpu-3-vfio"), NVIDIA: &api.NVIDIADevice{Group: 1, Type: api.NVIDIADeviceTypeVFIO, UUID: "GPU-eeee"}}, + }, + NVIDIA: &api.NVIDIAClaim{Groups: []api.NVIDIADeviceGroup{{}, {MPSControlDaemonID: "mps-claim-uid-1"}}}, + }, + {UID: "claim-uid-2", Name: "claim-2", Namespace: "team-a", State: api.PrepareStateStarted}, + }, + } +} + +// nvidiaV1LegacyCheckpoint is the oldest format: completed claims only, no +// names or boot ID. +func nvidiaV1LegacyCheckpoint() *api.Checkpoint { + cp := nvidiaLegacyCheckpoint() + claim := cp.PreparedClaims[0] + claim.Name, claim.Namespace = "", "" + return &api.Checkpoint{DriverName: testDriver, PreparedClaims: []api.PreparedClaim{claim}} +} + +func TestReadMigratesLegacy(t *testing.T) { + for fixture, want := range map[string]*api.Checkpoint{ + "testdata/legacy-amd.json": amdLegacyCheckpoint(), + "testdata/legacy-ascend.json": ascendLegacyCheckpoint(), + "testdata/legacy-nvidia.json": nvidiaLegacyCheckpoint(), + "testdata/legacy-nvidia-v1.json": nvidiaV1LegacyCheckpoint(), + } { + t.Run(filepath.Base(fixture), func(t *testing.T) { + legacy, err := os.ReadFile(fixture) + require.NoError(t, err) + s, path := newTestStore(t) + require.NoError(t, os.WriteFile(path, legacy, 0o600)) + + got, err := s.Read() + require.NoError(t, err) + assert.Equal(t, want, got) + migrated, err := os.ReadFile(path) + require.NoError(t, err) + assert.Contains(t, string(migrated), `"apiVersion":"`+testGroup+`/v1"`) + assert.NotContains(t, string(migrated), `"checksum"`) + + // Second run reads the new format and leaves the file alone. + got, err = s.Read() + require.NoError(t, err) + assert.Equal(t, want, got) + again, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, migrated, again) + }) + } +} + +func TestReadLegacyBadChecksum(t *testing.T) { + for fixture, tamper := range map[string][2]string{ + "testdata/legacy-amd.json": {`"activeMemoryMode":"nps4"`, `"activeMemoryMode":"nps1"`}, + "testdata/legacy-ascend.json": {`"device_name":"npu-2"`, `"device_name":"npu-3"`}, + "testdata/legacy-nvidia.json": {`"nodeBootID":"boot-id-1"`, `"nodeBootID":"boot-id-2"`}, // v2 checksum only + "testdata/legacy-nvidia-v1.json": {`"giId":2`, `"giId":3`}, + } { + t.Run(filepath.Base(fixture), func(t *testing.T) { + legacy, err := os.ReadFile(fixture) + require.NoError(t, err) + tampered := []byte(strings.Replace(string(legacy), tamper[0], tamper[1], 1)) + require.NotEqual(t, legacy, tampered) + s, path := newTestStore(t) + require.NoError(t, os.WriteFile(path, tampered, 0o600)) + + _, err = s.Read() + assert.ErrorContains(t, err, "checksum") + after, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, tampered, after, "a corrupt legacy checkpoint must not be overwritten") + }) + } +} + +func TestUpdateAppliesAllChangesInOneWrite(t *testing.T) { + s, path := newTestStore(t) + require.NoError(t, s.Write(sampleCheckpoint())) + + require.NoError(t, s.Update(func(cp *api.Checkpoint) error { + cp.PreparedClaims = append(cp.PreparedClaims, api.PreparedClaim{UID: "uid-2"}, api.PreparedClaim{UID: "uid-3"}) + cp.PreparedClaims = cp.PreparedClaims[1:] + return nil + })) + got, err := s.Read() + require.NoError(t, err) + assert.Equal(t, []api.PreparedClaim{{UID: "uid-2"}, {UID: "uid-3"}}, got.PreparedClaims) + + before, err := os.ReadFile(path) + require.NoError(t, err) + assert.ErrorContains(t, s.Update(func(cp *api.Checkpoint) error { + cp.PreparedClaims = nil + return errors.New("prepare failed") + }), "prepare failed") + after, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, before, after, "a failed update must not write") +} + +func TestReadSeesChangesFromOtherWriters(t *testing.T) { + s, path := newTestStore(t) + require.NoError(t, s.Write(sampleCheckpoint())) + _, err := s.Read() + require.NoError(t, err) + + other, err := NewStore(path, Options{Group: testGroup, DriverName: testDriver}) + require.NoError(t, err) + require.NoError(t, other.Write(&api.Checkpoint{NodeBootID: "boot-2"})) + + got, err := s.Read() + require.NoError(t, err) + assert.Equal(t, "boot-2", got.NodeBootID) + require.NoError(t, s.Update(func(cp *api.Checkpoint) error { + assert.Equal(t, "boot-2", cp.NodeBootID) + return nil + })) +} + +func TestWriteSyncsDirectoryAfterRename(t *testing.T) { + s, path := newTestStore(t) + var synced []string + orig := syncDir + t.Cleanup(func() { syncDir = orig }) + syncDir = func(dir string) error { + data, err := os.ReadFile(path) + require.NoError(t, err, "the directory is synced after the rename") + assert.Contains(t, string(data), `"driverName":"`+testDriver+`"`) + synced = append(synced, dir) + return orig(dir) + } + require.NoError(t, s.Write(sampleCheckpoint())) + assert.Equal(t, []string{filepath.Dir(path)}, synced) + + syncDir = func(string) error { return errors.New("injected sync failure") } + assert.ErrorContains(t, s.Write(sampleCheckpoint()), "injected sync failure") +} + +// testdata/v1-checkpoint.json was written before the internal API version was +// removed; it must decode unchanged and be written back byte for byte. +func TestV1FileFromBeforeInternalVersionRemoval(t *testing.T) { + want := nvidiaLegacyCheckpoint() + amd := amdLegacyCheckpoint() + want.Partitioning = amd.Partitioning + want.PreparedClaims = append(want.PreparedClaims, amd.PreparedClaims...) + want.PreparedClaims[2].UID = "claim-uid-3" + + data, err := os.ReadFile("testdata/v1-checkpoint.json") + require.NoError(t, err) + s, path := newTestStore(t) + require.NoError(t, os.WriteFile(path, data, 0o600)) + got, err := s.Read() + require.NoError(t, err) + assert.Equal(t, want, got) + + require.NoError(t, s.Write(got)) + written, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, string(data), string(written)) +} + +// helperLegacyCheckpoint is a device-list (AMD, Ascend) legacy checkpoint +// written with the test helper, and what it migrates to. +func helperLegacyCheckpoint(t *testing.T) ([]byte, *api.Checkpoint) { + t.Helper() + edits := cdispec.ContainerEdits{Env: []string{"A=1"}, DeviceNodes: []*cdispec.DeviceNode{{Path: "/dev/kfd"}}} + legacy := &legacyTestCheckpoint{V1: &legacyTestClaimsV1{PreparedClaims: map[string][]*legacyTestDevice{ + "uid-b": {{PoolName: "node-a", DeviceName: "gpu-1"}}, + "uid-a": {{RequestNames: []string{"gpu"}, PoolName: "node-a", DeviceName: "gpu-0", CDIDeviceIDs: []string{"example.com/gpu=uid-a"}, ContainerEdits: &edits}}, + }}} + data, err := legacy.marshal() + require.NoError(t, err) + return data, &api.Checkpoint{ + DriverName: testDriver, + PreparedClaims: []api.PreparedClaim{ + {UID: "uid-a", Devices: []api.PreparedDevice{{ + Device: api.Device{Requests: []string{"gpu"}, PoolName: "node-a", DeviceName: "gpu-0", CDIDeviceIDs: []string{"example.com/gpu=uid-a"}}, + ContainerEdits: &api.ContainerEdits{ContainerEdits: edits}, + }}}, + {UID: "uid-b", Devices: []api.PreparedDevice{{Device: api.Device{PoolName: "node-a", DeviceName: "gpu-1"}}}}, + }, + } +} + +func TestReadMigratesHelperLegacy(t *testing.T) { + data, want := helperLegacyCheckpoint(t) + s, path := newTestStore(t) + require.NoError(t, os.WriteFile(path, data, 0o600)) + got, err := s.Read() + require.NoError(t, err) + assert.Equal(t, want, got) +} + +func TestReadRejectsHelperLegacyWithBadChecksum(t *testing.T) { + data, _ := helperLegacyCheckpoint(t) + var cp legacyTestCheckpoint + require.NoError(t, cp.unmarshal(data)) + tampered := bytes.Replace(data, []byte(fmt.Sprintf(`"checksum":%d`, cp.Checksum)), []byte(fmt.Sprintf(`"checksum":%d`, cp.Checksum+1)), 1) + require.NotEqual(t, data, tampered) + s, path := newTestStore(t) + require.NoError(t, os.WriteFile(path, tampered, 0o600)) + _, err := s.Read() + assert.ErrorContains(t, err, "checksum") + after, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, tampered, after) +} diff --git a/checkpoint/testdata/fuzz/FuzzDecodeV1/0aa010a38fddf57f b/checkpoint/testdata/fuzz/FuzzDecodeV1/0aa010a38fddf57f new file mode 100644 index 0000000..28886ae --- /dev/null +++ b/checkpoint/testdata/fuzz/FuzzDecodeV1/0aa010a38fddf57f @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("{\"kind\":\"Checkpoint\"} ") diff --git a/checkpoint/testdata/legacy-amd.json b/checkpoint/testdata/legacy-amd.json new file mode 100644 index 0000000..6d59cfe --- /dev/null +++ b/checkpoint/testdata/legacy-amd.json @@ -0,0 +1 @@ +{"checksum":1306749467,"v1":{"preparedClaims":{"claim-uid-1":[{"request_names":["gpu"],"pool_name":"node-a","device_name":"gpu-0-129","cdi_device_ids":["amd.com/gpu=claim-uid-1-gpu-0-129"],"ContainerEdits":{"env":["AMD_VISIBLE_DEVICES=0"],"deviceNodes":[{"path":"/dev/dri/renderD128"}],"mounts":[{"hostPath":"/opt/hook","containerPath":"/opt/hook","options":["ro","bind"]}]},"shareKey":"claim-uid-1/gpu/gpu-0-129/","computeUnits":[0,1,2,3]},{"request_names":["part"],"pool_name":"node-a","device_name":"gpu-1-cpx-nps4-0","cdi_device_ids":["amd.com/gpu=claim-uid-1-gpu-1-cpx-nps4-0-1"],"ContainerEdits":null,"partitionSlot":1,"shareKey":"claim-uid-1/part/gpu-1-cpx-nps4-0/"}]},"activeMemoryMode":"nps4","gpuComputeModes":{"0":"spx","1":"cpx"},"memoryReload":{"mode":"nps4","triggeredAtUnix":1764460800},"assignedSlots":{"1":{"claim-uid-1/part/gpu-1-cpx-nps4-0/":1}}}} \ No newline at end of file diff --git a/checkpoint/testdata/legacy-ascend.json b/checkpoint/testdata/legacy-ascend.json new file mode 100644 index 0000000..ae4e644 --- /dev/null +++ b/checkpoint/testdata/legacy-ascend.json @@ -0,0 +1 @@ +{"checksum":143782451,"v1":{"preparedClaims":{"claim-uid-1":[{"request_names":["npu"],"pool_name":"node-a","device_name":"npu-0","cdi_device_ids":["ascend.project-hami.io/npu=claim-uid-1-npu-0"],"ContainerEdits":{"env":["ASCEND_VISIBLE_DEVICES=0"],"deviceNodes":[{"path":"/dev/davinci0"}]}},{"request_names":["vnpu"],"pool_name":"node-a","device_name":"npu-1-vir02","cdi_device_ids":["ascend.project-hami.io/npu=claim-uid-1-npu-1-vir02"],"ContainerEdits":null}],"claim-uid-2":[{"pool_name":"node-a","device_name":"npu-2","ContainerEdits":null}]}}} \ No newline at end of file diff --git a/checkpoint/testdata/legacy-nvidia-v1.json b/checkpoint/testdata/legacy-nvidia-v1.json new file mode 100644 index 0000000..f3750bb --- /dev/null +++ b/checkpoint/testdata/legacy-nvidia-v1.json @@ -0,0 +1 @@ +{"checksum":2232786024,"v1":{"preparedClaims":{"claim-uid-1":{"status":{"allocation":{"devices":{"results":[{"request":"gpu","driver":"hami-core-gpu.project-hami.io","pool":"node-a","device":"gpu-0"}]}}},"preparedDevices":[{"devices":[{"hami-gpu":{"info":{"uuid":"GPU-bbbb"},"device":{"Requests":["hami"],"PoolName":"node-a","DeviceName":"hami-gpu-1","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=hami-gpu-1"]}},"gpu":null,"mig":null},{"hami-gpu":null,"gpu":{"info":{"uuid":"GPU-aaaa"},"device":{"Requests":["gpu"],"PoolName":"node-a","DeviceName":"gpu-0","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-0"]}},"mig":null}],"configState":{"mpsControlDaemonID":""}},{"devices":[{"hami-gpu":null,"gpu":null,"mig":{"concrete":{"parentMinor":1,"giId":2,"ciId":0,"migUUID":"MIG-cccc","parentUUID":"GPU-dddd"},"device":{"Requests":["mig"],"PoolName":"node-a","DeviceName":"gpu-1-mig-1g10gb-2","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-1-mig-1g10gb-2"]}}},{"hami-gpu":null,"gpu":null,"mig":null,"vfio":{"info":{"uuid":"GPU-eeee"},"device":{"Requests":["vfio"],"PoolName":"node-a","DeviceName":"gpu-3-vfio","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-3-vfio"]}}}],"configState":{"mpsControlDaemonID":"mps-claim-uid-1"}}]}}}} \ No newline at end of file diff --git a/checkpoint/testdata/legacy-nvidia.json b/checkpoint/testdata/legacy-nvidia.json new file mode 100644 index 0000000..acceeee --- /dev/null +++ b/checkpoint/testdata/legacy-nvidia.json @@ -0,0 +1 @@ +{"checksum":2232786024,"v1":{"preparedClaims":{"claim-uid-1":{"status":{"allocation":{"devices":{"results":[{"request":"gpu","driver":"hami-core-gpu.project-hami.io","pool":"node-a","device":"gpu-0"}]}}},"preparedDevices":[{"devices":[{"hami-gpu":{"info":{"uuid":"GPU-bbbb"},"device":{"Requests":["hami"],"PoolName":"node-a","DeviceName":"hami-gpu-1","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=hami-gpu-1"]}},"gpu":null,"mig":null},{"hami-gpu":null,"gpu":{"info":{"uuid":"GPU-aaaa"},"device":{"Requests":["gpu"],"PoolName":"node-a","DeviceName":"gpu-0","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-0"]}},"mig":null}],"configState":{"mpsControlDaemonID":""}},{"devices":[{"hami-gpu":null,"gpu":null,"mig":{"concrete":{"parentMinor":1,"giId":2,"ciId":0,"migUUID":"MIG-cccc","parentUUID":"GPU-dddd"},"device":{"Requests":["mig"],"PoolName":"node-a","DeviceName":"gpu-1-mig-1g10gb-2","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-1-mig-1g10gb-2"]}}},{"hami-gpu":null,"gpu":null,"mig":null,"vfio":{"info":{"uuid":"GPU-eeee"},"device":{"Requests":["vfio"],"PoolName":"node-a","DeviceName":"gpu-3-vfio","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-3-vfio"]}}}],"configState":{"mpsControlDaemonID":"mps-claim-uid-1"}}]}}},"v2":{"checksum":1760879644,"preparedClaims":{"claim-uid-1":{"checkpointState":"PrepareCompleted","status":{"allocation":{"devices":{"results":[{"request":"gpu","driver":"hami-core-gpu.project-hami.io","pool":"node-a","device":"gpu-0"}]}}},"preparedDevices":[{"devices":[{"hami-gpu":{"info":{"uuid":"GPU-bbbb"},"device":{"Requests":["hami"],"PoolName":"node-a","DeviceName":"hami-gpu-1","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=hami-gpu-1"]}},"gpu":null,"mig":null},{"hami-gpu":null,"gpu":{"info":{"uuid":"GPU-aaaa"},"device":{"Requests":["gpu"],"PoolName":"node-a","DeviceName":"gpu-0","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-0"]}},"mig":null}],"configState":{"mpsControlDaemonID":""}},{"devices":[{"hami-gpu":null,"gpu":null,"mig":{"concrete":{"parentMinor":1,"giId":2,"ciId":0,"migUUID":"MIG-cccc","parentUUID":"GPU-dddd"},"device":{"Requests":["mig"],"PoolName":"node-a","DeviceName":"gpu-1-mig-1g10gb-2","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-1-mig-1g10gb-2"]}}},{"hami-gpu":null,"gpu":null,"mig":null,"vfio":{"info":{"uuid":"GPU-eeee"},"device":{"Requests":["vfio"],"PoolName":"node-a","DeviceName":"gpu-3-vfio","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-3-vfio"]}}}],"configState":{"mpsControlDaemonID":"mps-claim-uid-1"}}],"name":"claim-1","namespace":"default"},"claim-uid-2":{"checkpointState":"PrepareStarted","status":{},"name":"claim-2","namespace":"team-a"}},"nodeBootID":"boot-id-1"}} \ No newline at end of file diff --git a/checkpoint/testdata/v1-checkpoint.json b/checkpoint/testdata/v1-checkpoint.json new file mode 100644 index 0000000..ee43235 --- /dev/null +++ b/checkpoint/testdata/v1-checkpoint.json @@ -0,0 +1 @@ +{"kind":"Checkpoint","apiVersion":"checkpoint.internal.example.com/v1","driverName":"gpu.example.com","nodeBootID":"boot-id-1","partitioning":{"modes":[{"kind":"memory","mode":"nps4"},{"device":"0","kind":"compute","mode":"spx"},{"device":"1","kind":"compute","mode":"cpx"}],"amd":{"memoryReload":{"mode":"nps4","triggeredAt":"2025-11-30T00:00:00Z"},"assignedSlots":[{"gpuIndex":1,"shareKey":"claim-uid-1/part/gpu-1-cpx-nps4-0/","slot":1}]}},"preparedClaims":[{"uid":"claim-uid-1","name":"claim-1","namespace":"default","state":"PrepareCompleted","status":{"allocation":{"devices":{"results":[{"request":"gpu","driver":"hami-core-gpu.project-hami.io","pool":"node-a","device":"gpu-0"}]}}},"devices":[{"device":{"requests":["hami"],"poolName":"node-a","deviceName":"hami-gpu-1","cdiDeviceIDs":["k8s.gpu.nvidia.com/device=hami-gpu-1"]},"partition":{"type":"Soft"},"nvidia":{"group":0,"type":"gpu","uuid":"GPU-bbbb"}},{"device":{"requests":["gpu"],"poolName":"node-a","deviceName":"gpu-0","cdiDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-0"]},"nvidia":{"group":0,"type":"gpu","uuid":"GPU-aaaa"}},{"device":{"requests":["mig"],"poolName":"node-a","deviceName":"gpu-1-mig-1g10gb-2","cdiDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-1-mig-1g10gb-2"]},"partition":{"type":"Hard","parentDevice":"GPU-dddd","nvidia":{"parentMinor":1,"giID":2,"ciID":0,"migUUID":"MIG-cccc"}},"nvidia":{"group":1,"type":"mig"}},{"device":{"requests":["vfio"],"poolName":"node-a","deviceName":"gpu-3-vfio","cdiDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-3-vfio"]},"nvidia":{"group":1,"type":"vfio","uuid":"GPU-eeee"}}],"nvidia":{"groups":[{},{"mpsControlDaemonID":"mps-claim-uid-1"}]}},{"uid":"claim-uid-2","name":"claim-2","namespace":"team-a","state":"PrepareStarted"},{"uid":"claim-uid-3","devices":[{"device":{"requests":["gpu"],"poolName":"node-a","deviceName":"gpu-0-129","cdiDeviceIDs":["amd.com/gpu=claim-uid-1-gpu-0-129"]},"containerEdits":{"env":["AMD_VISIBLE_DEVICES=0"],"deviceNodes":[{"path":"/dev/dri/renderD128"}],"mounts":[{"hostPath":"/opt/hook","containerPath":"/opt/hook","options":["ro","bind"]}]},"partition":{"type":"Soft","amd":{"computeUnits":[0,1,2,3]}},"amd":{"shareKey":"claim-uid-1/gpu/gpu-0-129/"}},{"device":{"requests":["part"],"poolName":"node-a","deviceName":"gpu-1-cpx-nps4-0","cdiDeviceIDs":["amd.com/gpu=claim-uid-1-gpu-1-cpx-nps4-0-1"]},"partition":{"type":"Hard","amd":{"slot":1}},"amd":{"shareKey":"claim-uid-1/part/gpu-1-cpx-nps4-0/"}}]}]} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..330741d --- /dev/null +++ b/go.mod @@ -0,0 +1,36 @@ +module github.com/Project-HAMi/dra-lib + +go 1.26.0 + +require ( + github.com/stretchr/testify v1.10.0 + k8s.io/api v0.34.0 + k8s.io/apimachinery v0.34.0 + k8s.io/klog/v2 v2.130.1 + k8s.io/utils v0.0.0-20250604170112-4c0f3b243397 + tags.cncf.io/container-device-interface/specs-go v0.8.0 +) + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/fxamacker/cbor/v2 v2.9.0 // indirect + github.com/go-logr/logr v1.4.2 // indirect + github.com/gogo/protobuf v1.3.2 // indirect + github.com/google/go-cmp v0.7.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/kr/text v0.2.0 // 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/pmezard/go-difflib v1.0.0 // indirect + github.com/spf13/pflag v1.0.6 // indirect + github.com/x448/float16 v0.8.4 // indirect + go.yaml.in/yaml/v2 v2.4.2 // indirect + golang.org/x/net v0.60.0 // indirect + golang.org/x/text v0.42.0 // indirect + gopkg.in/inf.v0 v0.9.1 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + sigs.k8s.io/json v0.0.0-20241014173422-cfa47c3a1cc8 // indirect + sigs.k8s.io/randfill v1.0.0 // indirect + sigs.k8s.io/structured-merge-diff/v6 v6.3.0 // indirect + sigs.k8s.io/yaml v1.6.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..3614306 --- /dev/null +++ b/go.sum @@ -0,0 +1,99 @@ +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +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/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/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= +github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +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/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +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/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/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/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 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/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= +github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= +github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= +github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +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/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI= +go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU= +go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +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/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +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.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= +golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +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/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-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +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.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= +golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +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/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= +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/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= +gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +k8s.io/api v0.34.0 h1:L+JtP2wDbEYPUeNGbeSa/5GwFtIA662EmT2YSLOkAVE= +k8s.io/api v0.34.0/go.mod h1:YzgkIzOOlhl9uwWCZNqpw6RJy9L2FK4dlJeayUoydug= +k8s.io/apimachinery v0.34.0 h1:eR1WO5fo0HyoQZt1wdISpFDffnWOvFLOOeJ7MgIv4z0= +k8s.io/apimachinery v0.34.0/go.mod h1:/GwIlEcWuTX9zKIg2mbw0LRFIsXwrfoVxn+ef0X13lw= +k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk= +k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE= +k8s.io/utils v0.0.0-20250604170112-4c0f3b243397 h1:hwvWFiBzdWw1FhfY1FooPn3kzWuJ8tmbZBHi4zVsl1Y= +k8s.io/utils v0.0.0-20250604170112-4c0f3b243397/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= +sigs.k8s.io/json v0.0.0-20241014173422-cfa47c3a1cc8 h1:gBQPwqORJ8d8/YNZWEjoZs7npUVDpVXUUOFfW6CgAqE= +sigs.k8s.io/json v0.0.0-20241014173422-cfa47c3a1cc8/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg= +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.3.0 h1:jTijUJbW353oVOd9oTlifJqOGEkUw2jB/fXCbTiQEco= +sigs.k8s.io/structured-merge-diff/v6 v6.3.0/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/specs-go v0.8.0 h1:QYGFzGxvYK/ZLMrjhvY0RjpUavIn4KcmRmVP/JjdBTA= +tags.cncf.io/container-device-interface/specs-go v0.8.0/go.mod h1:BhJIkjjPh4qpys+qm4DAYtUyryaTDg9zris+AczXyws= diff --git a/sync-dot-project.yml b/sync-dot-project.yml index 3089217..35de1c9 100644 --- a/sync-dot-project.yml +++ b/sync-dot-project.yml @@ -1,5 +1,5 @@ # Community files pulled from Project-HAMi/.project by .github/workflows/sync-dot-project.yml. -# OWNERS is left out until hami-dra-lib has a project_id in .project/maintainers.yaml; +# OWNERS is left out until dra-lib has a project_id in .project/maintainers.yaml; # without one the generated OWNERS would be empty. source: Project-HAMi/.project@main files: