diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b1069d5..58d7f44 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -55,7 +55,11 @@ jobs: strategy: fail-fast: false matrix: - target: [FuzzDecodeV1, FuzzLegacy, FuzzRoundTrip] + include: + - {target: FuzzDecode, package: ./checkpoint/} + - {target: FuzzLegacy, package: ./checkpoint/} + - {target: FuzzRoundTrip, package: ./checkpoint/} + - {target: FuzzTestExtension, package: ./checkpoint/checkpointtest/} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -65,4 +69,4 @@ jobs: go-version: '1.26' check-latest: true - name: Run ${{ matrix.target }} for 60s - run: go test ./checkpoint/ -run '^$' -fuzz '^${{ matrix.target }}$' -fuzztime 60s + run: go test ${{ matrix.package }} -run '^$' -fuzz '^${{ matrix.target }}$' -fuzztime 60s diff --git a/CHANGELOG.md b/CHANGELOG.md index 321013c..7d3e200 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,50 @@ needs a new checkpoint API version (with conversion), not just a new release. ## [Unreleased] +### Changed + +- **Breaking:** the store writes `api/checkpoint/v2` and is generic over a + driver extension: `NewStore[N, C, D]`, `Options[N, C, D]`, + `Checkpoint[N, C, D]`. The core is the KEP set v2 (4381, 4817, 5075, 5304): + claims with status and lifecycle, the kubelet device reference with + `shareID` and `metadata`, CDI edits. Driver-only state is the typed payload + of the driver's extension at node, claim and device level, with its own + name, schema version, codecs, forward-only migrations and legacy readers. + A store without an extension (`None`) keeps only the core. +- v1 files are read and converted to v2 (`v2.ConvertFromV1`): the vendor + sections become payloads of extension version 1, keeping their v1 JSON. + Nothing writes v1 again. A newer core or extension version, another + extension, or payloads the store cannot decode are refused and the file is + left alone. +- `FuzzDecodeV1` is `FuzzDecode` and reads v1 and v2. + +### Added + +- `api/checkpoint/v2`: the v2 types and `ConvertFromV1`. +- `checkpoint`: `Extension`, `Codec`, `JSONCodec`, `RawPayloads`, `None`, + `ErrNotThisLayout`. +- `checkpoint.VerifyLegacyChecksums`, for a driver's `Extension.Legacy` + readers to check a checkpointmanager file before reading it. +- `checkpoint/checkpointtest`: `FuzzExtension`, for drivers to fuzz their + extension's codecs, migrations and legacy readers from their fixtures. + +### Open questions + +- Strict decoding: the core decoder and `JSONCodec` still ignore unknown + fields (`Strict: false`), as in v0.1.0. Version checks refuse newer schemas; + whether unknown fields within a known version should also be refused is + undecided. + +- `api/checkpoint/v1`: the state of the NVIDIA GPU and ComputeDomain kubelet + plugins of dra-driver-nvidia-gpu that v1 could not hold: `Device.ShareID` and + `Device.Metadata`; per NVIDIA device group `timeSliceApplied`, `mpsApplied`, + `computeDomain` and `type`; `pciBusID` and `id` of NVIDIA devices and + `parentPCIBusID` of MIG partitions; `PrepareAborted` claims with `abortedAt`. + All optional, so existing v1 files stay valid. +- `checkpoint`: the legacy reader reads the checkpointmanager layouts of both + NVIDIA plugins, including the ComputeDomain V1+V2, V1 only and 25.3.0-rc.2 + layouts. + ## [0.1.0] - 2026-12-01 ### Added diff --git a/Makefile b/Makefile index 5eed08a..1646fb4 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ CONTROLLER_GEN_VERSION ?= v0.17.0 GOBIN ?= $(shell go env GOPATH)/bin -CHECKPOINT_APIS := $(CURDIR)/api/checkpoint/v1 +CHECKPOINT_APIS := $(CURDIR)/api/checkpoint/v1 $(CURDIR)/api/checkpoint/v2 HEADER := $(CURDIR)/.license-header.txt .PHONY: build vet test fmt-check tools generate generate-deepcopy verify-generate diff --git a/README.md b/README.md index f6f08f3..54dc72e 100644 --- a/README.md +++ b/README.md @@ -2,22 +2,34 @@ Shared Go library for Kubernetes DRA (Dynamic Resource Allocation) drivers. -- `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. +- `api/checkpoint`: versioned kubelet plugin checkpoint API: kind `Checkpoint` + in an API group the driver chooses (for example + `checkpoint.internal.example.com`). `v2` is written: a vendor-neutral core + whose fields map to the DRA KEPs 4381, 4817, 5075 and 5304, plus opaque + driver payloads per node, claim and device. `v1` is read and converted. - `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). + checkpoint owned by another driver or written in a newer schema, decodes + the driver's payloads with its `Extension`, migrates them forward, and + migrates the legacy kubelet checkpointmanager format (deprecated, will be + removed in a future version). +- `checkpoint/checkpointtest`: `FuzzExtension` for a driver's extension. ```go -store, err := checkpoint.NewStore(path, checkpoint.Options{ +type node struct{ Modes []string `json:"modes,omitempty"` } +type device struct{ Slot *int32 `json:"slot,omitempty"` } + +store, err := checkpoint.NewStore(path, checkpoint.Options[node, checkpoint.None, device]{ Group: "checkpoint.internal.example.com", DriverName: "gpu.example.com", + Extension: &checkpoint.Extension[node, checkpoint.None, device]{ + Name: "gpu.example.com", Version: 1, + Node: checkpoint.JSONCodec[node]{}, Device: checkpoint.JSONCodec[device]{}, + }, +}) +err = store.Update(func(cp *checkpoint.Checkpoint[node, checkpoint.None, device]) error { + // cp.Core holds the claims; cp.Node, cp.Claims, cp.Devices the driver state. + return nil }) -cp, err := store.Read() -err = store.Write(cp) ``` Depends on k8s.io/apimachinery, k8s.io/api and the CDI spec only, so drivers diff --git a/api/checkpoint/install/install.go b/api/checkpoint/install/install.go index 14705d4..653603c 100644 --- a/api/checkpoint/install/install.go +++ b/api/checkpoint/install/install.go @@ -22,11 +22,13 @@ import ( utilruntime "k8s.io/apimachinery/pkg/util/runtime" v1 "github.com/Project-HAMi/dra-lib/api/checkpoint/v1" + v2 "github.com/Project-HAMi/dra-lib/api/checkpoint/v2" ) // Install registers all checkpoint versions under group. func Install(scheme *runtime.Scheme, group string) { utilruntime.Must(v1.AddToScheme(scheme, group)) + utilruntime.Must(v2.AddToScheme(scheme, group)) } // NewScheme returns a scheme that decodes any supported checkpoint version diff --git a/api/checkpoint/install/roundtrip_test.go b/api/checkpoint/install/roundtrip_test.go index 4bdb5ea..a6da1ef 100644 --- a/api/checkpoint/install/roundtrip_test.go +++ b/api/checkpoint/install/roundtrip_test.go @@ -26,9 +26,9 @@ import ( "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. +// TestRoundTrip fuzz-tests the v1 and v2 types through the scheme. There is +// no internal 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) diff --git a/api/checkpoint/v1/doc.go b/api/checkpoint/v1/doc.go index 43a7e5f..f7b306d 100644 --- a/api/checkpoint/v1/doc.go +++ b/api/checkpoint/v1/doc.go @@ -16,18 +16,11 @@ 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. +// Package v1 is version v1 of the checkpoint API, kind Checkpoint, in an API +// group the caller chooses, as dra-lib v0.1.0 wrote it. It is decode-only: +// the store reads v1 files and converts them with v2.ConvertFromV1; nothing +// writes v1 again. The types are frozen and stay so v1 files keep reading. +// Changes followed the Kubernetes [API changes] guidelines. // // [API changes]: https://github.com/kubernetes/community/blob/047598ce8b0932b9be921471dd301b6a82db210f/contributors/devel/sig-architecture/api_changes.md package v1 diff --git a/api/checkpoint/v1/types.go b/api/checkpoint/v1/types.go index 91d4d38..7e4cc2a 100644 --- a/api/checkpoint/v1/types.go +++ b/api/checkpoint/v1/types.go @@ -61,6 +61,9 @@ type PreparedClaim struct { Devices []PreparedDevice `json:"devices,omitempty"` // +optional NVIDIA *NVIDIAClaim `json:"nvidia,omitempty"` + // AbortedAt is when the claim entered PrepareStateAborted. + // +optional + AbortedAt *metav1.Time `json:"abortedAt,omitempty"` } type PrepareState string @@ -68,6 +71,10 @@ type PrepareState string const ( PrepareStateStarted PrepareState = "PrepareStarted" PrepareStateCompleted PrepareState = "PrepareCompleted" + // PrepareStateAborted marks a claim whose prepare was undone; the entry + // stays until AbortedAt plus a driver-defined TTL so that stale retries of + // the prepare can be recognised. + PrepareStateAborted PrepareState = "PrepareAborted" ) type PreparedDevice struct { @@ -92,6 +99,20 @@ type Device struct { // +optional // +listType=atomic CDIDeviceIDs []string `json:"cdiDeviceIDs,omitempty"` + // ShareID identifies the share of a device that several claims share. + // +optional + ShareID *types.UID `json:"shareID,omitempty"` + // Metadata is the device metadata the driver returned to the kubelet. + // +optional + Metadata *DeviceMetadata `json:"metadata,omitempty"` +} + +// DeviceMetadata mirrors the kubelet DRA API's device metadata. +type DeviceMetadata struct { + // +optional + Attributes map[string]resourcev1.DeviceAttribute `json:"attributes,omitempty"` + // +optional + NetworkData *resourcev1.NetworkDeviceData `json:"networkData,omitempty"` } // +k8s:deepcopy-gen=false @@ -202,6 +223,20 @@ type NVIDIAClaim struct { type NVIDIADeviceGroup struct { // +optional MPSControlDaemonID string `json:"mpsControlDaemonID,omitempty"` + // MPSApplied records whether MPS was applied to the group. Unset in + // checkpoints that predate it. + // +optional + MPSApplied *bool `json:"mpsApplied,omitempty"` + // TimeSliceApplied records whether time-slicing was applied to the group. + // Unset in checkpoints that predate it, which implied time-slicing. + // +optional + TimeSliceApplied *bool `json:"timeSliceApplied,omitempty"` + // Type is the device type of the group's ComputeDomain config. + // +optional + Type NVIDIADeviceType `json:"type,omitempty"` + // ComputeDomain is the ID of the ComputeDomain the group belongs to. + // +optional + ComputeDomain string `json:"computeDomain,omitempty"` } type NVIDIADeviceType string @@ -210,6 +245,9 @@ const ( NVIDIADeviceTypeGPU NVIDIADeviceType = "gpu" NVIDIADeviceTypeMIG NVIDIADeviceType = "mig" NVIDIADeviceTypeVFIO NVIDIADeviceType = "vfio" + // ComputeDomain devices: an IMEX channel or the daemon of a domain. + NVIDIADeviceTypeChannel NVIDIADeviceType = "channel" + NVIDIADeviceTypeDaemon NVIDIADeviceType = "daemon" ) type NVIDIADevice struct { @@ -219,6 +257,12 @@ type NVIDIADevice struct { // UUID is the GPU UUID of gpu and vfio devices. // +optional UUID string `json:"uuid,omitempty"` + // PCIBusID is the PCI bus ID of vfio devices. + // +optional + PCIBusID string `json:"pciBusID,omitempty"` + // ID is the IMEX channel or daemon ID of channel and daemon devices. + // +optional + ID *int32 `json:"id,omitempty"` } // NVIDIAPartition holds the MIG device identity of a hard partition. @@ -227,4 +271,7 @@ type NVIDIAPartition struct { GIID int32 `json:"giID"` CIID int32 `json:"ciID"` MIGUUID string `json:"migUUID"` + // ParentPCIBusID is the PCI bus ID of the parent GPU. + // +optional + ParentPCIBusID string `json:"parentPCIBusID,omitempty"` } diff --git a/api/checkpoint/v1/zz_generated.deepcopy.go b/api/checkpoint/v1/zz_generated.deepcopy.go index bee1a86..dcf91ef 100644 --- a/api/checkpoint/v1/zz_generated.deepcopy.go +++ b/api/checkpoint/v1/zz_generated.deepcopy.go @@ -23,6 +23,7 @@ package v1 import ( resourcev1 "k8s.io/api/resource/v1" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. @@ -170,6 +171,16 @@ func (in *Device) DeepCopyInto(out *Device) { *out = make([]string, len(*in)) copy(*out, *in) } + if in.ShareID != nil { + in, out := &in.ShareID, &out.ShareID + *out = new(types.UID) + **out = **in + } + if in.Metadata != nil { + in, out := &in.Metadata, &out.Metadata + *out = new(DeviceMetadata) + (*in).DeepCopyInto(*out) + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Device. @@ -182,13 +193,42 @@ func (in *Device) DeepCopy() *Device { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DeviceMetadata) DeepCopyInto(out *DeviceMetadata) { + *out = *in + if in.Attributes != nil { + in, out := &in.Attributes, &out.Attributes + *out = make(map[string]resourcev1.DeviceAttribute, len(*in)) + for key, val := range *in { + (*out)[key] = *val.DeepCopy() + } + } + if in.NetworkData != nil { + in, out := &in.NetworkData, &out.NetworkData + *out = new(resourcev1.NetworkDeviceData) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceMetadata. +func (in *DeviceMetadata) DeepCopy() *DeviceMetadata { + if in == nil { + return nil + } + out := new(DeviceMetadata) + 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) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } } } @@ -205,6 +245,11 @@ func (in *NVIDIAClaim) DeepCopy() *NVIDIAClaim { // 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 + if in.ID != nil { + in, out := &in.ID, &out.ID + *out = new(int32) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NVIDIADevice. @@ -220,6 +265,16 @@ func (in *NVIDIADevice) DeepCopy() *NVIDIADevice { // 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 + if in.MPSApplied != nil { + in, out := &in.MPSApplied, &out.MPSApplied + *out = new(bool) + **out = **in + } + if in.TimeSliceApplied != nil { + in, out := &in.TimeSliceApplied, &out.TimeSliceApplied + *out = new(bool) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NVIDIADeviceGroup. @@ -342,6 +397,10 @@ func (in *PreparedClaim) DeepCopyInto(out *PreparedClaim) { *out = new(NVIDIAClaim) (*in).DeepCopyInto(*out) } + if in.AbortedAt != nil { + in, out := &in.AbortedAt, &out.AbortedAt + *out = (*in).DeepCopy() + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PreparedClaim. @@ -375,7 +434,7 @@ func (in *PreparedDevice) DeepCopyInto(out *PreparedDevice) { if in.NVIDIA != nil { in, out := &in.NVIDIA, &out.NVIDIA *out = new(NVIDIADevice) - **out = **in + (*in).DeepCopyInto(*out) } } diff --git a/api/checkpoint/v2/cdi.go b/api/checkpoint/v2/cdi.go new file mode 100644 index 0000000..e52f831 --- /dev/null +++ b/api/checkpoint/v2/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 v2 + +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/v2/conversion.go b/api/checkpoint/v2/conversion.go new file mode 100644 index 0000000..9b943f4 --- /dev/null +++ b/api/checkpoint/v2/conversion.go @@ -0,0 +1,121 @@ +/* +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 v2 + +import ( + "encoding/json" + "fmt" + + "k8s.io/apimachinery/pkg/runtime" + + v1 "github.com/Project-HAMi/dra-lib/api/checkpoint/v1" +) + +// ConvertFromV1 converts a v1 checkpoint to v2. The core fields carry over +// unchanged. The vendor sections of v1, which have no place in the core, move +// verbatim into the driver payloads, keeping their v1 JSON keys: +// +// - node: {"partitioning": ...} +// - claim: {"nvidia": ...} +// - device: {"partition": ..., "amd": ..., "nvidia": ...} +// +// That shape is version 1 of every driver extension. The result has no +// Extension reference; the store sets it to the extension it registers. It +// shares slices, maps and CDI edits with in. +func ConvertFromV1(in *v1.Checkpoint) (*Checkpoint, error) { + out := &Checkpoint{ + DriverName: in.DriverName, + NodeBootID: in.NodeBootID, + } + var err error + if out.Driver, err = payload(v1NodePayload{Partitioning: in.Partitioning}); err != nil { + return nil, fmt.Errorf("node payload: %w", err) + } + if len(in.PreparedClaims) > 0 { + out.PreparedClaims = make([]PreparedClaim, len(in.PreparedClaims)) + } + for i := range in.PreparedClaims { + from, to := &in.PreparedClaims[i], &out.PreparedClaims[i] + *to = PreparedClaim{ + UID: from.UID, + Name: from.Name, + Namespace: from.Namespace, + State: PrepareState(from.State), + AbortedAt: from.AbortedAt.DeepCopy(), + Status: from.Status.DeepCopy(), + } + if to.Driver, err = payload(v1ClaimPayload{NVIDIA: from.NVIDIA}); err != nil { + return nil, fmt.Errorf("claim %s payload: %w", from.UID, err) + } + if len(from.Devices) > 0 { + to.Devices = make([]PreparedDevice, len(from.Devices)) + } + for j := range from.Devices { + d := &from.Devices[j] + dev := PreparedDevice{Device: Device{ + Requests: d.Device.Requests, + PoolName: d.Device.PoolName, + DeviceName: d.Device.DeviceName, + CDIDeviceIDs: d.Device.CDIDeviceIDs, + ShareID: d.Device.ShareID, + }} + if m := d.Device.Metadata; m != nil { + dev.Device.Metadata = &DeviceMetadata{Attributes: m.Attributes, NetworkData: m.NetworkData} + } + if d.ContainerEdits != nil { + dev.ContainerEdits = &ContainerEdits{ContainerEdits: d.ContainerEdits.ContainerEdits} + } + if dev.Driver, err = payload(v1DevicePayload{Partition: d.Partition, AMD: d.AMD, NVIDIA: d.NVIDIA}); err != nil { + return nil, fmt.Errorf("claim %s device %d payload: %w", from.UID, j, err) + } + to.Devices[j] = dev + } + } + return out, nil +} + +type v1NodePayload struct { + Partitioning *v1.NodePartitioning `json:"partitioning,omitempty"` +} + +func (p v1NodePayload) empty() bool { return p.Partitioning == nil } + +type v1ClaimPayload struct { + NVIDIA *v1.NVIDIAClaim `json:"nvidia,omitempty"` +} + +func (p v1ClaimPayload) empty() bool { return p.NVIDIA == nil } + +type v1DevicePayload struct { + Partition *v1.Partition `json:"partition,omitempty"` + AMD *v1.AMDDevice `json:"amd,omitempty"` + NVIDIA *v1.NVIDIADevice `json:"nvidia,omitempty"` +} + +func (p v1DevicePayload) empty() bool { return p.Partition == nil && p.AMD == nil && p.NVIDIA == nil } + +// payload returns the JSON of a v1 vendor section, or nil if it is empty. +func payload[T interface{ empty() bool }](p T) (*runtime.RawExtension, error) { + if p.empty() { + return nil, nil + } + raw, err := json.Marshal(p) + if err != nil { + return nil, err + } + return &runtime.RawExtension{Raw: raw}, nil +} diff --git a/api/checkpoint/v2/conversion_test.go b/api/checkpoint/v2/conversion_test.go new file mode 100644 index 0000000..f5ff68b --- /dev/null +++ b/api/checkpoint/v2/conversion_test.go @@ -0,0 +1,104 @@ +/* +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 v2 + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + resourcev1 "k8s.io/api/resource/v1" + "k8s.io/apimachinery/pkg/api/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/utils/ptr" + cdispec "tags.cncf.io/container-device-interface/specs-go" + + v1 "github.com/Project-HAMi/dra-lib/api/checkpoint/v1" +) + +func TestConvertFromV1(t *testing.T) { + aborted := metav1.NewTime(time.Unix(1764460800, 0).UTC()) + status := &resourcev1.ResourceClaimStatus{Allocation: &resourcev1.AllocationResult{Devices: resourcev1.DeviceAllocationResult{ + Results: []resourcev1.DeviceRequestAllocationResult{{Request: "gpu", Driver: "gpu.example.com", Pool: "node-a", Device: "gpu-0"}}, + }}} + share := types.UID("share-1") + metadata := &v1.DeviceMetadata{ + Attributes: map[string]resourcev1.DeviceAttribute{"model": {StringValue: ptr.To("x")}}, + NetworkData: &resourcev1.NetworkDeviceData{InterfaceName: "eth1"}, + } + edits := cdispec.ContainerEdits{Env: []string{"A=1"}} + memory := resource.MustParse("4Gi") + in := &v1.Checkpoint{ + DriverName: "gpu.example.com", + NodeBootID: "boot-1", + Partitioning: &v1.NodePartitioning{ + Modes: []v1.PartitionMode{{Kind: v1.PartitionModeKindMemory, Mode: "nps4"}}, + AMD: &v1.AMDNodePartitioning{AssignedSlots: []v1.AMDAssignedSlot{{GPUIndex: 1, ShareKey: "k", Slot: 2}}}, + }, + PreparedClaims: []v1.PreparedClaim{ + { + UID: "uid-1", Name: "claim-1", Namespace: "ns", State: v1.PrepareStateAborted, AbortedAt: &aborted, Status: status, + NVIDIA: &v1.NVIDIAClaim{Groups: []v1.NVIDIADeviceGroup{{MPSControlDaemonID: "mps-1"}}}, + Devices: []v1.PreparedDevice{ + { + Device: v1.Device{Requests: []string{"gpu"}, PoolName: "node-a", DeviceName: "gpu-0", CDIDeviceIDs: []string{"example.com/gpu=0"}, ShareID: &share, Metadata: metadata}, + ContainerEdits: &v1.ContainerEdits{ContainerEdits: edits}, + Partition: &v1.Partition{Type: v1.PartitionTypeSoft, Memory: &memory, Cores: ptr.To[int32](50)}, + AMD: &v1.AMDDevice{ShareKey: "k"}, + NVIDIA: &v1.NVIDIADevice{Group: 0, Type: v1.NVIDIADeviceTypeGPU, UUID: "GPU-0"}, + }, + {Device: v1.Device{PoolName: "node-a", DeviceName: "gpu-1"}}, + }, + }, + {UID: "uid-2", State: v1.PrepareStateCompleted}, + }, + } + raw := func(s string) *runtime.RawExtension { return &runtime.RawExtension{Raw: []byte(s)} } + want := &Checkpoint{ + DriverName: "gpu.example.com", + NodeBootID: "boot-1", + Driver: raw(`{"partitioning":{"modes":[{"kind":"memory","mode":"nps4"}],"amd":{"assignedSlots":[{"gpuIndex":1,"shareKey":"k","slot":2}]}}}`), + PreparedClaims: []PreparedClaim{ + { + UID: "uid-1", Name: "claim-1", Namespace: "ns", State: PrepareStateAborted, AbortedAt: &aborted, Status: status, + Driver: raw(`{"nvidia":{"groups":[{"mpsControlDaemonID":"mps-1"}]}}`), + Devices: []PreparedDevice{ + { + Device: Device{Requests: []string{"gpu"}, PoolName: "node-a", DeviceName: "gpu-0", CDIDeviceIDs: []string{"example.com/gpu=0"}, ShareID: &share, + Metadata: &DeviceMetadata{Attributes: metadata.Attributes, NetworkData: metadata.NetworkData}}, + ContainerEdits: &ContainerEdits{ContainerEdits: edits}, + Driver: raw(`{"partition":{"type":"Soft","memory":"4Gi","cores":50},"amd":{"shareKey":"k"},"nvidia":{"group":0,"type":"gpu","uuid":"GPU-0"}}`), + }, + {Device: Device{PoolName: "node-a", DeviceName: "gpu-1"}}, + }, + }, + {UID: "uid-2", State: PrepareStateCompleted}, + }, + } + got, err := ConvertFromV1(in) + require.NoError(t, err) + assert.Equal(t, want, got) +} + +func TestConvertFromV1CoreOnly(t *testing.T) { + got, err := ConvertFromV1(&v1.Checkpoint{DriverName: "npu.example.com", PreparedClaims: []v1.PreparedClaim{{UID: "uid-1"}}}) + require.NoError(t, err) + assert.Equal(t, &Checkpoint{DriverName: "npu.example.com", PreparedClaims: []PreparedClaim{{UID: "uid-1"}}}, got) +} diff --git a/api/checkpoint/v2/doc.go b/api/checkpoint/v2/doc.go new file mode 100644 index 0000000..49f6f1b --- /dev/null +++ b/api/checkpoint/v2/doc.go @@ -0,0 +1,32 @@ +/* +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 v2 is the checkpoint API, kind Checkpoint, version v2, in an API +// group the caller chooses. It is the version the store writes. +// +// A core version is a named set of beta/GA DRA KEPs, and every core field +// maps to a KEP of its set. v2 covers 4381 (structured parameters: the claim, +// its devices, CDI edits and the Prepare/Unprepare lifecycle), 4817 (device +// network data), 5075 (consumable capacity: ShareID) and 5304 (device +// metadata). apiVersion, driverName and the extension reference are the +// envelope. Driver-only state never goes in the core: it is the payload of a +// driver extension, stored per node, claim and device. +// +// v1 files are read through ConvertFromV1; nothing writes v1 again. A new KEP +// set is a new version with a forward conversion from this one. +package v2 diff --git a/api/checkpoint/v2/register.go b/api/checkpoint/v2/register.go new file mode 100644 index 0000000..dd27bc4 --- /dev/null +++ b/api/checkpoint/v2/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 v2 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +const ( + Version = "v2" + Kind = "Checkpoint" +) + +// AddToScheme registers the v2 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/v2/types.go b/api/checkpoint/v2/types.go new file mode 100644 index 0000000..e0527e4 --- /dev/null +++ b/api/checkpoint/v2/types.go @@ -0,0 +1,131 @@ +/* +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 v2 + +import ( + resourcev1 "k8s.io/api/resource/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + cdispec "tags.cncf.io/container-device-interface/specs-go" +) + +// Checkpoint is the persisted state of a DRA kubelet plugin. +// KEP set v2: 4381, 4817, 5075, 5304. +// +// +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 (envelope). + DriverName string `json:"driverName"` + // Extension names the driver extension whose payloads the checkpoint + // holds, and its schema version (envelope). + // +optional + Extension *ExtensionRef `json:"extension,omitempty"` + // NodeBootID is the Linux boot ID the prepared claims belong to (4381). + // +optional + NodeBootID string `json:"nodeBootID,omitempty"` + // Driver is the extension's node-level payload. + // +optional + Driver *runtime.RawExtension `json:"driver,omitempty"` + // +optional + // +listType=map + // +listMapKey=uid + PreparedClaims []PreparedClaim `json:"preparedClaims,omitempty"` +} + +// ExtensionRef identifies a driver extension and its own schema version. +type ExtensionRef struct { + Name string `json:"name"` + Version int32 `json:"version"` +} + +// PreparedClaim is a claim the plugin prepared (4381). +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"` + // AbortedAt is when State became PrepareAborted. + // +optional + AbortedAt *metav1.Time `json:"abortedAt,omitempty"` + // +optional + Status *resourcev1.ResourceClaimStatus `json:"status,omitempty"` + // +optional + // +listType=atomic + Devices []PreparedDevice `json:"devices,omitempty"` + // Driver is the extension's claim-level payload. + // +optional + Driver *runtime.RawExtension `json:"driver,omitempty"` +} + +// PrepareState is where a claim is in NodePrepareResources (4381). +type PrepareState string + +const ( + PrepareStateStarted PrepareState = "PrepareStarted" + PrepareStateCompleted PrepareState = "PrepareCompleted" + // PrepareStateAborted marks a claim whose prepare was undone; the entry + // stays until AbortedAt plus a driver-defined TTL so that stale retries of + // the prepare can be recognised. + PrepareStateAborted PrepareState = "PrepareAborted" +) + +type PreparedDevice struct { + Device Device `json:"device"` + // ContainerEdits are the CDI edits the plugin wrote for the device (4381). + // +optional + ContainerEdits *ContainerEdits `json:"containerEdits,omitempty"` + // Driver is the extension's device-level payload. + // +optional + Driver *runtime.RawExtension `json:"driver,omitempty"` +} + +// Device mirrors k8s.io/dynamic-resource-allocation/kubeletplugin.Device. +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"` + // ShareID identifies the share of a device that several claims share (5075). + // +optional + ShareID *types.UID `json:"shareID,omitempty"` + // Metadata is the device metadata the driver returned to the kubelet. + // +optional + Metadata *DeviceMetadata `json:"metadata,omitempty"` +} + +// DeviceMetadata mirrors k8s.io/dynamic-resource-allocation/kubeletplugin.DeviceMetadata. +type DeviceMetadata struct { + // +optional + Attributes map[string]resourcev1.DeviceAttribute `json:"attributes,omitempty"` // 5304 + // +optional + NetworkData *resourcev1.NetworkDeviceData `json:"networkData,omitempty"` // 4817 +} + +// +k8s:deepcopy-gen=false +type ContainerEdits struct { + cdispec.ContainerEdits `json:",inline"` +} diff --git a/api/checkpoint/v2/zz_generated.deepcopy.go b/api/checkpoint/v2/zz_generated.deepcopy.go new file mode 100644 index 0000000..19c1e5b --- /dev/null +++ b/api/checkpoint/v2/zz_generated.deepcopy.go @@ -0,0 +1,206 @@ +//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 v2 + +import ( + "k8s.io/api/resource/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" +) + +// 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.Extension != nil { + in, out := &in.Extension, &out.Extension + *out = new(ExtensionRef) + **out = **in + } + if in.Driver != nil { + in, out := &in.Driver, &out.Driver + *out = new(runtime.RawExtension) + (*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) + } + if in.ShareID != nil { + in, out := &in.ShareID, &out.ShareID + *out = new(types.UID) + **out = **in + } + if in.Metadata != nil { + in, out := &in.Metadata, &out.Metadata + *out = new(DeviceMetadata) + (*in).DeepCopyInto(*out) + } +} + +// 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 *DeviceMetadata) DeepCopyInto(out *DeviceMetadata) { + *out = *in + if in.Attributes != nil { + in, out := &in.Attributes, &out.Attributes + *out = make(map[string]v1.DeviceAttribute, len(*in)) + for key, val := range *in { + (*out)[key] = *val.DeepCopy() + } + } + if in.NetworkData != nil { + in, out := &in.NetworkData, &out.NetworkData + *out = new(v1.NetworkDeviceData) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceMetadata. +func (in *DeviceMetadata) DeepCopy() *DeviceMetadata { + if in == nil { + return nil + } + out := new(DeviceMetadata) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ExtensionRef) DeepCopyInto(out *ExtensionRef) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExtensionRef. +func (in *ExtensionRef) DeepCopy() *ExtensionRef { + if in == nil { + return nil + } + out := new(ExtensionRef) + 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.AbortedAt != nil { + in, out := &in.AbortedAt, &out.AbortedAt + *out = (*in).DeepCopy() + } + if in.Status != nil { + in, out := &in.Status, &out.Status + *out = new(v1.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.Driver != nil { + in, out := &in.Driver, &out.Driver + *out = new(runtime.RawExtension) + (*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.Driver != nil { + in, out := &in.Driver, &out.Driver + *out = new(runtime.RawExtension) + (*in).DeepCopyInto(*out) + } +} + +// 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 index 45a5901..8c72cc0 100644 --- a/checkpoint/bench_test.go +++ b/checkpoint/bench_test.go @@ -25,7 +25,7 @@ import ( "k8s.io/apimachinery/pkg/types" cdispec "tags.cncf.io/container-device-interface/specs-go" - api "github.com/Project-HAMi/dra-lib/api/checkpoint/v1" + api "github.com/Project-HAMi/dra-lib/api/checkpoint/v2" ) // The legacy side is what the kubelet checkpointmanager did for the AMD and @@ -88,13 +88,13 @@ func benchClaim(i, devices int) ([]*legacyTestDevice, api.PreparedClaim) { return legacy, claim } -func benchCheckpoints(c benchCase) (*legacyTestCheckpoint, *api.Checkpoint) { +func benchCheckpoints(c benchCase) (*legacyTestCheckpoint, *benchCheckpoint) { legacy := &legacyTestCheckpoint{V1: &legacyTestClaimsV1{PreparedClaims: map[string][]*legacyTestDevice{}}} - current := &api.Checkpoint{DriverName: testDriver} + current := &benchCheckpoint{Core: &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) + current.Core.PreparedClaims = append(current.Core.PreparedClaims, claim) } return legacy, current } @@ -161,7 +161,7 @@ func BenchmarkWrite(b *testing.B) { } reportFileSize(b, path) }) - b.Run("v1/"+c.String(), func(b *testing.B) { + b.Run("v2/"+c.String(), func(b *testing.B) { s := benchStore(b) b.ReportAllocs() for b.Loop() { @@ -190,7 +190,7 @@ func BenchmarkRead(b *testing.B) { } reportFileSize(b, path) }) - b.Run("v1/"+c.String(), func(b *testing.B) { + b.Run("v2/"+c.String(), func(b *testing.B) { s := benchStore(b) if err := s.Write(current); err != nil { b.Fatal(err) @@ -230,19 +230,20 @@ func BenchmarkPrepareCycle(b *testing.B) { } reportFileSize(b, path) }) - b.Run("v1/"+c.String(), func(b *testing.B) { + b.Run("v2/"+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 + err := s.Update(func(cp *benchCheckpoint) error { + claims := cp.Core.PreparedClaims + if last := len(claims) - 1; claims[last].UID == claim.UID { + claims[last] = claim return nil } - cp.PreparedClaims = append(cp.PreparedClaims, claim) + cp.Core.PreparedClaims = append(claims, claim) return nil }) if err != nil { @@ -254,8 +255,12 @@ func BenchmarkPrepareCycle(b *testing.B) { } } -func benchStore(b *testing.B) *Store { - s, err := NewStore(filepath.Join(b.TempDir(), "checkpoint.json"), Options{Group: testGroup, DriverName: testDriver}) +// The benchmarks store core state only, like the v1 benchmarks they compare +// with: the same claims, devices and CDI edits. +type benchCheckpoint = Checkpoint[None, None, None] + +func benchStore(b *testing.B) *Store[None, None, None] { + s, err := NewStore(filepath.Join(b.TempDir(), "checkpoint.json"), Options[None, None, None]{Group: testGroup, DriverName: testDriver}) if err != nil { b.Fatal(err) } diff --git a/checkpoint/checkpointtest/fuzz.go b/checkpoint/checkpointtest/fuzz.go new file mode 100644 index 0000000..b5113c3 --- /dev/null +++ b/checkpoint/checkpointtest/fuzz.go @@ -0,0 +1,152 @@ +/* +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 checkpointtest has test helpers for drivers that define a +// checkpoint.Extension. +package checkpointtest + +import ( + "bytes" + "encoding/json" + "regexp" + "testing" + + "k8s.io/apimachinery/pkg/types" + + "github.com/Project-HAMi/dra-lib/checkpoint" +) + +// slowQuantity matches quantities with a large negative exponent, for which +// k8s.io/apimachinery's resource.ParseQuantity does not finish in practice. +var slowQuantity = regexp.MustCompile(`[eE]-0*[0-9]{6,}`) + +const fuzzClaim = types.UID("fuzz-claim") + +// FuzzExtension fuzzes an extension with arbitrary payloads, starting from +// seeds (the driver's fixtures). For every input: +// - each codec must not panic, and a payload it decodes must encode, and +// decode and encode again to the same bytes; +// - the migrations from every older version must not panic, must keep the +// number of device payloads, and what they produce is checked like a +// payload; +// - each legacy reader must not panic, and the state it returns must encode +// with the codecs and round-trip. +func FuzzExtension[N, C, D any](f *testing.F, ext checkpoint.Extension[N, C, D], seeds ...[]byte) { + for _, seed := range seeds { + f.Add(seed) + } + f.Add([]byte(`{}`)) + f.Add([]byte(`null`)) + f.Fuzz(func(t *testing.T, data []byte) { + if slowQuantity.Match(data) { + return + } + roundTrip(t, ext.Node, data, "node") + roundTrip(t, ext.Claim, data, "claim") + roundTrip(t, ext.Device, data, "device") + for from := 1; from < ext.Version; from++ { + migrate(t, ext, from, data) + } + for i, read := range ext.Legacy { + cp, err := read(data) + if err != nil { + continue + } + if cp == nil { + t.Fatalf("legacy reader %d returned no checkpoint and no error", i) + } + if cp.Node != nil { + roundTrip(t, ext.Node, encode(t, ext.Node, cp.Node, "legacy node"), "legacy node") + } + for uid, c := range cp.Claims { + if c != nil { + roundTrip(t, ext.Claim, encode(t, ext.Claim, c, "legacy claim "+string(uid)), "legacy claim") + } + } + for uid, devices := range cp.Devices { + for _, d := range devices { + if d != nil { + roundTrip(t, ext.Device, encode(t, ext.Device, d, "legacy device of "+string(uid)), "legacy device") + } + } + } + } + }) +} + +func migrate[N, C, D any](t *testing.T, ext checkpoint.Extension[N, C, D], from int, data []byte) { + t.Helper() + raw := checkpoint.RawPayloads{ + Node: clone(data), + Claims: map[types.UID]json.RawMessage{fuzzClaim: clone(data)}, + Devices: map[types.UID][]json.RawMessage{fuzzClaim: {clone(data), nil}}, + } + for v := from; v < ext.Version; v++ { + if err := ext.Migrations[v](&raw); err != nil { + return + } + } + if n := len(raw.Devices[fuzzClaim]); n != 2 { + t.Fatalf("migrations from version %d turned 2 device payloads into %d", from, n) + } + if len(raw.Node) > 0 { + roundTrip(t, ext.Node, raw.Node, "migrated node") + } + if c := raw.Claims[fuzzClaim]; len(c) > 0 { + roundTrip(t, ext.Claim, c, "migrated claim") + } + for _, d := range raw.Devices[fuzzClaim] { + if len(d) > 0 { + roundTrip(t, ext.Device, d, "migrated device") + } + } +} + +func roundTrip[T any](t *testing.T, codec checkpoint.Codec[T], data []byte, what string) { + t.Helper() + if codec == nil { + return + } + v, err := codec.Decode(data) + if err != nil { + return + } + once := encode(t, codec, v, what) + again, err := codec.Decode(once) + if err != nil { + t.Fatalf("decode the encoded %s payload: %v\n%s", what, err, once) + } + twice := encode(t, codec, again, what) + if !bytes.Equal(once, twice) { + t.Fatalf("%s payload changed in a round trip:\n%s\n%s", what, once, twice) + } +} + +func encode[T any](t *testing.T, codec checkpoint.Codec[T], v *T, what string) json.RawMessage { + t.Helper() + if codec == nil { + t.Fatalf("%s has state but the extension has no codec for it", what) + } + data, err := codec.Encode(v) + if err != nil { + t.Fatalf("encode %s payload: %v", what, err) + } + return data +} + +func clone(data []byte) json.RawMessage { + return append(json.RawMessage(nil), data...) +} diff --git a/checkpoint/checkpointtest/fuzz_test.go b/checkpoint/checkpointtest/fuzz_test.go new file mode 100644 index 0000000..217b906 --- /dev/null +++ b/checkpoint/checkpointtest/fuzz_test.go @@ -0,0 +1,93 @@ +/* +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 checkpointtest + +import ( + "encoding/json" + "errors" + "testing" + + "github.com/Project-HAMi/dra-lib/checkpoint" +) + +// exampleDevice is version 2 of an example extension: version 1 stored the +// share as {"share":{"key":...}}. +type exampleDevice struct { + ShareKey string `json:"shareKey,omitempty"` + Slot *int32 `json:"slot,omitempty"` +} + +type exampleNode struct { + Modes []string `json:"modes,omitempty"` +} + +func exampleExtension() checkpoint.Extension[exampleNode, checkpoint.None, exampleDevice] { + return checkpoint.Extension[exampleNode, checkpoint.None, exampleDevice]{ + Name: "gpu.example.com", + Version: 2, + Node: checkpoint.JSONCodec[exampleNode]{}, + Device: checkpoint.JSONCodec[exampleDevice]{}, + Migrations: map[int]func(*checkpoint.RawPayloads) error{1: func(raw *checkpoint.RawPayloads) error { + for uid, devices := range raw.Devices { + for j, d := range devices { + if d == nil { + continue + } + var old struct { + Share *struct { + Key string `json:"key"` + } `json:"share"` + Slot *int32 `json:"slot"` + } + if err := json.Unmarshal(d, &old); err != nil { + return err + } + next := exampleDevice{Slot: old.Slot} + if old.Share != nil { + next.ShareKey = old.Share.Key + } + data, err := json.Marshal(next) + if err != nil { + return err + } + raw.Devices[uid][j] = data + } + } + return nil + }}, + Legacy: []func([]byte) (*checkpoint.Checkpoint[exampleNode, checkpoint.None, exampleDevice], error){ + func(data []byte) (*checkpoint.Checkpoint[exampleNode, checkpoint.None, exampleDevice], error) { + var old struct { + Mode string `json:"activeMode"` + } + if err := json.Unmarshal(data, &old); err != nil || old.Mode == "" { + return nil, errors.Join(checkpoint.ErrNotThisLayout, err) + } + return &checkpoint.Checkpoint[exampleNode, checkpoint.None, exampleDevice]{Node: &exampleNode{Modes: []string{old.Mode}}}, nil + }, + }, + } +} + +func FuzzTestExtension(f *testing.F) { + FuzzExtension(f, exampleExtension(), + []byte(`{"share":{"key":"claim/req/dev/"},"slot":1}`), + []byte(`{"shareKey":"k","slot":2}`), + []byte(`{"modes":["nps4"]}`), + []byte(`{"activeMode":"spx"}`), + ) +} diff --git a/checkpoint/extension.go b/checkpoint/extension.go new file mode 100644 index 0000000..43fe338 --- /dev/null +++ b/checkpoint/extension.go @@ -0,0 +1,89 @@ +/* +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" + "errors" + + "k8s.io/apimachinery/pkg/types" +) + +// None is the payload type of a level an extension does not use, and of +// every level of a store without an extension. +type None struct{} + +// Codec turns the payload of one level into the driver's type and back. +type Codec[T any] interface { + Encode(*T) (json.RawMessage, error) + Decode(json.RawMessage) (*T, error) +} + +// JSONCodec encodes a payload with encoding/json. Like the core decoder it +// ignores unknown fields. +type JSONCodec[T any] struct{} + +func (JSONCodec[T]) Encode(v *T) (json.RawMessage, error) { return json.Marshal(v) } + +func (JSONCodec[T]) Decode(data json.RawMessage) (*T, error) { + v := new(T) + if err := json.Unmarshal(data, v); err != nil { + return nil, err + } + return v, nil +} + +// Extension is the driver-owned part of a checkpoint: N is its node, C its +// claim and D its device state. The store keeps the payloads next to the core +// and records Name and Version in the file. +type Extension[N, C, D any] struct { + // Name identifies the extension, usually the DRA driver name. + Name string + // Version is the payload schema version this build writes. A file with a + // newer version is refused. + Version int + // Codecs of the levels the extension uses. A payload at a level without + // a codec is an error. + Node Codec[N] + Claim Codec[C] + Device Codec[D] + // Migrations[k] rewrites payloads of version k to version k+1. Version 1 + // is the shape a v1 checkpoint converts to (see v2.ConvertFromV1). Forward + // only, never removed. + Migrations map[int]func(*RawPayloads) error + // Legacy reads this driver's checkpointmanager layouts, before the store's + // built-in reader. A reader returns ErrNotThisLayout for data it does not + // recognise. + Legacy []func(data []byte) (*Checkpoint[N, C, D], error) + // Validate, if set, runs after a checkpoint is decoded and before it is + // written. + Validate func(*Checkpoint[N, C, D]) error +} + +// ErrNotThisLayout is returned by an Extension.Legacy reader for data in +// another layout. +var ErrNotThisLayout = errors.New("not this legacy checkpoint layout") + +// RawPayloads are the payloads of one checkpoint as stored, for migrations. +// Claims and Devices are keyed by claim UID. A Devices entry is index-aligned +// with the claim's core devices, nil where a device has no payload; it must +// keep its length. +type RawPayloads struct { + Node json.RawMessage + Claims map[types.UID]json.RawMessage + Devices map[types.UID][]json.RawMessage +} diff --git a/checkpoint/fuzz_test.go b/checkpoint/fuzz_test.go index d17c5e9..6bc3349 100644 --- a/checkpoint/fuzz_test.go +++ b/checkpoint/fuzz_test.go @@ -31,6 +31,7 @@ import ( cdispec "tags.cncf.io/container-device-interface/specs-go" api "github.com/Project-HAMi/dra-lib/api/checkpoint/v1" + apiv2 "github.com/Project-HAMi/dra-lib/api/checkpoint/v2" ) // slowQuantity matches quantities with a large negative exponent, for which @@ -46,35 +47,44 @@ var legacyFixtures = []string{ "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) +// encode is what Write puts in the file, without writing it. +func encode(s *testStore, cp *testCheckpoint) ([]byte, error) { + defer func() { clearPayloads(cp.Core) }() + if err := s.prepareWrite(cp); err != nil { + return nil, err } - return s + var buf bytes.Buffer + err := s.encoder.Encode(cp.Core, &buf) + return buf.Bytes(), err } -// 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) +// FuzzDecode reads arbitrary bytes as a v1 or v2 checkpoint: it must not +// panic, and a checkpoint that reads must encode, and read back to the same +// encoding. +func FuzzDecode(f *testing.F) { + s, _ := newTestStore(f) for _, fixture := range legacyFixtures { legacy, err := os.ReadFile(fixture) if err != nil { f.Fatal(err) } - cp, err := readLegacy(legacy) - if err != nil { + seed, path := newTestStore(f) + if err := os.WriteFile(path, legacy, 0o600); err != nil { + f.Fatal(err) + } + if _, err := seed.Read(); err != nil { f.Fatal(err) } - cp.DriverName = testDriver - var buf bytes.Buffer - if err := s.encoder.Encode(cp, &buf); err != nil { + migrated, err := os.ReadFile(path) + if err != nil { f.Fatal(err) } - f.Add(buf.Bytes()) + f.Add(migrated) + } + if v1File, err := os.ReadFile("testdata/v1-checkpoint.json"); err == nil { + f.Add(v1File) } + f.Add([]byte(`{"apiVersion":"` + testGroup + `/v2","kind":"Checkpoint","driverName":"` + testDriver + `"}`)) f.Add([]byte(`{"apiVersion":"` + testGroup + `/v1","kind":"Checkpoint","driverName":"` + testDriver + `"}`)) f.Add([]byte(`{}`)) // A quantity for which Quantity.Cmp does not finish. @@ -85,25 +95,26 @@ func FuzzDecodeV1(f *testing.F) { if isLegacy(data) || slowQuantity.Match(data) { return // FuzzLegacy covers legacy input. } - first, err := s.decode(data) + first, err := s.parse(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 { + once, err := encode(s, first) + if err != nil { t.Fatalf("encode a decoded checkpoint: %v", err) } - second, err := s.decode(once.Bytes()) + second, err := s.parse(once) if err != nil { - t.Fatalf("decode an encoded checkpoint: %v\n%s", err, once.Bytes()) + t.Fatalf("decode an encoded checkpoint: %v\n%s", err, once) } - if err := s.encoder.Encode(second, &twice); err != nil { + twice, err := encode(s, second) + if 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()) + if !bytes.Equal(once, twice) { + t.Fatalf("round trip changed the checkpoint:\n%s\n%s", once, twice) } }) } @@ -133,13 +144,12 @@ func FuzzLegacy(f *testing.F) { if !isLegacy(data) || slowQuantity.Match(data) { return } - s := fuzzStore(t, testDriver) + s, _ := newTestStore(t) if err := os.WriteFile(s.path, data, 0o600); err != nil { t.Fatal(err) } - verifyErr := verifyLegacyChecksums(data) - got, err := s.Read() - if err != nil { + verifyErr := VerifyLegacyChecksums(data) + if _, err := s.Read(); 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) @@ -149,21 +159,22 @@ func FuzzLegacy(f *testing.F) { if verifyErr != nil { t.Fatalf("legacy checkpoint with a bad checksum was accepted: %v", verifyErr) } + migrated, err := os.ReadFile(s.path) + if err != nil { + t.Fatal(err) + } 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 { + encoded, err := encode(s, again) + if 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()) + if !bytes.Equal(migrated, encoded) { + t.Fatalf("migrated checkpoint reads back differently:\n%s\n%s", migrated, encoded) } }) } @@ -172,7 +183,7 @@ func FuzzLegacy(f *testing.F) { // 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.Add("", "x", "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. @@ -181,57 +192,60 @@ func FuzzRoundTrip(f *testing.F) { return } } - if driverName == "" { + if driverName == "" || uid1 == uid2 { return } - checkpoint := &api.Checkpoint{ - DriverName: driverName, - NodeBootID: uid2, - Partitioning: &api.NodePartitioning{ + share := types.UID(uid2) + cp := &testCheckpoint{ + Core: &apiv2.Checkpoint{ + DriverName: driverName, + NodeBootID: uid2, + PreparedClaims: []apiv2.PreparedClaim{ + { + UID: types.UID(uid1), + State: apiv2.PrepareStateCompleted, + Devices: []apiv2.PreparedDevice{{ + Device: apiv2.Device{Requests: []string{profile}, PoolName: driverName, DeviceName: device1, CDIDeviceIDs: []string{device2}, ShareID: &share}, + ContainerEdits: &apiv2.ContainerEdits{ContainerEdits: cdispec.ContainerEdits{Env: []string{env}, DeviceNodes: []*cdispec.DeviceNode{{Path: devicePath}}}}, + }}, + }, + {UID: types.UID(uid2), Devices: []apiv2.PreparedDevice{{Device: apiv2.Device{DeviceName: device2}}}}, + }, + }, + Node: &testNode{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}, - }}, - }, + }}, + Claims: map[types.UID]*testClaim{types.UID(uid1): {NVIDIA: &api.NVIDIAClaim{Groups: []api.NVIDIADeviceGroup{{MPSControlDaemonID: env}}}}}, + Devices: map[types.UID][]*testDevice{ + types.UID(uid1): {{ + // Memory is built from bytes: quantities parsed from arbitrary + // strings can have exponents for which Quantity.Cmp does not finish. + Partition: &api.Partition{Type: api.PartitionTypeHard, Profile: profile, ParentDevice: device2, Cores: &cores, + Memory: resource.NewQuantity(memory, resource.BinarySI), AMD: &api.AMDPartition{Slot: &slot}}, + AMD: &api.AMDDevice{ShareKey: uid2}, + }}, + types.UID(uid2): {{ + 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 { + s := openStore(t, filepath.Join(t.TempDir(), "checkpoint.json"), driverName, newTestExtension()) + if err := s.Write(cp); 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) + cp.Core.Extension = &apiv2.ExtensionRef{Name: testExtension, Version: 1} + if !equality.Semantic.DeepEqual(cp, got) { + t.Fatalf("round trip changed the checkpoint:\n%#v\n%#v", cp, got) } - other, err := NewStore(s.path, Options{Group: testGroup, DriverName: driverName + "-other"}) - if err != nil { - t.Fatal(err) - } + other := openStore(t, s.path, driverName+"-other", newTestExtension()) 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 index c8eecb9..3f82a66 100644 --- a/checkpoint/legacy.go +++ b/checkpoint/legacy.go @@ -42,6 +42,7 @@ import ( cdispec "tags.cncf.io/container-device-interface/specs-go" api "github.com/Project-HAMi/dra-lib/api/checkpoint/v1" + apiv2 "github.com/Project-HAMi/dra-lib/api/checkpoint/v2" ) // legacyFile is the union of the checksum-wrapped JSON layouts that DRA @@ -78,33 +79,55 @@ type legacyListDevice struct { 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"` + PreparedDevices []*legacyGroup `json:"preparedDevices"` + Name string `json:"name"` + Namespace string `json:"namespace"` + AbortedAt *metav1.Time `json:"abortedAt"` +} + +// legacyGroup is the devices of one config of a claim. +type legacyGroup struct { + Devices []struct { + HAMiGPU *legacyUUIDDevice `json:"hami-gpu"` + GPU *legacyUUIDDevice `json:"gpu"` + VFIO *legacyUUIDDevice `json:"vfio"` + Channel *legacyDomainDevice `json:"channel"` + Daemon *legacyDomainDevice `json:"daemon"` + MIG *struct { + Concrete *struct { + ParentMinor int32 `json:"parentMinor"` + GIID int32 `json:"giId"` + CIID int32 `json:"ciId"` + MIGUUID string `json:"migUUID"` + ParentUUID string `json:"parentUUID"` + // ParentPCIBusID postdates the first NVIDIA checkpoints. + ParentPCIBusID string `json:"parentPCIBusID"` + } `json:"concrete"` + Device legacyDevice `json:"device"` + } `json:"mig"` + } `json:"devices"` + ConfigState struct { + MPSControlDaemonID string `json:"mpsControlDaemonID"` + MPSApplied *bool `json:"mpsApplied"` + TimeSliceApplied *bool `json:"timeSliceApplied"` + // Type and ComputeDomain are the ComputeDomain plugin's. + Type string + ComputeDomain string + } `json:"configState"` } type legacyUUIDDevice struct { Info *struct { - UUID string `json:"uuid"` + UUID string `json:"uuid"` + PCIBusID string `json:"pciBusID"` + } `json:"info"` + Device legacyDevice `json:"device"` +} + +// legacyDomainDevice is a ComputeDomain channel or daemon device. +type legacyDomainDevice struct { + Info *struct { + ID int32 `json:"id"` } `json:"info"` Device legacyDevice `json:"device"` } @@ -116,6 +139,38 @@ type legacyDevice struct { PoolName string DeviceName string CDIDeviceIDs []string + ShareID *types.UID + Metadata *struct { + Attributes map[string]resourcev1.DeviceAttribute + NetworkData *resourcev1.NetworkDeviceData + } + + // 25.3.0-rc.2 wrote the kubelet DRA proto message instead. + RequestNames []string `json:"request_names"` + Pool string `json:"pool_name"` + Device string `json:"device_name"` + CDIIDs []string `json:"cdi_device_ids"` +} + +func orSlice(a, b []string) []string { + if len(a) > 0 { + return a + } + return b +} + +func (d legacyDevice) toAPI() api.Device { + device := api.Device{ + Requests: orSlice(d.Requests, d.RequestNames), + PoolName: cmp.Or(d.PoolName, d.Pool), + DeviceName: cmp.Or(d.DeviceName, d.Device), + CDIDeviceIDs: orSlice(d.CDIDeviceIDs, d.CDIIDs), + ShareID: d.ShareID, + } + if d.Metadata != nil { + device.Metadata = &api.DeviceMetadata{Attributes: d.Metadata.Attributes, NetworkData: d.Metadata.NetworkData} + } + return device } func isLegacy(data []byte) bool { @@ -127,22 +182,65 @@ func isLegacy(data []byte) bool { } // 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) +// format. The extension's own legacy readers go first; the built-in reader +// converts through v1. A legacy file with a bad checksum is an error and is +// not modified. +func (s *Store[N, C, D]) migrateLegacy(data []byte) (*Checkpoint[N, C, D], error) { + cp, err := s.readExtensionLegacy(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 { + if cp == nil { + old, err := readLegacy(data) + if err != nil { + return nil, fmt.Errorf("read legacy checkpoint %s: %w", s.path, err) + } + core, err := s.fromV1(old) + if err != nil { + return nil, fmt.Errorf("read legacy checkpoint %s: %w", s.path, err) + } + if cp, err = s.typed(core); err != nil { + return nil, fmt.Errorf("read legacy checkpoint %s: %w", s.path, err) + } + } + if cp.Core == nil { + cp.Core = &apiv2.Checkpoint{} + } + cp.Core.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.group, apiv2.Version) + if err := s.Write(cp); err != nil { return nil, err } - return checkpoint, nil + return cp, nil +} + +// readExtensionLegacy tries the extension's legacy readers in order. It +// returns nil if none recognises the data. +func (s *Store[N, C, D]) readExtensionLegacy(data []byte) (*Checkpoint[N, C, D], error) { + if s.ext == nil { + return nil, nil + } + for _, read := range s.ext.Legacy { + cp, err := read(data) + if errors.Is(err, ErrNotThisLayout) { + continue + } + if err != nil { + return nil, err + } + if cp.Claims == nil { + cp.Claims = map[types.UID]*C{} + } + if cp.Devices == nil { + cp.Devices = map[types.UID][]*D{} + } + return cp, nil + } + return nil, nil } func readLegacy(data []byte) (*api.Checkpoint, error) { - if err := verifyLegacyChecksums(data); err != nil { + if err := VerifyLegacyChecksums(data); err != nil { return nil, err } var file legacyFile @@ -204,6 +302,22 @@ func legacyV1ClaimToAPI(uid string, raw json.RawMessage) (api.PreparedClaim, err } return legacyClaimToAPI(uid, claim, true), nil } + // 25.3.0-rc.2 wrote the claims of the ComputeDomain plugin as lists of + // device groups. + var groupProbe []struct { + Devices json.RawMessage `json:"devices"` + } + if err := json.Unmarshal(raw, &groupProbe); err == nil && len(groupProbe) > 0 && groupProbe[0].Devices != nil { + var groups []*legacyGroup + if err := json.Unmarshal(raw, &groups); err != nil { + return api.PreparedClaim{}, err + } + claim := api.PreparedClaim{UID: types.UID(uid), State: api.PrepareStateCompleted} + for _, group := range groups { + appendLegacyGroup(&claim, group) + } + return claim, nil + } var devices []legacyListDevice if err := json.Unmarshal(raw, &devices); err != nil { return api.PreparedClaim{}, err @@ -245,52 +359,78 @@ func legacyClaimToAPI(uid string, c legacyClaim, v1 bool) api.PreparedClaim { if v1 { claim.State = api.PrepareStateCompleted } + claim.AbortedAt = c.AbortedAt for _, group := range c.PreparedDevices { - if group == nil { - continue - } - if claim.NVIDIA == nil { - claim.NVIDIA = &api.NVIDIAClaim{} + appendLegacyGroup(&claim, group) + } + return claim +} + +// appendLegacyGroup adds the devices of one NVIDIA config group to the claim. +func appendLegacyGroup(claim *api.PreparedClaim, group *legacyGroup) { + if group == nil { + return + } + 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, + MPSApplied: group.ConfigState.MPSApplied, + TimeSliceApplied: group.ConfigState.TimeSliceApplied, + Type: api.NVIDIADeviceType(group.ConfigState.Type), + ComputeDomain: group.ConfigState.ComputeDomain, + }) + 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 + nvidia.PCIBusID = u.Info.PCIBusID + } + device.Device = u.Device.toAPI() } - 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) + domainDevice := func(t api.NVIDIADeviceType, c *legacyDomainDevice) { + nvidia.Type = t + if c.Info != nil { + nvidia.ID = &c.Info.ID } - 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} - } + device.Device = c.Device.toAPI() + } + 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 = d.MIG.Device.toAPI() + 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, ParentPCIBusID: m.ParentPCIBusID} } - claim.Devices = append(claim.Devices, device) + case d.Channel != nil: + domainDevice(api.NVIDIADeviceTypeChannel, d.Channel) + case d.Daemon != nil: + domainDevice(api.NVIDIADeviceTypeDaemon, d.Daemon) } + 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 { +// VerifyLegacyChecksums checks the checksums the kubelet checkpointmanager +// stored in a legacy checkpoint. Each covers the compact JSON of its object +// with the checksum set to 0; the top-level one excludes the separately +// checksummed v2 section. Extension.Legacy readers call it before trusting +// the data. +func VerifyLegacyChecksums(data []byte) error { var compact bytes.Buffer if err := json.Compact(&compact, data); err != nil { return err diff --git a/checkpoint/legacy_export_test.go b/checkpoint/legacy_export_test.go new file mode 100644 index 0000000..f4f8a56 --- /dev/null +++ b/checkpoint/legacy_export_test.go @@ -0,0 +1,42 @@ +/* +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_test + +import ( + "bytes" + "os" + "testing" + + "github.com/Project-HAMi/dra-lib/checkpoint" +) + +// Drivers verify the checksums in their own Extension.Legacy readers. +func TestVerifyLegacyChecksums(t *testing.T) { + for _, name := range []string{"legacy-amd.json", "legacy-nvidia.json", "legacy-nvidia-gpu.json"} { + data, err := os.ReadFile("testdata/" + name) + if err != nil { + t.Fatal(err) + } + if err := checkpoint.VerifyLegacyChecksums(data); err != nil { + t.Errorf("%s: %v", name, err) + } + tampered := bytes.Replace(data, []byte(`"checksum"`), []byte(`"x":1,"checksum"`), 1) + if err := checkpoint.VerifyLegacyChecksums(tampered); err == nil { + t.Errorf("%s: tampered file verified", name) + } + } +} diff --git a/checkpoint/legacy_nvidia_cd_test.go b/checkpoint/legacy_nvidia_cd_test.go new file mode 100644 index 0000000..a435470 --- /dev/null +++ b/checkpoint/legacy_nvidia_cd_test.go @@ -0,0 +1,78 @@ +/* +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 ( + "testing" + "time" + + resourcev1 "k8s.io/api/resource/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/utils/ptr" + + api "github.com/Project-HAMi/dra-lib/api/checkpoint/v1" +) + +// The fixtures were written by the ComputeDomain kubelet plugin's +// checkpointmanager code: V1+V2 is the current layout, V1 only what releases +// before the v2 checkpoint wrote, and 2503rc2 the layout of 25.3.0-rc.2, whose +// v1 claims are lists of device groups with the kubelet proto device. + +func nvidiaCDClaim() api.PreparedClaim { + dev := func(req, name string) api.Device { + return api.Device{Requests: []string{req}, PoolName: "node-a", DeviceName: name, CDIDeviceIDs: []string{"k8s.compute-domain.nvidia.com/device=" + name}} + } + return api.PreparedClaim{ + UID: "claim-uid-1", + Name: "claim-1", + Namespace: "default", + State: api.PrepareStateCompleted, + Status: nvidiaCDStatus(), + Devices: []api.PreparedDevice{ + {Device: dev("channel", "channel-0"), NVIDIA: &api.NVIDIADevice{Group: 0, Type: api.NVIDIADeviceTypeChannel, ID: ptr.To[int32](5)}}, + {Device: dev("daemon", "daemon-0"), NVIDIA: &api.NVIDIADevice{Group: 1, Type: api.NVIDIADeviceTypeDaemon, ID: ptr.To[int32](0)}}, + }, + NVIDIA: &api.NVIDIAClaim{Groups: []api.NVIDIADeviceGroup{ + {Type: api.NVIDIADeviceTypeChannel, ComputeDomain: "domain-a"}, + {Type: api.NVIDIADeviceTypeDaemon, ComputeDomain: "domain-b"}, + }}, + } +} + +func nvidiaCDStatus() *resourcev1.ResourceClaimStatus { + return &resourcev1.ResourceClaimStatus{Allocation: &resourcev1.AllocationResult{Devices: resourcev1.DeviceAllocationResult{ + Results: []resourcev1.DeviceRequestAllocationResult{{Request: "channel", Driver: "compute-domain.nvidia.com", Pool: "node-a", Device: "channel-0"}}, + }}} +} + +func TestReadMigratesNVIDIAComputeDomain(t *testing.T) { + started := api.PreparedClaim{UID: "claim-uid-2", Name: "claim-2", Namespace: "team-a", State: api.PrepareStateStarted, Status: nvidiaCDStatus()} + aborted := api.PreparedClaim{UID: "claim-uid-3", Name: "claim-3", Namespace: "team-a", State: api.PrepareStateAborted, Status: nvidiaCDStatus(), + AbortedAt: &metav1.Time{Time: time.Unix(1764460800, 0)}} + oldest := nvidiaCDClaim() + oldest.Name, oldest.Namespace, oldest.Status = "", "", nil + // 25.3.0-rc.2 recorded neither status nor names. + rc2 := oldest + + v1 := nvidiaCDClaim() + v1.Name, v1.Namespace = "", "" + testMigratesLegacy(t, map[string]*api.Checkpoint{ + "testdata/legacy-nvidia-cd.json": {DriverName: testDriver, NodeBootID: "boot-id-1", PreparedClaims: []api.PreparedClaim{nvidiaCDClaim(), started, aborted}}, + "testdata/legacy-nvidia-cd-v1.json": {DriverName: testDriver, PreparedClaims: []api.PreparedClaim{v1}}, + "testdata/legacy-nvidia-cd-2503rc2.json": {DriverName: testDriver, PreparedClaims: []api.PreparedClaim{rc2}}, + }) +} diff --git a/checkpoint/legacy_nvidia_gpu_test.go b/checkpoint/legacy_nvidia_gpu_test.go new file mode 100644 index 0000000..f33a94c --- /dev/null +++ b/checkpoint/legacy_nvidia_gpu_test.go @@ -0,0 +1,75 @@ +/* +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 ( + "testing" + + resourcev1 "k8s.io/api/resource/v1" + "k8s.io/utils/ptr" + + api "github.com/Project-HAMi/dra-lib/api/checkpoint/v1" +) + +// The fixtures were written by the NVIDIA GPU kubelet plugin's checkpointmanager +// code: V1+V2 is what releases with the v2 checkpoint wrote, V1 only what the +// earlier ones wrote. + +func nvidiaGPUClaim() api.PreparedClaim { + 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}} + } + vfio := dev("vfio", "gpu-3-vfio") + vfio.Metadata = &api.DeviceMetadata{Attributes: map[string]resourcev1.DeviceAttribute{ + "resource.kubernetes.io/pciBusID": {StringValue: ptr.To("0000:5e:00.0")}, + "productName": {StringValue: ptr.To("NVIDIA A100")}, + }} + return 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: "gpu.nvidia.com", Pool: "node-a", Device: "gpu-0"}}, + }}}, + Devices: []api.PreparedDevice{ + {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", ParentPCIBusID: "0000:3b:00.0"}}, + NVIDIA: &api.NVIDIADevice{Group: 1, Type: api.NVIDIADeviceTypeMIG}, + }, + {Device: vfio, NVIDIA: &api.NVIDIADevice{Group: 2, Type: api.NVIDIADeviceTypeVFIO, UUID: "GPU-eeee", PCIBusID: "0000:5e:00.0"}}, + }, + NVIDIA: &api.NVIDIAClaim{Groups: []api.NVIDIADeviceGroup{ + {TimeSliceApplied: ptr.To(true)}, + {MPSControlDaemonID: "mps-claim-uid-1"}, + {TimeSliceApplied: ptr.To(false)}, + }}, + } +} + +func TestReadMigratesNVIDIAGPU(t *testing.T) { + started := api.PreparedClaim{UID: "claim-uid-2", Name: "claim-2", Namespace: "team-a", State: api.PrepareStateStarted, Status: nvidiaGPUClaim().Status} + oldest := nvidiaGPUClaim() + oldest.Name, oldest.Namespace = "", "" + testMigratesLegacy(t, map[string]*api.Checkpoint{ + "testdata/legacy-nvidia-gpu.json": {DriverName: testDriver, NodeBootID: "boot-id-1", PreparedClaims: []api.PreparedClaim{nvidiaGPUClaim(), started}}, + "testdata/legacy-nvidia-gpu-v1.json": {DriverName: testDriver, PreparedClaims: []api.PreparedClaim{oldest}}, + }) +} diff --git a/checkpoint/store.go b/checkpoint/store.go index 4d03b4e..8d7cef3 100644 --- a/checkpoint/store.go +++ b/checkpoint/store.go @@ -15,10 +15,12 @@ limitations under the License. */ // Package checkpoint reads and writes DRA kubelet plugin checkpoints as -// versioned Kubernetes API objects. +// versioned Kubernetes API objects: the generic core (api/checkpoint/v2) plus +// the typed payloads of one driver extension. package checkpoint import ( + "encoding/json" "errors" "fmt" "io/fs" @@ -29,62 +31,92 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/serializer" - "k8s.io/apimachinery/pkg/runtime/serializer/json" + jsonserializer "k8s.io/apimachinery/pkg/runtime/serializer/json" + "k8s.io/apimachinery/pkg/types" "github.com/Project-HAMi/dra-lib/api/checkpoint/install" - api "github.com/Project-HAMi/dra-lib/api/checkpoint/v1" + v1 "github.com/Project-HAMi/dra-lib/api/checkpoint/v1" + api "github.com/Project-HAMi/dra-lib/api/checkpoint/v2" ) // Options configure a Store. -type Options struct { +type Options[N, C, D any] 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 + // Extension holds the driver's own state. Nil for a store that keeps only + // the core; it then refuses files that carry driver payloads. + Extension *Extension[N, C, D] +} + +// Checkpoint is the core plus the typed driver state. Claims and Devices are +// keyed by claim UID; a Devices entry is index-aligned with the core claim's +// devices. Entries of claims that are not in the core are not written, so +// removing a core claim drops its driver state. +type Checkpoint[N, C, D any] struct { + Core *api.Checkpoint + Node *N + Claims map[types.UID]*C + Devices map[types.UID][]*D } // Store reads and writes the checkpoint file at one path. -type Store struct { +type Store[N, C, D any] struct { path string driverName string - gvk schema.GroupVersionKind + group string + ext *Extension[N, C, D] + v1GVK schema.GroupVersionKind decoder runtime.Decoder encoder runtime.Encoder } -func NewStore(path string, opts Options) (*Store, error) { +func NewStore[N, C, D any](path string, opts Options[N, C, D]) (*Store[N, C, D], error) { if opts.Group == "" || opts.DriverName == "" { return nil, errors.New("checkpoint store needs a group and a driver name") } + if ext := opts.Extension; ext != nil { + if ext.Name == "" || ext.Version < 1 { + return nil, errors.New("checkpoint extension needs a name and a version of at least 1") + } + for v := 1; v < ext.Version; v++ { + if ext.Migrations[v] == nil { + return nil, fmt.Errorf("checkpoint extension %s has no migration from version %d to %d", ext.Name, v, v+1) + } + } + } 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}) + serializerJSON := jsonserializer.NewSerializerWithOptions(jsonserializer.DefaultMetaFactory, scheme, scheme, + jsonserializer.SerializerOptions{Pretty: false, Strict: false}) codecs := serializer.NewCodecFactory(scheme) - versioned := schema.GroupVersion{Group: opts.Group, Version: api.Version} - return &Store{ + return &Store[N, C, D]{ path: path, driverName: opts.DriverName, + group: opts.Group, + ext: opts.Extension, // A file without apiVersion is read as v1. - gvk: versioned.WithKind(api.Kind), - decoder: codecs.UniversalDecoder(versioned), - encoder: codecs.EncoderForVersion(serializerJSON, versioned), + v1GVK: schema.GroupVersionKind{Group: opts.Group, Version: v1.Version, Kind: v1.Kind}, + decoder: codecs.UniversalDeserializer(), + encoder: codecs.EncoderForVersion(serializerJSON, schema.GroupVersion{Group: opts.Group, Version: api.Version}), }, 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. +// Read returns the checkpoint. A missing file is an empty checkpoint. A v1 +// checkpoint is converted to v2 and its payloads migrated to the extension's +// version; it is written as v2 by the next Write. A checkpoint in the legacy +// kubelet checkpointmanager format is migrated and written back at once. // // 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) { +func (s *Store[N, C, D]) Read() (*Checkpoint[N, C, D], error) { data, err := os.ReadFile(s.path) if errors.Is(err, fs.ErrNotExist) { - return &api.Checkpoint{DriverName: s.driverName}, nil + return s.typed(&api.Checkpoint{DriverName: s.driverName}) } if err != nil { return nil, err @@ -92,53 +124,343 @@ func (s *Store) Read() (*api.Checkpoint, error) { if isLegacy(data) { return s.migrateLegacy(data) } - checkpoint, err := s.decode(data) + return s.parse(data) +} + +func (s *Store[N, C, D]) parse(data []byte) (*Checkpoint[N, C, D], error) { + core, 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) + if core.DriverName != s.driverName { + return nil, fmt.Errorf("checkpoint %s has driverName %q, expected %q", s.path, core.DriverName, s.driverName) } - return checkpoint, nil + cp, err := s.typed(core) + if err != nil { + return nil, fmt.Errorf("checkpoint %s: %w", s.path, err) + } + return cp, 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 { +// decode decodes a v1 or v2 checkpoint into v2. Any other version or group is +// an error. The result has no TypeMeta; the store sets it when writing. +func (s *Store[N, C, D]) decode(data []byte) (*api.Checkpoint, error) { + gvk := s.v1GVK + obj, _, err := s.decoder.Decode(data, &gvk, nil) + if err != nil { + return nil, err + } + switch cp := obj.(type) { + case *api.Checkpoint: + cp.TypeMeta = metav1.TypeMeta{} + return cp, nil + case *v1.Checkpoint: + return s.fromV1(cp) + default: + return nil, fmt.Errorf("unexpected checkpoint type %T", obj) + } +} + +// fromV1 converts a v1 checkpoint. Its vendor sections become payloads of +// version 1 of the store's extension. +func (s *Store[N, C, D]) fromV1(old *v1.Checkpoint) (*api.Checkpoint, error) { + core, err := api.ConvertFromV1(old) + if err != nil { + return nil, fmt.Errorf("convert v1 checkpoint: %w", err) + } + if s.ext != nil && hasPayloads(core) { + core.Extension = &api.ExtensionRef{Name: s.ext.Name, Version: 1} + } + return core, nil +} + +// typed checks the extension of core, migrates its payloads to the store's +// extension version and decodes them. The payload fields of core are cleared: +// the typed fields hold that state until the next Write. +func (s *Store[N, C, D]) typed(core *api.Checkpoint) (*Checkpoint[N, C, D], error) { + if err := uniqueClaims(core); err != nil { + return nil, err + } + cp := &Checkpoint[N, C, D]{Core: core, Claims: map[types.UID]*C{}, Devices: map[types.UID][]*D{}} + ref := core.Extension + if s.ext == nil { + if ref != nil { + return nil, fmt.Errorf("has extension %s version %d, but the store has no extension", ref.Name, ref.Version) + } + if hasPayloads(core) { + return nil, errors.New("has driver payloads, but the store has no extension") + } + return cp, nil + } + if ref == nil { + if hasPayloads(core) { + return nil, errors.New("has driver payloads without an extension reference") + } + return cp, nil + } + if ref.Name != s.ext.Name { + return nil, fmt.Errorf("has extension %q, expected %q", ref.Name, s.ext.Name) + } + if ref.Version > int32(s.ext.Version) { + return nil, fmt.Errorf("has extension %s version %d, newer than version %d this driver reads", ref.Name, ref.Version, s.ext.Version) + } + if ref.Version < 1 { + return nil, fmt.Errorf("has extension %s with invalid version %d", ref.Name, ref.Version) + } + if err := s.migrate(core); err != nil { + return nil, err + } + if err := s.decodePayloads(cp); err != nil { return nil, err } - checkpoint.TypeMeta = metav1.TypeMeta{} - return checkpoint, nil + if err := s.validate(cp); err != nil { + return nil, err + } + return cp, nil +} + +func (s *Store[N, C, D]) migrate(core *api.Checkpoint) error { + ref := core.Extension + if int(ref.Version) == s.ext.Version { + return nil + } + raw := RawPayloads{Node: rawOf(core.Driver), Claims: map[types.UID]json.RawMessage{}, Devices: map[types.UID][]json.RawMessage{}} + for i := range core.PreparedClaims { + c := &core.PreparedClaims[i] + raw.Claims[c.UID] = rawOf(c.Driver) + devices := make([]json.RawMessage, len(c.Devices)) + for j := range c.Devices { + devices[j] = rawOf(c.Devices[j].Driver) + } + raw.Devices[c.UID] = devices + } + for v := int(ref.Version); v < s.ext.Version; v++ { + if err := s.ext.Migrations[v](&raw); err != nil { + return fmt.Errorf("migrate extension %s from version %d to %d: %w", s.ext.Name, v, v+1, err) + } + } + core.Driver = rawExtension(raw.Node) + for i := range core.PreparedClaims { + c := &core.PreparedClaims[i] + c.Driver = rawExtension(raw.Claims[c.UID]) + devices := raw.Devices[c.UID] + if len(devices) != len(c.Devices) { + return fmt.Errorf("migrate extension %s: claim %s has %d device payloads for %d devices", s.ext.Name, c.UID, len(devices), len(c.Devices)) + } + for j := range c.Devices { + c.Devices[j].Driver = rawExtension(devices[j]) + } + } + ref.Version = int32(s.ext.Version) + return nil +} + +func (s *Store[N, C, D]) decodePayloads(cp *Checkpoint[N, C, D]) error { + core := cp.Core + var err error + if cp.Node, err = decodePayload(s.ext.Node, core.Driver, "node"); err != nil { + return err + } + for i := range core.PreparedClaims { + c := &core.PreparedClaims[i] + claim, err := decodePayload(s.ext.Claim, c.Driver, "claim "+string(c.UID)) + if err != nil { + return err + } + if claim != nil { + cp.Claims[c.UID] = claim + } + var devices []*D + for j := range c.Devices { + if c.Devices[j].Driver == nil { + continue + } + if devices == nil { + devices = make([]*D, len(c.Devices)) + } + if devices[j], err = decodePayload(s.ext.Device, c.Devices[j].Driver, fmt.Sprintf("claim %s device %d", c.UID, j)); err != nil { + return err + } + } + if devices != nil { + cp.Devices[c.UID] = devices + } + } + clearPayloads(core) + return nil +} + +func (s *Store[N, C, D]) validate(cp *Checkpoint[N, C, D]) error { + if s.ext.Validate == nil { + return nil + } + if err := s.ext.Validate(cp); err != nil { + return fmt.Errorf("validate extension %s: %w", s.ext.Name, err) + } + return nil +} + +func decodePayload[T any](codec Codec[T], raw *runtime.RawExtension, what string) (*T, error) { + if raw == nil { + return nil, nil + } + if codec == nil { + return nil, fmt.Errorf("%s has a payload, but the extension has no codec for it", what) + } + v, err := codec.Decode(raw.Raw) + if err != nil { + return nil, fmt.Errorf("decode %s payload: %w", what, err) + } + return v, nil +} + +func encodePayload[T any](codec Codec[T], v *T, what string) (*runtime.RawExtension, error) { + if v == nil { + return nil, nil + } + if codec == nil { + return nil, fmt.Errorf("%s has state, but the extension has no codec for it", what) + } + raw, err := codec.Encode(v) + if err != nil { + return nil, fmt.Errorf("encode %s payload: %w", what, err) + } + return rawExtension(raw), nil +} + +func eachPayload(core *api.Checkpoint, f func(**runtime.RawExtension)) { + f(&core.Driver) + for i := range core.PreparedClaims { + c := &core.PreparedClaims[i] + f(&c.Driver) + for j := range c.Devices { + f(&c.Devices[j].Driver) + } + } +} + +func hasPayloads(core *api.Checkpoint) bool { + found := false + eachPayload(core, func(p **runtime.RawExtension) { found = found || *p != nil }) + return found +} + +func clearPayloads(core *api.Checkpoint) { + if core != nil { + eachPayload(core, func(p **runtime.RawExtension) { *p = nil }) + } +} + +func rawOf(re *runtime.RawExtension) json.RawMessage { + if re == nil { + return nil + } + return re.Raw +} + +// rawExtension wraps a payload; an absent or null payload is no payload. +func rawExtension(raw json.RawMessage) *runtime.RawExtension { + if len(raw) == 0 || string(raw) == "null" { + return nil + } + return &runtime.RawExtension{Raw: raw} } // 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() +func (s *Store[N, C, D]) Update(mutate func(*Checkpoint[N, C, D]) error) error { + cp, err := s.Read() if err != nil { return err } - if err := mutate(checkpoint); err != nil { + if err := mutate(cp); err != nil { + return err + } + return s.Write(cp) +} + +// Write atomically replaces the checkpoint file with cp as v2: 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[N, C, D]) Write(cp *Checkpoint[N, C, D]) error { + // The typed fields stay the source of the driver state. + defer func() { clearPayloads(cp.Core) }() + if err := s.prepareWrite(cp); err != nil { return err } - return s.Write(checkpoint) + return s.writeFile(cp.Core) } -// 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 { +func (s *Store[N, C, D]) prepareWrite(cp *Checkpoint[N, C, D]) error { + if cp.Core == nil { + cp.Core = &api.Checkpoint{} + } + switch cp.Core.DriverName { case "": - checkpoint.DriverName = s.driverName + cp.Core.DriverName = s.driverName case s.driverName: default: - return fmt.Errorf("checkpoint has driverName %q, expected %q", checkpoint.DriverName, s.driverName) + return fmt.Errorf("checkpoint has driverName %q, expected %q", cp.Core.DriverName, s.driverName) } + if err := uniqueClaims(cp.Core); err != nil { + return err + } + return s.encodePayloads(cp) +} + +// uniqueClaims checks that claims are keyed by UID, as the API list is. +func uniqueClaims(core *api.Checkpoint) error { + seen := make(map[types.UID]struct{}, len(core.PreparedClaims)) + for i := range core.PreparedClaims { + uid := core.PreparedClaims[i].UID + if _, dup := seen[uid]; dup { + return fmt.Errorf("duplicate claim %q", uid) + } + seen[uid] = struct{}{} + } + return nil +} + +func (s *Store[N, C, D]) encodePayloads(cp *Checkpoint[N, C, D]) error { + core := cp.Core + if s.ext == nil { + if core.Extension != nil || hasPayloads(core) || cp.Node != nil || len(cp.Claims) > 0 || len(cp.Devices) > 0 { + return errors.New("checkpoint has driver state, but the store has no extension") + } + return nil + } + if err := s.validate(cp); err != nil { + return err + } + core.Extension = &api.ExtensionRef{Name: s.ext.Name, Version: int32(s.ext.Version)} + var err error + if core.Driver, err = encodePayload(s.ext.Node, cp.Node, "node"); err != nil { + return err + } + for i := range core.PreparedClaims { + c := &core.PreparedClaims[i] + if c.Driver, err = encodePayload(s.ext.Claim, cp.Claims[c.UID], "claim "+string(c.UID)); err != nil { + return err + } + devices := cp.Devices[c.UID] + if len(devices) > len(c.Devices) { + return fmt.Errorf("claim %s has %d device payloads for %d devices", c.UID, len(devices), len(c.Devices)) + } + for j := range c.Devices { + var d *D + if j < len(devices) { + d = devices[j] + } + if c.Devices[j].Driver, err = encodePayload(s.ext.Device, d, fmt.Sprintf("claim %s device %d", c.UID, j)); err != nil { + return err + } + } + } + return nil +} + +func (s *Store[N, C, D]) writeFile(core *api.Checkpoint) (err error) { dir := filepath.Dir(s.path) tmp, err := os.CreateTemp(dir, "tmp-checkpoint-*") if err != nil { @@ -152,7 +474,7 @@ func (s *Store) Write(checkpoint *api.Checkpoint) (err error) { _ = os.Remove(tmp.Name()) } }() - if err := s.encoder.Encode(checkpoint, tmp); err != nil { + if err := s.encoder.Encode(core, tmp); err != nil { return fmt.Errorf("encode to temp file %s: %w", tmp.Name(), err) } if err := tmp.Sync(); err != nil { diff --git a/checkpoint/store_test.go b/checkpoint/store_test.go index 303ce0e..234af0d 100644 --- a/checkpoint/store_test.go +++ b/checkpoint/store_test.go @@ -17,7 +17,7 @@ limitations under the License. package checkpoint import ( - "bytes" + "encoding/json" "errors" "fmt" "os" @@ -29,131 +29,406 @@ import ( "github.com/stretchr/testify/require" resourcev1 "k8s.io/api/resource/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" "k8s.io/utils/ptr" cdispec "tags.cncf.io/container-device-interface/specs-go" api "github.com/Project-HAMi/dra-lib/api/checkpoint/v1" + apiv2 "github.com/Project-HAMi/dra-lib/api/checkpoint/v2" ) const ( - testGroup = "checkpoint.internal.example.com" - testDriver = "gpu.example.com" + testGroup = "checkpoint.internal.example.com" + testDriver = "gpu.example.com" + testExtension = "gpu.example.com" ) -func newTestStore(t *testing.T) (*Store, string) { +// The test extension is version 1 of a driver extension: the payload shape +// of the v1 vendor sections (see apiv2.ConvertFromV1). +type testNode struct { + Partitioning *api.NodePartitioning `json:"partitioning,omitempty"` +} + +type testClaim struct { + NVIDIA *api.NVIDIAClaim `json:"nvidia,omitempty"` +} + +type testDevice struct { + Partition *api.Partition `json:"partition,omitempty"` + AMD *api.AMDDevice `json:"amd,omitempty"` + NVIDIA *api.NVIDIADevice `json:"nvidia,omitempty"` +} + +type ( + testStore = Store[testNode, testClaim, testDevice] + testCheckpoint = Checkpoint[testNode, testClaim, testDevice] + testExt = Extension[testNode, testClaim, testDevice] +) + +func newTestExtension() *testExt { + return &testExt{ + Name: testExtension, + Version: 1, + Node: JSONCodec[testNode]{}, + Claim: JSONCodec[testClaim]{}, + Device: JSONCodec[testDevice]{}, + } +} + +func openStore(t testing.TB, path, driverName string, ext *testExt) *testStore { + t.Helper() + s, err := NewStore(path, Options[testNode, testClaim, testDevice]{Group: testGroup, DriverName: driverName, Extension: ext}) + require.NoError(t, err) + return s +} + +func newTestStore(t testing.TB) (*testStore, string) { + t.Helper() + path := filepath.Join(t.TempDir(), "checkpoint.json") + return openStore(t, path, testDriver, newTestExtension()), path +} + +func seedFile(t *testing.T, data []byte) string { t.Helper() path := filepath.Join(t.TempDir(), "checkpoint.json") - s, err := NewStore(path, Options{Group: testGroup, DriverName: testDriver}) + require.NoError(t, os.WriteFile(path, data, 0o600)) + return path +} + +func readFile(t *testing.T, path string) []byte { + t.Helper() + data, err := os.ReadFile(path) require.NoError(t, err) - return s, path + return data } -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 v2File(rest string) string { + return `{"apiVersion":"` + testGroup + `/v2","kind":"Checkpoint","driverName":"` + testDriver + `"` + rest + `}` +} + +// assertRefused checks that read fails with msg and leaves the file alone. +func assertRefused(t *testing.T, read func() error, path string, data []byte, msg string) { + t.Helper() + assert.ErrorContains(t, read(), msg) + assert.Equal(t, string(data), string(readFile(t, path))) +} + +func readErr[N, C, D any](s *Store[N, C, D]) func() error { + return func() error { _, err := s.Read(); return err } +} + +func emptyCheckpoint() *testCheckpoint { + return &testCheckpoint{Core: &apiv2.Checkpoint{DriverName: testDriver}, Claims: map[types.UID]*testClaim{}, Devices: map[types.UID][]*testDevice{}} +} + +func sampleCheckpoint() *testCheckpoint { + cp := emptyCheckpoint() + cp.Core.Extension = &apiv2.ExtensionRef{Name: testExtension, Version: 1} + cp.Core.NodeBootID = "boot-1" + cp.Core.PreparedClaims = []apiv2.PreparedClaim{{ + UID: "uid-1", + State: apiv2.PrepareStateCompleted, + Devices: []apiv2.PreparedDevice{{ + Device: apiv2.Device{Requests: []string{"gpu"}, PoolName: "node-a", DeviceName: "gpu-0", CDIDeviceIDs: []string{"example.com/gpu=uid-1-gpu-0"}, ShareID: ptr.To(types.UID("share-1"))}, + ContainerEdits: &apiv2.ContainerEdits{ContainerEdits: cdispec.ContainerEdits{Env: []string{"A=1"}}}, }}, + }} + cp.Node = &testNode{Partitioning: &api.NodePartitioning{Modes: []api.PartitionMode{{Kind: api.PartitionModeKindMemory, Mode: "nps4"}}}} + cp.Devices["uid-1"] = []*testDevice{{Partition: &api.Partition{Type: api.PartitionTypeSoft, Cores: ptr.To[int32](50)}}} + return cp +} + +// typedFromV1 is what the test store reads from a v1 checkpoint once it has +// written it as v2, built field by field rather than through +// apiv2.ConvertFromV1. +func typedFromV1(in *api.Checkpoint) *testCheckpoint { + cp := emptyCheckpoint() + cp.Core.DriverName = in.DriverName + cp.Core.NodeBootID = in.NodeBootID + cp.Core.Extension = &apiv2.ExtensionRef{Name: testExtension, Version: 1} + if in.Partitioning != nil { + cp.Node = &testNode{Partitioning: in.Partitioning} } + for _, c := range in.PreparedClaims { + claim := apiv2.PreparedClaim{UID: c.UID, Name: c.Name, Namespace: c.Namespace, State: apiv2.PrepareState(c.State), AbortedAt: c.AbortedAt, Status: c.Status} + if c.NVIDIA != nil { + cp.Claims[c.UID] = &testClaim{NVIDIA: c.NVIDIA} + } + var devices []*testDevice + for j, d := range c.Devices { + dev := apiv2.PreparedDevice{Device: apiv2.Device{ + Requests: d.Device.Requests, PoolName: d.Device.PoolName, DeviceName: d.Device.DeviceName, + CDIDeviceIDs: d.Device.CDIDeviceIDs, ShareID: d.Device.ShareID, + }} + if m := d.Device.Metadata; m != nil { + dev.Device.Metadata = &apiv2.DeviceMetadata{Attributes: m.Attributes, NetworkData: m.NetworkData} + } + if d.ContainerEdits != nil { + dev.ContainerEdits = &apiv2.ContainerEdits{ContainerEdits: d.ContainerEdits.ContainerEdits} + } + claim.Devices = append(claim.Devices, dev) + if d.Partition != nil || d.AMD != nil || d.NVIDIA != nil { + if devices == nil { + devices = make([]*testDevice, len(c.Devices)) + } + devices[j] = &testDevice{Partition: d.Partition, AMD: d.AMD, NVIDIA: d.NVIDIA} + } + } + if devices != nil { + cp.Devices[c.UID] = devices + } + cp.Core.PreparedClaims = append(cp.Core.PreparedClaims, claim) + } + return cp } 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.Equal(t, emptyCheckpoint(), 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"`) + require.NoError(t, s.Write(sampleCheckpoint())) + data := string(readFile(t, path)) + assert.Contains(t, data, `"apiVersion":"`+testGroup+`/v2"`) + assert.Contains(t, data, `"kind":"Checkpoint"`) + assert.Contains(t, data, `"extension":{"name":"`+testExtension+`","version":1}`) + assert.Contains(t, data, `"driver":{"partition":{"type":"Soft","cores":50}}`) + assert.NotContains(t, strings.TrimSuffix(data, "\n"), "\n", "checkpoint must be written on a single line") got, err := s.Read() require.NoError(t, err) - assert.Equal(t, want, got) + assert.Equal(t, sampleCheckpoint(), 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) +func TestWriteKeepsTypedStateAsTheSource(t *testing.T) { + s, _ := newTestStore(t) + cp := sampleCheckpoint() + require.NoError(t, s.Write(cp)) + assert.Nil(t, cp.Core.PreparedClaims[0].Devices[0].Driver, "payloads live in the typed fields between writes") + cp.Devices["uid-1"][0].Partition.Cores = ptr.To[int32](25) + require.NoError(t, s.Write(cp)) + got, err := s.Read() require.NoError(t, err) - assert.NotContains(t, strings.TrimSuffix(string(data), "\n"), "\n", "checkpoint must be written on a single line") + assert.Equal(t, int32(25), *got.Devices["uid-1"][0].Partition.Cores) } -func TestWriteSetsDriverName(t *testing.T) { +func TestWriteDropsStateOfRemovedClaims(t *testing.T) { s, _ := newTestStore(t) cp := sampleCheckpoint() - cp.DriverName = "" + cp.Claims["gone"] = &testClaim{NVIDIA: &api.NVIDIAClaim{}} + cp.Devices["gone"] = []*testDevice{{AMD: &api.AMDDevice{ShareKey: "k"}}} require.NoError(t, s.Write(cp)) got, err := s.Read() require.NoError(t, err) - assert.Equal(t, testDriver, got.DriverName) + assert.Equal(t, sampleCheckpoint(), got) } -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 TestWriteRejects(t *testing.T) { + for name, tc := range map[string]struct { + mutate func(*testCheckpoint) + err string + }{ + "too many device payloads": {func(cp *testCheckpoint) { cp.Devices["uid-1"] = append(cp.Devices["uid-1"], &testDevice{}) }, "2 device payloads for 1 devices"}, + "other driver": {func(cp *testCheckpoint) { cp.Core.DriverName = "other.example.com" }, "other.example.com"}, + } { + t.Run(name, func(t *testing.T) { + s, path := newTestStore(t) + cp := sampleCheckpoint() + tc.mutate(cp) + assert.ErrorContains(t, s.Write(cp), tc.err) + 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"}) +func TestWriteSetsDriverName(t *testing.T) { + s, _ := newTestStore(t) + cp := sampleCheckpoint() + cp.Core.DriverName = "" + require.NoError(t, s.Write(cp)) + got, err := s.Read() require.NoError(t, err) - _, err = other.Read() - assert.ErrorContains(t, err, testDriver) - assert.ErrorContains(t, err, "other.example.com") + assert.Equal(t, testDriver, got.Core.DriverName) } -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 TestNewStoreValidatesOptions(t *testing.T) { + type opts = Options[testNode, testClaim, testDevice] + for name, o := range map[string]opts{ + "no group": {DriverName: testDriver}, + "no driver": {Group: testGroup}, + "extension no name": {Group: testGroup, DriverName: testDriver, Extension: &testExt{Version: 1}}, + "extension version 0": {Group: testGroup, DriverName: testDriver, Extension: &testExt{Name: testExtension}}, + "missing migration 1": {Group: testGroup, DriverName: testDriver, Extension: &testExt{Name: testExtension, Version: 2}}, + } { + t.Run(name, func(t *testing.T) { + _, err := NewStore("checkpoint.json", o) + assert.Error(t, err) + }) + } } -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) +// Every refusal leaves the file alone: a newer driver wrote it, or another +// driver, and nothing here may drop its state. +func TestReadRefusesUnknownSchemaLoudly(t *testing.T) { + coreOnly := func(t *testing.T, path string) func() error { + s, err := NewStore(path, Options[None, None, None]{Group: testGroup, DriverName: testDriver}) + require.NoError(t, err) + return readErr(s) + } + withExt := func(t *testing.T, path string) func() error { + return readErr(openStore(t, path, testDriver, newTestExtension())) + } + otherDriver := func(t *testing.T, path string) func() error { + return readErr(openStore(t, path, "other.example.com", newTestExtension())) + } + noNodeCodec := func(t *testing.T, path string) func() error { + ext := newTestExtension() + ext.Node = nil + return readErr(openStore(t, path, testDriver, ext)) + } + for name, tc := range map[string]struct { + data string + store func(*testing.T, string) func() error + err string + }{ + "newer core version": { + `{"apiVersion":"` + testGroup + `/v3","kind":"Checkpoint","driverName":"` + testDriver + `"}`, withExt, "v3", + }, + "other group": { + `{"apiVersion":"checkpoint.internal.other.com/v2","kind":"Checkpoint","driverName":"` + testDriver + `"}`, withExt, "checkpoint.internal.other.com", + }, + "corrupt": {`{"apiVersion":"` + testGroup + `/v2","kind":"Checkpoint","preparedClaims":`, withExt, "decode checkpoint"}, + "missing driver name": {`{"apiVersion":"` + testGroup + `/v2","kind":"Checkpoint"}`, withExt, "driverName"}, + "other driver": {v2File(""), otherDriver, testDriver}, + "newer extension version": { + v2File(`,"extension":{"name":"` + testExtension + `","version":2}`), withExt, "newer than version 1", + }, + "other extension": { + v2File(`,"extension":{"name":"other.example.com","version":1}`), withExt, "other.example.com", + }, + "payload without extension reference": { + v2File(`,"driver":{"x":1}`), withExt, "without an extension reference", + }, + "extension in a core-only store": { + v2File(`,"extension":{"name":"` + testExtension + `","version":1}`), coreOnly, "the store has no extension", + }, + "payload in a core-only store": { + v2File(`,"preparedClaims":[{"uid":"a","devices":[{"device":{"poolName":"p","deviceName":"d"},"driver":{"x":1}}]}]`), coreOnly, "the store has no extension", + }, + "v1 vendor state in a core-only store": { + `{"apiVersion":"` + testGroup + `/v1","kind":"Checkpoint","driverName":"` + testDriver + `","partitioning":{"modes":[{"kind":"memory","mode":"nps4"}]}}`, coreOnly, "the store has no extension", + }, + "payload at a level without a codec": { + v2File(`,"extension":{"name":"` + testExtension + `","version":1},"driver":{"x":1}`), noNodeCodec, "no codec", + }, + "duplicate claim in a core-only store": { + `{"driverName":"` + testDriver + `","preparedClaims":[{},{}]}`, coreOnly, `duplicate claim ""`, + }, + "duplicate claim": { + v2File(`,"extension":{"name":"` + testExtension + `","version":1},"preparedClaims":[{"uid":"a"},{"uid":"a"}]`), withExt, `duplicate claim "a"`, + }, + } { + t.Run(name, func(t *testing.T) { + path := seedFile(t, []byte(tc.data)) + assertRefused(t, tc.store(t, path), path, []byte(tc.data), tc.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 TestCoreOnlyStore(t *testing.T) { + path := filepath.Join(t.TempDir(), "checkpoint.json") + s, err := NewStore(path, Options[None, None, None]{Group: testGroup, DriverName: testDriver}) + require.NoError(t, err) + cp := &Checkpoint[None, None, None]{Core: &apiv2.Checkpoint{PreparedClaims: []apiv2.PreparedClaim{{UID: "uid-1"}}}} + require.NoError(t, s.Write(cp)) + assert.NotContains(t, string(readFile(t, path)), `"extension"`) + got, err := s.Read() + require.NoError(t, err) + assert.Equal(t, []apiv2.PreparedClaim{{UID: "uid-1"}}, got.Core.PreparedClaims) + + cp.Devices = map[types.UID][]*None{"uid-1": {{}}} + assert.ErrorContains(t, s.Write(cp), "the store has no extension") } -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) +// testDeviceV2 is version 2 of the test extension: the AMD share key moved +// out of its own section. +type testDeviceV2 struct { + Partition *api.Partition `json:"partition,omitempty"` + ShareKey string `json:"shareKey,omitempty"` +} + +func TestReadMigratesExtensionForward(t *testing.T) { + path := seedFile(t, []byte(`{"apiVersion":"`+testGroup+`/v1","kind":"Checkpoint","driverName":"`+testDriver+`","preparedClaims":[{"uid":"a","devices":[`+ + `{"device":{"poolName":"p","deviceName":"d0"},"amd":{"shareKey":"k0"}},{"device":{"poolName":"p","deviceName":"d1"}}]}]}`)) + ext := &Extension[None, None, testDeviceV2]{ + Name: testExtension, Version: 2, Device: JSONCodec[testDeviceV2]{}, + Migrations: map[int]func(*RawPayloads) error{1: func(raw *RawPayloads) error { + for uid, devices := range raw.Devices { + for j, d := range devices { + if d == nil { + continue + } + var old testDevice + if err := json.Unmarshal(d, &old); err != nil { + return err + } + next := testDeviceV2{Partition: old.Partition} + if old.AMD != nil { + next.ShareKey = old.AMD.ShareKey + } + data, err := json.Marshal(next) + if err != nil { + return err + } + raw.Devices[uid][j] = data + } + } + return nil + }}, + } + s, err := NewStore(path, Options[None, None, testDeviceV2]{Group: testGroup, DriverName: testDriver, Extension: ext}) + require.NoError(t, err) + got, err := s.Read() + require.NoError(t, err) + assert.Equal(t, &apiv2.ExtensionRef{Name: testExtension, Version: 2}, got.Core.Extension) + assert.Equal(t, map[types.UID][]*testDeviceV2{"a": {{ShareKey: "k0"}, nil}}, got.Devices) + + require.NoError(t, s.Write(got)) + data := string(readFile(t, path)) + assert.Contains(t, data, `"apiVersion":"`+testGroup+`/v2"`) + assert.Contains(t, data, `"extension":{"name":"`+testExtension+`","version":2}`) + assert.Contains(t, data, `"driver":{"shareKey":"k0"}`) +} + +func TestReadUsesExtensionLegacyReaders(t *testing.T) { + legacy := readFile(t, "testdata/legacy-ascend.json") + var calls []string + ext := newTestExtension() + ext.Legacy = []func([]byte) (*testCheckpoint, error){ + func([]byte) (*testCheckpoint, error) { calls = append(calls, "other"); return nil, ErrNotThisLayout }, + func([]byte) (*testCheckpoint, error) { + calls = append(calls, "mine") + return &testCheckpoint{Core: &apiv2.Checkpoint{NodeBootID: "from-extension"}}, nil + }, + } + got, err := openStore(t, seedFile(t, legacy), testDriver, ext).Read() + require.NoError(t, err) + assert.Equal(t, []string{"other", "mine"}, calls) + assert.Equal(t, "from-extension", got.Core.NodeBootID) + assert.Equal(t, testDriver, got.Core.DriverName) + + ext.Legacy = ext.Legacy[:1] + got, err = openStore(t, seedFile(t, legacy), testDriver, ext).Read() + require.NoError(t, err) + assert.Equal(t, typedFromV1(ascendLegacyCheckpoint()), got, "the built-in reader is the fallback") } func amdLegacyCheckpoint() *api.Checkpoint { @@ -255,58 +530,63 @@ func nvidiaV1LegacyCheckpoint() *api.Checkpoint { 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(), - } { +// testMigratesLegacy reads each legacy fixture with the built-in reader and +// through the store, which writes it as v2 once. +func testMigratesLegacy(t *testing.T, fixtures map[string]*api.Checkpoint) { + for fixture, want := range fixtures { t.Run(filepath.Base(fixture), func(t *testing.T) { - legacy, err := os.ReadFile(fixture) + legacy := readFile(t, fixture) + old, err := readLegacy(legacy) require.NoError(t, err) - s, path := newTestStore(t) - require.NoError(t, os.WriteFile(path, legacy, 0o600)) + old.DriverName = testDriver + assert.Equal(t, want, old) + path := seedFile(t, legacy) + s := openStore(t, path, testDriver, newTestExtension()) 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.Equal(t, typedFromV1(want), got) + migrated := readFile(t, path) + assert.Contains(t, string(migrated), `"apiVersion":"`+testGroup+`/v2"`) 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) + assert.Equal(t, typedFromV1(want), got) + assert.Equal(t, migrated, readFile(t, path)) }) } } +func TestReadMigratesLegacy(t *testing.T) { + testMigratesLegacy(t, 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(), + }) +} + 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`}, + helper, _ := helperLegacyCheckpoint(t) + var cp legacyTestCheckpoint + require.NoError(t, cp.unmarshal(helper)) + for name, tc := range map[string]struct { + data []byte + old, new string + }{ + "legacy-amd.json": {readFile(t, "testdata/legacy-amd.json"), `"activeMemoryMode":"nps4"`, `"activeMemoryMode":"nps1"`}, + "legacy-ascend.json": {readFile(t, "testdata/legacy-ascend.json"), `"device_name":"npu-2"`, `"device_name":"npu-3"`}, + "legacy-nvidia.json": {readFile(t, "testdata/legacy-nvidia.json"), `"nodeBootID":"boot-id-1"`, `"nodeBootID":"boot-id-2"`}, // v2 checksum only + "legacy-nvidia-v1.json": {readFile(t, "testdata/legacy-nvidia-v1.json"), `"giId":2`, `"giId":3`}, + "helper checksum": {helper, fmt.Sprintf(`"checksum":%d`, cp.Checksum), fmt.Sprintf(`"checksum":%d`, cp.Checksum+1)}, } { - 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") + t.Run(name, func(t *testing.T) { + tampered := []byte(strings.Replace(string(tc.data), tc.old, tc.new, 1)) + require.NotEqual(t, tc.data, tampered) + path := seedFile(t, tampered) + assertRefused(t, readErr(openStore(t, path, testDriver, newTestExtension())), path, tampered, "checksum") }) } } @@ -315,24 +595,24 @@ 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:] + require.NoError(t, s.Update(func(cp *testCheckpoint) error { + cp.Core.PreparedClaims = append(cp.Core.PreparedClaims, apiv2.PreparedClaim{UID: "uid-2"}, apiv2.PreparedClaim{UID: "uid-3"}) + cp.Core.PreparedClaims = cp.Core.PreparedClaims[1:] + cp.Claims["uid-3"] = &testClaim{NVIDIA: &api.NVIDIAClaim{}} return nil })) got, err := s.Read() require.NoError(t, err) - assert.Equal(t, []api.PreparedClaim{{UID: "uid-2"}, {UID: "uid-3"}}, got.PreparedClaims) + assert.Equal(t, []apiv2.PreparedClaim{{UID: "uid-2"}, {UID: "uid-3"}}, got.Core.PreparedClaims) + assert.Equal(t, map[types.UID]*testClaim{"uid-3": {NVIDIA: &api.NVIDIAClaim{}}}, got.Claims) + assert.Empty(t, got.Devices, "the removed claim's device state is gone with it") - before, err := os.ReadFile(path) - require.NoError(t, err) - assert.ErrorContains(t, s.Update(func(cp *api.Checkpoint) error { - cp.PreparedClaims = nil + before := readFile(t, path) + assert.ErrorContains(t, s.Update(func(cp *testCheckpoint) error { + cp.Core.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") + assert.Equal(t, before, readFile(t, path), "a failed update must not write") } func TestReadSeesChangesFromOtherWriters(t *testing.T) { @@ -341,15 +621,14 @@ func TestReadSeesChangesFromOtherWriters(t *testing.T) { _, 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"})) + other := openStore(t, path, testDriver, newTestExtension()) + require.NoError(t, other.Write(&testCheckpoint{Core: &apiv2.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) + assert.Equal(t, "boot-2", got.Core.NodeBootID) + require.NoError(t, s.Update(func(cp *testCheckpoint) error { + assert.Equal(t, "boot-2", cp.Core.NodeBootID) return nil })) } @@ -373,32 +652,40 @@ func TestWriteSyncsDirectoryAfterRename(t *testing.T) { 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) { +// v1CheckpointWant is testdata/v1-checkpoint.json, a v1 file as dra-lib +// v0.1.0 wrote it. +func v1CheckpointWant() *api.Checkpoint { want := nvidiaLegacyCheckpoint() amd := amdLegacyCheckpoint() want.Partitioning = amd.Partitioning want.PreparedClaims = append(want.PreparedClaims, amd.PreparedClaims...) want.PreparedClaims[2].UID = "claim-uid-3" + return want +} - data, err := os.ReadFile("testdata/v1-checkpoint.json") - require.NoError(t, err) - s, path := newTestStore(t) - require.NoError(t, os.WriteFile(path, data, 0o600)) +// The v1 reader is pinned: testdata/v1-checkpoint.json decodes as v1, converts +// to v2 with its vendor sections as payloads of extension version 1, and is +// written as testdata/v2-from-v1-checkpoint.json. +func TestReadV1File(t *testing.T) { + data := readFile(t, "testdata/v1-checkpoint.json") + path := seedFile(t, data) + s := openStore(t, path, testDriver, newTestExtension()) got, err := s.Read() require.NoError(t, err) - assert.Equal(t, want, got) + assert.Equal(t, typedFromV1(v1CheckpointWant()), got) + assert.Equal(t, data, readFile(t, path), "reading a v1 file does not write") require.NoError(t, s.Write(got)) - written, err := os.ReadFile(path) + assert.Equal(t, string(readFile(t, "testdata/v2-from-v1-checkpoint.json")), string(readFile(t, path))) + + again, err := s.Read() require.NoError(t, err) - assert.Equal(t, string(data), string(written)) + assert.Equal(t, typedFromV1(v1CheckpointWant()), again) } // 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) { +func helperLegacyCheckpoint(t *testing.T) ([]byte, *testCheckpoint) { t.Helper() edits := cdispec.ContainerEdits{Env: []string{"A=1"}, DeviceNodes: []*cdispec.DeviceNode{{Path: "/dev/kfd"}}} legacy := &legacyTestCheckpoint{V1: &legacyTestClaimsV1{PreparedClaims: map[string][]*legacyTestDevice{ @@ -407,7 +694,7 @@ func helperLegacyCheckpoint(t *testing.T) ([]byte, *api.Checkpoint) { }}} data, err := legacy.marshal() require.NoError(t, err) - return data, &api.Checkpoint{ + return data, typedFromV1(&api.Checkpoint{ DriverName: testDriver, PreparedClaims: []api.PreparedClaim{ {UID: "uid-a", Devices: []api.PreparedDevice{{ @@ -416,29 +703,12 @@ func helperLegacyCheckpoint(t *testing.T) ([]byte, *api.Checkpoint) { }}}, {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() + got, err := openStore(t, seedFile(t, data), testDriver, newTestExtension()).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/FuzzDecode/0aa010a38fddf57f similarity index 100% rename from checkpoint/testdata/fuzz/FuzzDecodeV1/0aa010a38fddf57f rename to checkpoint/testdata/fuzz/FuzzDecode/0aa010a38fddf57f diff --git a/checkpoint/testdata/fuzz/FuzzDecode/20d7e85442f9cee0 b/checkpoint/testdata/fuzz/FuzzDecode/20d7e85442f9cee0 new file mode 100644 index 0000000..f90458d --- /dev/null +++ b/checkpoint/testdata/fuzz/FuzzDecode/20d7e85442f9cee0 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("{\"driverName\":\"gpu.example.com\",\"preparedClaims\":[{},{}]}") diff --git a/checkpoint/testdata/legacy-nvidia-cd-2503rc2.json b/checkpoint/testdata/legacy-nvidia-cd-2503rc2.json new file mode 100644 index 0000000..bf771de --- /dev/null +++ b/checkpoint/testdata/legacy-nvidia-cd-2503rc2.json @@ -0,0 +1 @@ +{"checksum":2340767533,"v1":{"preparedClaims":{"claim-uid-1":[{"devices":[{"channel":{"info":{"id":5},"device":{"request_names":["channel"],"pool_name":"node-a","device_name":"channel-0","cdi_device_ids":["k8s.compute-domain.nvidia.com/device=channel-0"]}},"daemon":null}],"configState":{"Type":"channel","ComputeDomain":"domain-a"}},{"devices":[{"channel":null,"daemon":{"info":{"id":0},"device":{"request_names":["daemon"],"pool_name":"node-a","device_name":"daemon-0","cdi_device_ids":["k8s.compute-domain.nvidia.com/device=daemon-0"]}}}],"configState":{"Type":"daemon","ComputeDomain":"domain-b"}}]}}} diff --git a/checkpoint/testdata/legacy-nvidia-cd-v1.json b/checkpoint/testdata/legacy-nvidia-cd-v1.json new file mode 100644 index 0000000..c76e945 --- /dev/null +++ b/checkpoint/testdata/legacy-nvidia-cd-v1.json @@ -0,0 +1 @@ +{"checksum":4288992558,"v1":{"preparedClaims":{"claim-uid-1":{"status":{"allocation":{"devices":{"results":[{"request":"channel","driver":"compute-domain.nvidia.com","pool":"node-a","device":"channel-0"}]}}},"preparedDevices":[{"devices":[{"channel":{"info":{"id":5},"device":{"Requests":["channel"],"PoolName":"node-a","DeviceName":"channel-0","CDIDeviceIDs":["k8s.compute-domain.nvidia.com/device=channel-0"]}},"daemon":null}],"configState":{"Type":"channel","ComputeDomain":"domain-a"}},{"devices":[{"channel":null,"daemon":{"info":{"id":0},"device":{"Requests":["daemon"],"PoolName":"node-a","DeviceName":"daemon-0","CDIDeviceIDs":["k8s.compute-domain.nvidia.com/device=daemon-0"]}}}],"configState":{"Type":"daemon","ComputeDomain":"domain-b"}}]}}}} diff --git a/checkpoint/testdata/legacy-nvidia-cd.json b/checkpoint/testdata/legacy-nvidia-cd.json new file mode 100644 index 0000000..c98bf00 --- /dev/null +++ b/checkpoint/testdata/legacy-nvidia-cd.json @@ -0,0 +1 @@ +{"checksum":4288992558,"v1":{"preparedClaims":{"claim-uid-1":{"status":{"allocation":{"devices":{"results":[{"request":"channel","driver":"compute-domain.nvidia.com","pool":"node-a","device":"channel-0"}]}}},"preparedDevices":[{"devices":[{"channel":{"info":{"id":5},"device":{"Requests":["channel"],"PoolName":"node-a","DeviceName":"channel-0","CDIDeviceIDs":["k8s.compute-domain.nvidia.com/device=channel-0"]}},"daemon":null}],"configState":{"Type":"channel","ComputeDomain":"domain-a"}},{"devices":[{"channel":null,"daemon":{"info":{"id":0},"device":{"Requests":["daemon"],"PoolName":"node-a","DeviceName":"daemon-0","CDIDeviceIDs":["k8s.compute-domain.nvidia.com/device=daemon-0"]}}}],"configState":{"Type":"daemon","ComputeDomain":"domain-b"}}]}}},"v2":{"checksum":2809985884,"preparedClaims":{"claim-uid-1":{"checkpointState":"PrepareCompleted","status":{"allocation":{"devices":{"results":[{"request":"channel","driver":"compute-domain.nvidia.com","pool":"node-a","device":"channel-0"}]}}},"preparedDevices":[{"devices":[{"channel":{"info":{"id":5},"device":{"Requests":["channel"],"PoolName":"node-a","DeviceName":"channel-0","CDIDeviceIDs":["k8s.compute-domain.nvidia.com/device=channel-0"]}},"daemon":null}],"configState":{"Type":"channel","ComputeDomain":"domain-a"}},{"devices":[{"channel":null,"daemon":{"info":{"id":0},"device":{"Requests":["daemon"],"PoolName":"node-a","DeviceName":"daemon-0","CDIDeviceIDs":["k8s.compute-domain.nvidia.com/device=daemon-0"]}}}],"configState":{"Type":"daemon","ComputeDomain":"domain-b"}}],"name":"claim-1","namespace":"default"},"claim-uid-2":{"checkpointState":"PrepareStarted","status":{"allocation":{"devices":{"results":[{"request":"channel","driver":"compute-domain.nvidia.com","pool":"node-a","device":"channel-0"}]}}},"name":"claim-2","namespace":"team-a"},"claim-uid-3":{"checkpointState":"PrepareAborted","status":{"allocation":{"devices":{"results":[{"request":"channel","driver":"compute-domain.nvidia.com","pool":"node-a","device":"channel-0"}]}}},"name":"claim-3","namespace":"team-a","abortedAt":"2025-11-30T00:00:00Z"}},"nodeBootID":"boot-id-1"}} diff --git a/checkpoint/testdata/legacy-nvidia-gpu-v1.json b/checkpoint/testdata/legacy-nvidia-gpu-v1.json new file mode 100644 index 0000000..8590dce --- /dev/null +++ b/checkpoint/testdata/legacy-nvidia-gpu-v1.json @@ -0,0 +1 @@ +{"checksum":346381570,"v1":{"preparedClaims":{"claim-uid-1":{"status":{"allocation":{"devices":{"results":[{"request":"gpu","driver":"gpu.nvidia.com","pool":"node-a","device":"gpu-0"}]}}},"preparedDevices":[{"devices":[{"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":"","timeSliceApplied":true}},{"devices":[{"gpu":null,"mig":{"concrete":{"parentMinor":1,"giId":2,"ciId":0,"migUUID":"MIG-cccc","parentUUID":"GPU-dddd","parentPCIBusID":"0000:3b:00.0"},"device":{"Requests":["mig"],"PoolName":"node-a","DeviceName":"gpu-1-mig-1g10gb-2","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-1-mig-1g10gb-2"]}}}],"configState":{"mpsControlDaemonID":"mps-claim-uid-1"}},{"devices":[{"gpu":null,"mig":null,"vfio":{"info":{"uuid":"GPU-eeee","pciBusID":"0000:5e:00.0"},"device":{"Requests":["vfio"],"PoolName":"node-a","DeviceName":"gpu-3-vfio","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-3-vfio"],"Metadata":{"Attributes":{"productName":{"string":"NVIDIA A100"},"resource.kubernetes.io/pciBusID":{"string":"0000:5e:00.0"}},"NetworkData":null}}}}],"configState":{"mpsControlDaemonID":"","timeSliceApplied":false}}]}}}} diff --git a/checkpoint/testdata/legacy-nvidia-gpu.json b/checkpoint/testdata/legacy-nvidia-gpu.json new file mode 100644 index 0000000..760771a --- /dev/null +++ b/checkpoint/testdata/legacy-nvidia-gpu.json @@ -0,0 +1 @@ +{"checksum":346381570,"v1":{"preparedClaims":{"claim-uid-1":{"status":{"allocation":{"devices":{"results":[{"request":"gpu","driver":"gpu.nvidia.com","pool":"node-a","device":"gpu-0"}]}}},"preparedDevices":[{"devices":[{"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":"","timeSliceApplied":true}},{"devices":[{"gpu":null,"mig":{"concrete":{"parentMinor":1,"giId":2,"ciId":0,"migUUID":"MIG-cccc","parentUUID":"GPU-dddd","parentPCIBusID":"0000:3b:00.0"},"device":{"Requests":["mig"],"PoolName":"node-a","DeviceName":"gpu-1-mig-1g10gb-2","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-1-mig-1g10gb-2"]}}}],"configState":{"mpsControlDaemonID":"mps-claim-uid-1"}},{"devices":[{"gpu":null,"mig":null,"vfio":{"info":{"uuid":"GPU-eeee","pciBusID":"0000:5e:00.0"},"device":{"Requests":["vfio"],"PoolName":"node-a","DeviceName":"gpu-3-vfio","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-3-vfio"],"Metadata":{"Attributes":{"productName":{"string":"NVIDIA A100"},"resource.kubernetes.io/pciBusID":{"string":"0000:5e:00.0"}},"NetworkData":null}}}}],"configState":{"mpsControlDaemonID":"","timeSliceApplied":false}}]}}},"v2":{"checksum":1104686740,"preparedClaims":{"claim-uid-1":{"checkpointState":"PrepareCompleted","status":{"allocation":{"devices":{"results":[{"request":"gpu","driver":"gpu.nvidia.com","pool":"node-a","device":"gpu-0"}]}}},"preparedDevices":[{"devices":[{"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":"","timeSliceApplied":true}},{"devices":[{"gpu":null,"mig":{"concrete":{"parentMinor":1,"giId":2,"ciId":0,"migUUID":"MIG-cccc","parentUUID":"GPU-dddd","parentPCIBusID":"0000:3b:00.0"},"device":{"Requests":["mig"],"PoolName":"node-a","DeviceName":"gpu-1-mig-1g10gb-2","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-1-mig-1g10gb-2"]}}}],"configState":{"mpsControlDaemonID":"mps-claim-uid-1"}},{"devices":[{"gpu":null,"mig":null,"vfio":{"info":{"uuid":"GPU-eeee","pciBusID":"0000:5e:00.0"},"device":{"Requests":["vfio"],"PoolName":"node-a","DeviceName":"gpu-3-vfio","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-3-vfio"],"Metadata":{"Attributes":{"productName":{"string":"NVIDIA A100"},"resource.kubernetes.io/pciBusID":{"string":"0000:5e:00.0"}},"NetworkData":null}}}}],"configState":{"mpsControlDaemonID":"","timeSliceApplied":false}}],"name":"claim-1","namespace":"default"},"claim-uid-2":{"checkpointState":"PrepareStarted","status":{"allocation":{"devices":{"results":[{"request":"gpu","driver":"gpu.nvidia.com","pool":"node-a","device":"gpu-0"}]}}},"name":"claim-2","namespace":"team-a"}},"nodeBootID":"boot-id-1"}} diff --git a/checkpoint/testdata/v2-from-v1-checkpoint.json b/checkpoint/testdata/v2-from-v1-checkpoint.json new file mode 100644 index 0000000..e6d6595 --- /dev/null +++ b/checkpoint/testdata/v2-from-v1-checkpoint.json @@ -0,0 +1 @@ +{"kind":"Checkpoint","apiVersion":"checkpoint.internal.example.com/v2","driverName":"gpu.example.com","extension":{"name":"gpu.example.com","version":1},"nodeBootID":"boot-id-1","driver":{"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"]},"driver":{"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"]},"driver":{"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"]},"driver":{"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"]},"driver":{"nvidia":{"group":1,"type":"vfio","uuid":"GPU-eeee"}}}],"driver":{"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"]}]},"driver":{"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"]},"driver":{"partition":{"type":"Hard","amd":{"slot":1}},"amd":{"shareKey":"claim-uid-1/part/gpu-1-cpx-nps4-0/"}}}]}]}