diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1d1baa0f..c3c37154 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -91,7 +91,7 @@ jobs: - name: Set up Go uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 with: - go-version: '1.25.1' + go-version: '1.26.0' - name: Build run: make build diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..42e9f7c3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +go.work +go.work.sum diff --git a/cmd/hami-kubelet-plugin/checkpoint.go b/cmd/hami-kubelet-plugin/checkpoint.go deleted file mode 100644 index 78c9ae5d..00000000 --- a/cmd/hami-kubelet-plugin/checkpoint.go +++ /dev/null @@ -1,129 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - - "k8s.io/kubernetes/pkg/kubelet/checkpointmanager/checksum" -) - -type Checkpoint struct { - // Note: The Checksum below is only associated with the V1 checkpoint - // (because it doesn't have an embedded one). All future versions have - // their checksum directly embedded in them to better support - // downgrades. This checksum will be removed once the V1 checkpoint is - // no longer supported. - Checksum checksum.Checksum `json:"checksum"` - V1 *CheckpointV1 `json:"v1,omitempty"` - V2 *CheckpointV2 `json:"v2,omitempty"` -} - -func (cp *Checkpoint) ToLatestVersion() *Checkpoint { - latest := &Checkpoint{} - switch { - case cp.V2 != nil: - latest.V2 = cp.V2 - case cp.V1 != nil: - latest.V2 = cp.V1.ToV2() - default: - latest.V2 = &CheckpointV2{} - } - if latest.V2.PreparedClaims == nil { - latest.V2.PreparedClaims = make(PreparedClaimsByUID) - } - return latest -} - -func (cp *Checkpoint) MarshalCheckpoint() ([]byte, error) { - cp = cp.ToLatestVersion() - cp.V1 = cp.V2.ToV1() - if err := cp.SetChecksumV1(); err != nil { - return nil, fmt.Errorf("error setting v1 checksum: %v", err) - } - if err := cp.SetChecksumV2(); err != nil { - return nil, fmt.Errorf("error setting v2 checksum: %v", err) - } - return json.Marshal(*cp) -} - -func (cp *Checkpoint) SetChecksumV1() error { - v2 := cp.V2 - cp.V2 = nil - defer func() { - cp.V2 = v2 - }() - - cp.Checksum = 0 - out, err := json.Marshal(*cp) - if err != nil { - return err - } - cp.Checksum = checksum.New(out) - return nil -} - -func (cp *Checkpoint) SetChecksumV2() error { - cp.V2.Checksum = 0 - out, err := json.Marshal(*cp.V2) - if err != nil { - return err - } - cp.V2.Checksum = checksum.New(out) - return nil -} - -func (cp *Checkpoint) UnmarshalCheckpoint(data []byte) error { - return json.Unmarshal(data, cp) -} - -func (cp *Checkpoint) VerifyChecksum() error { - if err := cp.VerifyChecksumV1(); err != nil { - return err - } - if err := cp.VerifyChecksumV2(); err != nil { - return err - } - return nil -} - -func (cp *Checkpoint) VerifyChecksumV1() error { - ck := cp.Checksum - v2 := cp.V2 - cp.V2 = nil - defer func() { - cp.Checksum = ck - cp.V2 = v2 - }() - - cp.Checksum = 0 - out, err := json.Marshal(*cp) - if err != nil { - return err - } - - return ck.Verify(out) -} - -func (cp *Checkpoint) VerifyChecksumV2() error { - if cp.V2 == nil { - return nil - } - - ck := cp.V2.Checksum - defer func() { - cp.V2.Checksum = ck - }() - cp.V2.Checksum = 0 - out, err := json.Marshal(*cp.V2) - if err != nil { - return err - } - return ck.Verify(out) -} - -func (cp *Checkpoint) GetNodeBootID() string { - if cp.V2 != nil { - return cp.V2.NodeBootID - } - return "" -} diff --git a/cmd/hami-kubelet-plugin/checkpoint_convert.go b/cmd/hami-kubelet-plugin/checkpoint_convert.go new file mode 100644 index 00000000..94e24a3b --- /dev/null +++ b/cmd/hami-kubelet-plugin/checkpoint_convert.go @@ -0,0 +1,232 @@ +/* + * 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 main + +import ( + "maps" + "path/filepath" + "reflect" + "slices" + + resourceapi "k8s.io/api/resource/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/dynamic-resource-allocation/kubeletplugin" + + checkpointapi "github.com/Project-HAMi/dra-lib/api/checkpoint/v1" + "github.com/Project-HAMi/dra-lib/checkpoint" +) + +// checkpointGroup is the API group of the checkpoint shared by the HAMi DRA drivers. +const checkpointGroup = "checkpoint.internal.project-hami.io" + +type checkpointStore interface { + Read() (*checkpointapi.Checkpoint, error) + Write(*checkpointapi.Checkpoint) error + Update(func(*checkpointapi.Checkpoint) error) error +} + +// newCheckpointStore opens the driver checkpoint in dir. A legacy kubelet +// checkpointmanager file is migrated on first read; that is deprecated and will be removed in a future version. +func newCheckpointStore(dir string) (*checkpoint.Store, error) { + return checkpoint.NewStore(filepath.Join(dir, DriverPluginCheckpointFileBasename), + checkpoint.Options{Group: checkpointGroup, DriverName: DriverName}) +} + +type ClaimCheckpointState string + +const ( + ClaimCheckpointStateUnset ClaimCheckpointState = "" + ClaimCheckpointStatePrepareStarted ClaimCheckpointState = "PrepareStarted" + ClaimCheckpointStatePrepareCompleted ClaimCheckpointState = "PrepareCompleted" +) + +// CheckpointState is the driver state persisted in the checkpoint, in the +// form the driver works with. +type CheckpointState struct { + NodeBootID string + PreparedClaims PreparedClaimsByUID +} + +type PreparedClaimsByUID map[string]PreparedClaim + +type PreparedClaim struct { + CheckpointState ClaimCheckpointState + Status resourceapi.ResourceClaimStatus + PreparedDevices PreparedDevices + Name string + Namespace string +} + +func newCheckpointState() *CheckpointState { + return &CheckpointState{PreparedClaims: make(PreparedClaimsByUID)} +} + +func checkpointStateToAPI(state *CheckpointState) *checkpointapi.Checkpoint { + checkpoint := &checkpointapi.Checkpoint{NodeBootID: state.NodeBootID} + for _, uid := range slices.Sorted(maps.Keys(state.PreparedClaims)) { + pc := state.PreparedClaims[uid] + claim := checkpointapi.PreparedClaim{ + UID: types.UID(uid), + Name: pc.Name, + Namespace: pc.Namespace, + State: checkpointapi.PrepareState(pc.CheckpointState), + } + if status := pc.Status; !reflect.DeepEqual(status, resourceapi.ResourceClaimStatus{}) { + claim.Status = &status + } + if len(pc.PreparedDevices) > 0 { + claim.NVIDIA = &checkpointapi.NVIDIAClaim{} + } + for _, group := range pc.PreparedDevices { + if group == nil { + continue + } + index := int32(len(claim.NVIDIA.Groups)) + claim.NVIDIA.Groups = append(claim.NVIDIA.Groups, checkpointapi.NVIDIADeviceGroup{ + MPSControlDaemonID: group.ConfigState.MpsControlDaemonID, + }) + for i := range group.Devices { + claim.Devices = append(claim.Devices, preparedDeviceToAPI(&group.Devices[i], index)) + } + } + checkpoint.PreparedClaims = append(checkpoint.PreparedClaims, claim) + } + return checkpoint +} + +func preparedDeviceToAPI(pd *PreparedDevice, group int32) checkpointapi.PreparedDevice { + nvidia := &checkpointapi.NVIDIADevice{Group: group} + device := checkpointapi.PreparedDevice{NVIDIA: nvidia} + switch { + case pd.HAMiGpu != nil: + nvidia.Type = checkpointapi.NVIDIADeviceTypeGPU + if pd.HAMiGpu.Info != nil { + nvidia.UUID = pd.HAMiGpu.Info.UUID + } + device.Device = deviceToAPI(pd.HAMiGpu.Device) + device.Partition = &checkpointapi.Partition{Type: checkpointapi.PartitionTypeSoft} + case pd.Gpu != nil: + nvidia.Type = checkpointapi.NVIDIADeviceTypeGPU + if pd.Gpu.Info != nil { + nvidia.UUID = pd.Gpu.Info.UUID + } + device.Device = deviceToAPI(pd.Gpu.Device) + case pd.Mig != nil: + nvidia.Type = checkpointapi.NVIDIADeviceTypeMIG + device.Device = deviceToAPI(pd.Mig.Device) + device.Partition = &checkpointapi.Partition{Type: checkpointapi.PartitionTypeHard} + if c := pd.Mig.Concrete; c != nil { + device.Partition.ParentDevice = c.ParentUUID + device.Partition.NVIDIA = &checkpointapi.NVIDIAPartition{ + ParentMinor: int32(c.ParentMinor), + GIID: int32(c.GIID), + CIID: int32(c.CIID), + MIGUUID: c.MigUUID, + } + } + case pd.Vfio != nil: + nvidia.Type = checkpointapi.NVIDIADeviceTypeVFIO + if pd.Vfio.Info != nil { + nvidia.UUID = pd.Vfio.Info.UUID + } + device.Device = deviceToAPI(pd.Vfio.Device) + } + return device +} + +func deviceToAPI(d *kubeletplugin.Device) checkpointapi.Device { + if d == nil { + return checkpointapi.Device{} + } + return checkpointapi.Device{ + Requests: d.Requests, + PoolName: d.PoolName, + DeviceName: d.DeviceName, + CDIDeviceIDs: d.CDIDeviceIDs, + } +} + +func checkpointStateFromAPI(checkpoint *checkpointapi.Checkpoint) *CheckpointState { + state := newCheckpointState() + state.NodeBootID = checkpoint.NodeBootID + for _, claim := range checkpoint.PreparedClaims { + pc := PreparedClaim{ + CheckpointState: ClaimCheckpointState(claim.State), + Name: claim.Name, + Namespace: claim.Namespace, + } + if claim.Status != nil { + pc.Status = *claim.Status + } + if claim.NVIDIA != nil { + for _, group := range claim.NVIDIA.Groups { + pc.PreparedDevices = append(pc.PreparedDevices, &PreparedDeviceGroup{ + ConfigState: DeviceConfigState{MpsControlDaemonID: group.MPSControlDaemonID}, + }) + } + } + for i := range claim.Devices { + device := &claim.Devices[i] + var group int + if device.NVIDIA != nil { + group = int(device.NVIDIA.Group) + } + for group >= len(pc.PreparedDevices) { + pc.PreparedDevices = append(pc.PreparedDevices, &PreparedDeviceGroup{}) + } + pc.PreparedDevices[group].Devices = append(pc.PreparedDevices[group].Devices, preparedDeviceFromAPI(device)) + } + state.PreparedClaims[string(claim.UID)] = pc + } + return state +} + +func preparedDeviceFromAPI(device *checkpointapi.PreparedDevice) PreparedDevice { + if device.NVIDIA == nil { + return PreparedDevice{} + } + d := &kubeletplugin.Device{ + Requests: device.Device.Requests, + PoolName: device.Device.PoolName, + DeviceName: device.Device.DeviceName, + CDIDeviceIDs: device.Device.CDIDeviceIDs, + } + uuid := device.NVIDIA.UUID + switch device.NVIDIA.Type { + case checkpointapi.NVIDIADeviceTypeGPU: + // A HAMi-core GPU is a whole GPU shared through software limits. + if p := device.Partition; p != nil && p.Type == checkpointapi.PartitionTypeSoft { + return PreparedDevice{HAMiGpu: &PreparedHAMiGpu{Info: &HAMiGpuInfo{GpuInfo{UUID: uuid}}, Device: d}} + } + return PreparedDevice{Gpu: &PreparedGpu{Info: &GpuInfo{UUID: uuid}, Device: d}} + case checkpointapi.NVIDIADeviceTypeMIG: + mig := &PreparedMigDevice{Device: d} + if p := device.Partition; p != nil && p.NVIDIA != nil { + mig.Concrete = &MigLiveTuple{ + ParentMinor: GPUMinor(p.NVIDIA.ParentMinor), + GIID: int(p.NVIDIA.GIID), + CIID: int(p.NVIDIA.CIID), + MigUUID: p.NVIDIA.MIGUUID, + ParentUUID: p.ParentDevice, + } + } + return PreparedDevice{Mig: mig} + case checkpointapi.NVIDIADeviceTypeVFIO: + return PreparedDevice{Vfio: &PreparedVfioDevice{Info: &VfioDeviceInfo{UUID: uuid}, Device: d}} + } + return PreparedDevice{} +} diff --git a/cmd/hami-kubelet-plugin/checkpoint_test.go b/cmd/hami-kubelet-plugin/checkpoint_test.go new file mode 100644 index 00000000..fc64a76c --- /dev/null +++ b/cmd/hami-kubelet-plugin/checkpoint_test.go @@ -0,0 +1,199 @@ +/* + * 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 main + +import ( + "context" + "os" + "path/filepath" + "testing" + + checkpointapi "github.com/Project-HAMi/dra-lib/api/checkpoint/v1" + "github.com/Project-HAMi/k8s-dra-driver/pkg/featuregates" + "github.com/Project-HAMi/k8s-dra-driver/pkg/version" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + resourceapi "k8s.io/api/resource/v1" + "k8s.io/apimachinery/pkg/types" + featuregatetesting "k8s.io/component-base/featuregate/testing" + "k8s.io/dynamic-resource-allocation/kubeletplugin" +) + +// fixtureCheckpointState is the content of testdata/legacy-checkpoint.json, +// which was written by the kubelet checkpointmanager-based code. +func fixtureCheckpointState() *CheckpointState { + dev := func(req, name string) *kubeletplugin.Device { + return &kubeletplugin.Device{Requests: []string{req}, PoolName: "node-a", DeviceName: name, CDIDeviceIDs: []string{"k8s.gpu.nvidia.com/device=" + name}} + } + return &CheckpointState{ + NodeBootID: "boot-id-1", + PreparedClaims: PreparedClaimsByUID{ + "claim-uid-1": { + CheckpointState: ClaimCheckpointStatePrepareCompleted, + Name: "claim-1", + Namespace: "default", + Status: resourceapi.ResourceClaimStatus{Allocation: &resourceapi.AllocationResult{Devices: resourceapi.DeviceAllocationResult{ + Results: []resourceapi.DeviceRequestAllocationResult{{Request: "gpu", Driver: DriverName, Pool: "node-a", Device: "gpu-0"}}, + }}}, + PreparedDevices: PreparedDevices{ + {Devices: PreparedDeviceList{ + {HAMiGpu: &PreparedHAMiGpu{Info: &HAMiGpuInfo{GpuInfo{UUID: "GPU-bbbb"}}, Device: dev("hami", "hami-gpu-1")}}, + {Gpu: &PreparedGpu{Info: &GpuInfo{UUID: "GPU-aaaa"}, Device: dev("gpu", "gpu-0")}}, + }}, + {Devices: PreparedDeviceList{ + {Mig: &PreparedMigDevice{Concrete: &MigLiveTuple{ParentMinor: 1, GIID: 2, CIID: 0, MigUUID: "MIG-cccc", ParentUUID: "GPU-dddd"}, Device: dev("mig", "gpu-1-mig-1g10gb-2")}}, + {Vfio: &PreparedVfioDevice{Info: &VfioDeviceInfo{UUID: "GPU-eeee"}, Device: dev("vfio", "gpu-3-vfio")}}, + }, ConfigState: DeviceConfigState{MpsControlDaemonID: "mps-claim-uid-1"}}, + }, + }, + "claim-uid-2": { + CheckpointState: ClaimCheckpointStatePrepareStarted, + Name: "claim-2", + Namespace: "team-a", + }, + }, + } +} + +// fixtureCheckpointStateV1 is the content of testdata/legacy-checkpoint-v1.json: +// the oldest format, which only holds completed claims without names. +func fixtureCheckpointStateV1() *CheckpointState { + state := fixtureCheckpointState() + claim := state.PreparedClaims["claim-uid-1"] + claim.Name, claim.Namespace = "", "" + return &CheckpointState{PreparedClaims: PreparedClaimsByUID{"claim-uid-1": claim}} +} + +func TestCheckpointRoundtrip(t *testing.T) { + s := newTestDeviceState(t) + ctx := context.Background() + + got, err := s.getCheckpoint(ctx) + require.NoError(t, err) + assert.Equal(t, newCheckpointState(), got) + + require.NoError(t, s.createCheckpoint(ctx, fixtureCheckpointState())) + got, err = s.getCheckpoint(ctx) + require.NoError(t, err) + assert.Equal(t, fixtureCheckpointState(), got) +} + +// TestLegacyCheckpointMigrates checks that checkpoints written by the kubelet +// checkpointmanager-based driver are migrated (deprecated, will be removed in a future version). +func TestLegacyCheckpointMigrates(t *testing.T) { + for fixture, want := range map[string]*CheckpointState{ + "testdata/legacy-checkpoint.json": fixtureCheckpointState(), + "testdata/legacy-checkpoint-v1.json": fixtureCheckpointStateV1(), + } { + t.Run(filepath.Base(fixture), func(t *testing.T) { + legacy, err := os.ReadFile(fixture) + require.NoError(t, err) + s := newTestDeviceState(t) + ctx := context.Background() + require.NoError(t, os.WriteFile(s.checkpointPath, legacy, 0o600)) + + got, err := s.getCheckpoint(ctx) + require.NoError(t, err) + assert.Equal(t, want, got) + migrated, err := os.ReadFile(s.checkpointPath) + require.NoError(t, err) + assert.Contains(t, string(migrated), `"apiVersion":"checkpoint.internal.project-hami.io/v1"`) + assert.Contains(t, string(migrated), `"driverName":"hami-core-gpu.project-hami.io"`) + + got, err = s.getCheckpoint(ctx) + require.NoError(t, err) + assert.Equal(t, want, got) + again, err := os.ReadFile(s.checkpointPath) + require.NoError(t, err) + assert.Equal(t, migrated, again) + }) + } +} + +type countingCheckpointStore struct { + checkpointStore + writes int +} + +func (c *countingCheckpointStore) Write(cp *checkpointapi.Checkpoint) error { + c.writes++ + return c.checkpointStore.Write(cp) +} + +func (c *countingCheckpointStore) Update(mutate func(*checkpointapi.Checkpoint) error) error { + cp, err := c.Read() + if err != nil { + return err + } + if err := mutate(cp); err != nil { + return err + } + return c.Write(cp) +} + +// A kubelet call writes the checkpoint twice (claims started, claims +// completed) no matter how many claims it carries, and unprepare writes once. +func TestKubeletCallWritesCheckpointPerPhase(t *testing.T) { + ctx := context.Background() + claims := []*resourceapi.ResourceClaim{ + testHAMiClaim(t, "uid-a", 30, "4Gi"), + testHAMiClaim(t, "uid-b", 50, "2Gi"), + testHAMiClaim(t, "uid-c", 10, "1Gi"), + } + s := newTestPrepareDeviceState(t, claims...) + counter := &countingCheckpointStore{checkpointStore: s.checkpoints} + s.checkpoints = counter + + var refs []kubeletplugin.NamespacedObject + for uid, r := range s.PrepareClaims(ctx, claims) { + require.NoError(t, r.Err, uid) + } + assert.Equal(t, 2, counter.writes) + cp, err := s.getCheckpoint(ctx) + require.NoError(t, err) + for _, claim := range claims { + assert.Equal(t, ClaimCheckpointStatePrepareCompleted, cp.PreparedClaims[string(claim.UID)].CheckpointState) + refs = append(refs, kubeletplugin.NamespacedObject{ + UID: claim.UID, NamespacedName: types.NamespacedName{Namespace: claim.Namespace, Name: claim.Name}, + }) + } + + for uid, err := range s.UnprepareClaims(ctx, refs) { + require.NoError(t, err, uid) + } + assert.Equal(t, 3, counter.writes) + cp, err = s.getCheckpoint(ctx) + require.NoError(t, err) + assert.Empty(t, cp.PreparedClaims) +} + +// Two claims of one kubelet call must not both get the same non-admin device. +func TestPrepareClaimsRejectsOverlapWithinCall(t *testing.T) { + if version.NVVesion() == "" { + t.Skip("requires the version injected by -ldflags; run `make test`") + } + // HAMi-core GPUs are shared on purpose; the check applies to exclusive devices. + featuregatetesting.SetFeatureGateDuringTest(t, featuregates.FeatureGates(), featuregates.HAMiCoreSupport, false) + ctx := context.Background() + s := newTestDeviceState(t) + claimA := testHAMiClaim(t, "uid-a", 30, "4Gi") + claimB := testHAMiClaim(t, "uid-b", 30, "4Gi") + + results := s.PrepareClaims(ctx, []*resourceapi.ResourceClaim{claimA, claimB}) + require.ErrorContains(t, results["uid-b"].Err, "already allocated to different claim uid-a") + assert.NotContains(t, results["uid-a"].Err.Error(), "already allocated") +} diff --git a/cmd/hami-kubelet-plugin/checkpointv.go b/cmd/hami-kubelet-plugin/checkpointv.go deleted file mode 100644 index 0d01bdee..00000000 --- a/cmd/hami-kubelet-plugin/checkpointv.go +++ /dev/null @@ -1,86 +0,0 @@ -package main - -import ( - resourceapi "k8s.io/api/resource/v1" - - "k8s.io/kubernetes/pkg/kubelet/checkpointmanager/checksum" -) - -type ClaimCheckpointState string - -const ( - ClaimCheckpointStateUnset ClaimCheckpointState = "" - ClaimCheckpointStatePrepareStarted ClaimCheckpointState = "PrepareStarted" - ClaimCheckpointStatePrepareCompleted ClaimCheckpointState = "PrepareCompleted" -) - -// Latest version type aliases - -type PreparedClaimsByUID = PreparedClaimsByUIDV2 -type PreparedClaim = PreparedClaimV2 - -// V2 types - -type CheckpointV2 struct { - Checksum checksum.Checksum `json:"checksum"` - PreparedClaims PreparedClaimsByUIDV2 `json:"preparedClaims,omitempty"` - // NodeBootID is the Linux kernel boot_id - // for the node when this checkpoint was last validated at plugin startup. - // If it differs from the current boot id, prepared claims are invalid (reboot). - NodeBootID string `json:"nodeBootID,omitempty"` -} - -type PreparedClaimsByUIDV2 map[string]PreparedClaimV2 - -type PreparedClaimV2 struct { - CheckpointState ClaimCheckpointState `json:"checkpointState"` - Status resourceapi.ResourceClaimStatus `json:"status,omitempty"` - PreparedDevices PreparedDevices `json:"preparedDevices,omitempty"` - Name string `json:"name,omitempty"` - Namespace string `json:"namespace,omitempty"` -} - -// V1 types - -type CheckpointV1 struct { - PreparedClaims PreparedClaimsByUIDV1 `json:"preparedClaims,omitempty"` -} - -type PreparedClaimsByUIDV1 map[string]PreparedClaimV1 - -type PreparedClaimV1 struct { - Status resourceapi.ResourceClaimStatus `json:"status,omitempty"` - PreparedDevices PreparedDevices `json:"preparedDevices,omitempty"` -} - -// Conversion functions - -func (v1 *CheckpointV1) ToV2() *CheckpointV2 { - v2 := &CheckpointV2{ - PreparedClaims: make(PreparedClaimsByUIDV2), - } - for claimUID, v1Claim := range v1.PreparedClaims { - v2.PreparedClaims[claimUID] = PreparedClaimV2{ - CheckpointState: ClaimCheckpointStatePrepareCompleted, - Status: v1Claim.Status, - PreparedDevices: v1Claim.PreparedDevices, - } - } - return v2 -} - -func (v2 *CheckpointV2) ToV1() *CheckpointV1 { - v1 := &CheckpointV1{ - PreparedClaims: make(PreparedClaimsByUIDV1), - } - for claimUID, v1Claim := range v2.PreparedClaims { - if v1Claim.CheckpointState != ClaimCheckpointStatePrepareCompleted { - continue - } - v1.PreparedClaims[claimUID] = PreparedClaimV1{ - Status: v1Claim.Status, - PreparedDevices: v1Claim.PreparedDevices, - } - } - return v1 -} diff --git a/cmd/hami-kubelet-plugin/cleanup.go b/cmd/hami-kubelet-plugin/cleanup.go index 6b5a72dd..b863fc59 100644 --- a/cmd/hami-kubelet-plugin/cleanup.go +++ b/cmd/hami-kubelet-plugin/cleanup.go @@ -116,14 +116,14 @@ func (m *CheckpointCleanupManager) cleanup(ctx context.Context) { } // Get checkpointed claims in PrepareStarted state. - filtered := make(PreparedClaimsByUIDV2) - for uid, claim := range cp.V2.PreparedClaims { + filtered := make(PreparedClaimsByUID) + for uid, claim := range cp.PreparedClaims { if claim.CheckpointState == ClaimCheckpointStatePrepareStarted { filtered[uid] = claim } } - klog.V(4).Infof("Checkpointed RC cleanup: claims in PrepareStarted state: %d (of %d)", len(filtered), len(cp.V2.PreparedClaims)) + klog.V(4).Infof("Checkpointed RC cleanup: claims in PrepareStarted state: %d (of %d)", len(filtered), len(cp.PreparedClaims)) for cpuid, cpclaim := range filtered { m.unprepareIfStale(ctx, cpuid, cpclaim) diff --git a/cmd/hami-kubelet-plugin/device_state.go b/cmd/hami-kubelet-plugin/device_state.go index 48d1b873..bd23c145 100644 --- a/cmd/hami-kubelet-plugin/device_state.go +++ b/cmd/hami-kubelet-plugin/device_state.go @@ -18,8 +18,11 @@ package main import ( "context" + "errors" "fmt" "io" + "io/fs" + "os" "path/filepath" "slices" "sync" @@ -29,9 +32,9 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/dynamic-resource-allocation/kubeletplugin" "k8s.io/klog/v2" - "k8s.io/kubernetes/pkg/kubelet/checkpointmanager" cdiapi "tags.cncf.io/container-device-interface/pkg/cdi" + checkpointapi "github.com/Project-HAMi/dra-lib/api/checkpoint/v1" "github.com/sirupsen/logrus" configapi "github.com/NVIDIA/k8s-dra-driver-gpu/api/nvidia.com/resource/v1beta1" @@ -67,8 +70,9 @@ type DeviceState struct { // when announcing one ResourceSlice per physical GPU). perGPUAllocatable PerGPUMinorAllocatableDevices - nvdevlib *deviceLib - checkpointManager checkpointmanager.CheckpointManager + nvdevlib *deviceLib + checkpointPath string + checkpoints checkpointStore // Checkpoint read/write lock, file-based for multi-process synchronization. cplock *flock.Flock @@ -151,11 +155,10 @@ func NewDeviceState(ctx context.Context, config *Config) (*DeviceState, error) { } } - checkpointManager, err := checkpointmanager.NewCheckpointManager(config.DriverPluginPath()) + checkpoints, err := newCheckpointStore(config.DriverPluginPath()) if err != nil { - return nil, fmt.Errorf("unable to create checkpoint manager: %v", err) + return nil, err } - cpLockPath := filepath.Join(config.DriverPluginPath(), "cp.lock") state := &DeviceState{ @@ -168,7 +171,8 @@ func NewDeviceState(ctx context.Context, config *Config) (*DeviceState, error) { perGPUAllocatable: perGPUAllocatable, config: config, nvdevlib: nvdevlib, - checkpointManager: checkpointManager, + checkpointPath: filepath.Join(config.DriverPluginPath(), DriverPluginCheckpointFileBasename), + checkpoints: checkpoints, cplock: flock.NewFlock(cpLockPath), } state.checkpointCleanupManager = NewCheckpointCleanupManager(state, config.clientsets.Resource) @@ -189,23 +193,23 @@ func NewDeviceState(ctx context.Context, config *Config) (*DeviceState, error) { // the current boot. CDI specs and device configuration do not survive a node // reboot, so claims prepared before a reboot must be prepared again. func (s *DeviceState) initCheckpoint(ctx context.Context, currentBootID string) error { - checkpoints, err := s.checkpointManager.ListCheckpoints() - if err != nil { - return fmt.Errorf("unable to list checkpoints: %w", err) + _, err := os.Stat(s.checkpointPath) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + return fmt.Errorf("unable to stat checkpoint: %w", err) } - if slices.Contains(checkpoints, DriverPluginCheckpointFileBasename) { + if err == nil { cp, err := s.getCheckpoint(ctx) if err != nil { return fmt.Errorf("unable to get checkpoint: %w", err) } - switch storedBootID := cp.GetNodeBootID(); storedBootID { + switch storedBootID := cp.NodeBootID; storedBootID { case currentBootID: return nil case "": klog.V(4).Info("The existing checkpoint file does not contain a boot ID, injecting current boot ID") - if err := s.updateCheckpoint(ctx, func(cp *Checkpoint) { - cp.V2.NodeBootID = currentBootID + if err := s.updateCheckpoint(ctx, func(cp *CheckpointState) { + cp.NodeBootID = currentBootID }); err != nil { return fmt.Errorf("unable to update checkpoint: %w", err) } @@ -215,78 +219,175 @@ func (s *DeviceState) initCheckpoint(ctx context.Context, currentBootID string) } } - if err := s.createCheckpoint(ctx, &Checkpoint{V2: &CheckpointV2{NodeBootID: currentBootID}}); err != nil { + if err := s.createCheckpoint(ctx, &CheckpointState{NodeBootID: currentBootID}); err != nil { return fmt.Errorf("unable to create fresh checkpoint: %w", err) } return nil } +// PrepareResult is the outcome of preparing one claim. +type PrepareResult struct { + Devices []kubeletplugin.Device + Err error +} + func (s *DeviceState) Prepare(ctx context.Context, claim *resourceapi.ResourceClaim) ([]kubeletplugin.Device, error) { + r := s.PrepareClaims(ctx, []*resourceapi.ResourceClaim{claim})[string(claim.UID)] + return r.Devices, r.Err +} + +// PrepareClaims prepares the claims of one kubelet call. The checkpoint is +// written once to mark all claims to prepare as PrepareStarted and once to mark +// the prepared ones PrepareCompleted, independent of the number of claims. +func (s *DeviceState) PrepareClaims(ctx context.Context, claims []*resourceapi.ResourceClaim) map[string]PrepareResult { tplock0 := time.Now() s.Lock() defer s.Unlock() klog.V(6).Infof("t_prep_state_lock_acq %.3f s", time.Since(tplock0).Seconds()) - claimUID := string(claim.UID) + results := make(map[string]PrepareResult, len(claims)) + fail := func(claims []*resourceapi.ResourceClaim, err error) { + for _, claim := range claims { + results[string(claim.UID)] = PrepareResult{Err: err} + } + } tgcp0 := time.Now() cp, err := s.getCheckpoint(ctx) if err != nil { - return nil, fmt.Errorf("unable to get checkpoint: %v", err) + fail(claims, fmt.Errorf("unable to get checkpoint: %v", err)) + return results } klog.V(7).Infof("t_prep_get_checkpoint %.3f s", time.Since(tgcp0).Seconds()) - // Check for existing 'completed' claim preparation before updating the - // checkpoint with 'PrepareStarted'. Otherwise, we effectively mark a - // perfectly prepared claim as only partially prepared, which may have - // negative side effects during Unprepare(). - preparedClaim, exists := cp.V2.PreparedClaims[claimUID] - if exists && preparedClaim.CheckpointState == ClaimCheckpointStatePrepareCompleted { - // Make this a noop. Associated device(s) has/ave been prepared by us. - // Prepare() must be idempotent, as it may be invoked more than once per - // claim (and actual device preparation must happen at most once). - klog.V(4).Infof("Skip prepare: claim already in PrepareCompleted state: %s", ResourceClaimToString(claim)) - return preparedClaim.PreparedDevices.GetDevices(), nil - } - - if !featuregates.Enabled(featuregates.HAMiCoreSupport) { - // In certain scenarios, the same device can be prepared/allocated more than once for different claims - // due to races between data processing in different goroutines in the scheduler, or when pods are - // force-deleted while the kubelet still considers the devices allocated. - // To prevent this, we check whether any device requested in the incoming claim has already been prepared - // and fail the request if so (unless the prior preparation was performed with admin access). - // More details: https://github.com/kubernetes/kubernetes/pull/136269 - if err := s.validateNoOverlappingPreparedDevices(cp, claim); err != nil { - return nil, fmt.Errorf("unable to prepare claim %v: %w", claimUID, err) - } - - // Relevant for DynamicMIG: a previous preparation attempt for the same - // claim might have resulted in complete or partial GI/CI creation. Roll - // that back, and retry creation from scratch (that maybe can later be - // optimized into filling the gaps). - if exists && preparedClaim.CheckpointState == ClaimCheckpointStatePrepareStarted { - klog.V(4).Infof("Claim %s already in PrepareStarted state: attempt rollback before new prepare", ResourceClaimToString(claim)) - if err := s.unpreparePartiallyPrepairedClaim(claimUID, preparedClaim, cp); err != nil { - return nil, fmt.Errorf("unprepare failed for partially prepared claim %s failed: %w", PreparedClaimToString(&preparedClaim, claimUID), err) + var toPrepare []*resourceapi.ResourceClaim + // Non-admin devices requested by claims accepted earlier in this call, + // which are not PrepareCompleted in the checkpoint yet. + pending := make(map[string]string) + for _, claim := range claims { + claimUID := string(claim.UID) + // Check for existing 'completed' claim preparation before updating the + // checkpoint with 'PrepareStarted'. Otherwise, we effectively mark a + // perfectly prepared claim as only partially prepared, which may have + // negative side effects during Unprepare(). + preparedClaim, exists := cp.PreparedClaims[claimUID] + if exists && preparedClaim.CheckpointState == ClaimCheckpointStatePrepareCompleted { + // Make this a noop. Associated device(s) has/ave been prepared by us. + // Prepare() must be idempotent, as it may be invoked more than once per + // claim (and actual device preparation must happen at most once). + klog.V(4).Infof("Skip prepare: claim already in PrepareCompleted state: %s", ResourceClaimToString(claim)) + results[claimUID] = PrepareResult{Devices: preparedClaim.PreparedDevices.GetDevices()} + continue + } + + if !featuregates.Enabled(featuregates.HAMiCoreSupport) { + // In certain scenarios, the same device can be prepared/allocated more than once for different claims + // due to races between data processing in different goroutines in the scheduler, or when pods are + // force-deleted while the kubelet still considers the devices allocated. + // To prevent this, we check whether any device requested in the incoming claim has already been prepared + // and fail the request if so (unless the prior preparation was performed with admin access). + // More details: https://github.com/kubernetes/kubernetes/pull/136269 + if err := s.validateNoOverlappingPreparedDevices(cp, claim); err != nil { + results[claimUID] = PrepareResult{Err: fmt.Errorf("unable to prepare claim %v: %w", claimUID, err)} + continue + } + requested := s.requestedNonAdminDevices(claim) + if err := overlapWithinCall(requested, pending); err != nil { + results[claimUID] = PrepareResult{Err: fmt.Errorf("unable to prepare claim %v: %w", claimUID, err)} + continue + } + + // Relevant for DynamicMIG: a previous preparation attempt for the same + // claim might have resulted in complete or partial GI/CI creation. Roll + // that back, and retry creation from scratch (that maybe can later be + // optimized into filling the gaps). + if exists && preparedClaim.CheckpointState == ClaimCheckpointStatePrepareStarted { + klog.V(4).Infof("Claim %s already in PrepareStarted state: attempt rollback before new prepare", ResourceClaimToString(claim)) + if err := s.unpreparePartiallyPrepairedClaim(claimUID, preparedClaim, cp); err != nil { + results[claimUID] = PrepareResult{Err: fmt.Errorf("unprepare failed for partially prepared claim %s failed: %w", PreparedClaimToString(&preparedClaim, claimUID), err)} + continue + } + } + for device := range requested { + pending[device] = claimUID } } + toPrepare = append(toPrepare, claim) + } + if len(toPrepare) == 0 { + return results } tucp0 := time.Now() - err = s.updateCheckpoint(ctx, func(cp *Checkpoint) { - cp.V2.PreparedClaims[claimUID] = PreparedClaim{ - CheckpointState: ClaimCheckpointStatePrepareStarted, - Status: claim.Status, - Name: claim.Name, - Namespace: claim.Namespace, + err = s.updateCheckpoint(ctx, func(cp *CheckpointState) { + for _, claim := range toPrepare { + cp.PreparedClaims[string(claim.UID)] = PreparedClaim{ + CheckpointState: ClaimCheckpointStatePrepareStarted, + Status: claim.Status, + Name: claim.Name, + Namespace: claim.Namespace, + } } }) if err != nil { - return nil, fmt.Errorf("unable to update checkpoint: %w", err) + fail(toPrepare, fmt.Errorf("unable to update checkpoint: %w", err)) + return results } klog.V(6).Infof("t_prep_update_checkpoint %.3f s", time.Since(tucp0).Seconds()) - klog.V(6).Infof("checkpoint updated for claim %v", claimUID) + klog.V(6).Infof("checkpoint updated for %d claim(s)", len(toPrepare)) + + prepared := make(map[string]PreparedDevices, len(toPrepare)) + var completed []*resourceapi.ResourceClaim + for _, claim := range toPrepare { + preparedDevices, err := s.prepareClaimDevices(ctx, claim) + if err != nil { + results[string(claim.UID)] = PrepareResult{Err: err} + continue + } + prepared[string(claim.UID)] = preparedDevices + completed = append(completed, claim) + } + if len(completed) == 0 { + return results + } + + tucp20 := time.Now() + err = s.updateCheckpoint(ctx, func(cp *CheckpointState) { + for _, claim := range completed { + cp.PreparedClaims[string(claim.UID)] = PreparedClaim{ + CheckpointState: ClaimCheckpointStatePrepareCompleted, + Status: claim.Status, + PreparedDevices: prepared[string(claim.UID)], + } + } + }) + if err != nil { + fail(completed, fmt.Errorf("unable to update checkpoint: %w", err)) + return results + } + klog.V(6).Infof("checkpoint updated for %d claim(s)", len(completed)) + klog.V(7).Infof("t_prep_ucp2 %.3f s", time.Since(tucp20).Seconds()) + + for _, claim := range completed { + results[string(claim.UID)] = PrepareResult{Devices: prepared[string(claim.UID)].GetDevices()} + } + return results +} + +// overlapWithinCall reports a requested device that an earlier claim of the +// same kubelet call already requested. +func overlapWithinCall(requested map[string]struct{}, pending map[string]string) error { + for device := range requested { + if other, found := pending[device]; found { + return fmt.Errorf("requested device %s is already allocated to different claim %s", device, other) + } + } + return nil +} +// prepareClaimDevices prepares the devices of a claim in PrepareStarted state +// and writes its CDI spec. +func (s *DeviceState) prepareClaimDevices(ctx context.Context, claim *resourceapi.ResourceClaim) (PreparedDevices, error) { tprep0 := time.Now() preparedDevices, err := s.prepareDevices(ctx, claim) klog.V(6).Infof("t_prep_core %.3f s (claim %s)", time.Since(tprep0).Seconds(), ResourceClaimToString(claim)) @@ -307,26 +408,11 @@ func (s *DeviceState) Prepare(ctx context.Context, claim *resourceapi.ResourceCl } tccsf0 := time.Now() - if err := s.cdi.CreateClaimSpecFile(claimUID, preparedDevices); err != nil { + if err := s.cdi.CreateClaimSpecFile(string(claim.UID), preparedDevices); err != nil { return nil, fmt.Errorf("unable to create CDI spec file for claim: %w", err) } klog.V(7).Infof("t_prep_ccsf %.3f s", time.Since(tccsf0).Seconds()) - - tucp20 := time.Now() - err = s.updateCheckpoint(ctx, func(cp *Checkpoint) { - cp.V2.PreparedClaims[claimUID] = PreparedClaim{ - CheckpointState: ClaimCheckpointStatePrepareCompleted, - Status: claim.Status, - PreparedDevices: preparedDevices, - } - }) - if err != nil { - return nil, fmt.Errorf("unable to update checkpoint: %w", err) - } - klog.V(6).Infof("checkpoint updated for claim %v", claimUID) - klog.V(7).Infof("t_prep_ucp2 %.3f s", time.Since(tucp20).Seconds()) - - return preparedDevices.GetDevices(), nil + return preparedDevices, nil } // DestroyUnknownMIGDevices() relies on the checkpoint as the source of truth. @@ -392,8 +478,8 @@ func (s *DeviceState) DestroyUnknownMIGDevices(ctx context.Context) { // down MIG devices that correspond to claims in a PrepareStarted limbo // state -- that can only be correct when there are no overlapping // NodePrepareResources() executions. - filtered := make(PreparedClaimsByUIDV2) - for uid, claim := range cp.V2.PreparedClaims { + filtered := make(PreparedClaimsByUID) + for uid, claim := range cp.PreparedClaims { if claim.CheckpointState == ClaimCheckpointStatePrepareCompleted { filtered[uid] = claim } @@ -418,37 +504,80 @@ func (s *DeviceState) DestroyUnknownMIGDevices(ctx context.Context) { } func (s *DeviceState) Unprepare(ctx context.Context, claimRef kubeletplugin.NamespacedObject) error { + return s.UnprepareClaims(ctx, []kubeletplugin.NamespacedObject{claimRef})[string(claimRef.UID)] +} + +// UnprepareClaims unprepares the claims of one kubelet call and removes them +// from the checkpoint with a single write. +func (s *DeviceState) UnprepareClaims(ctx context.Context, claimRefs []kubeletplugin.NamespacedObject) map[string]error { s.Lock() defer s.Unlock() - klog.V(6).Infof("Unprepare() for claim '%s'", claimRef.String()) + results := make(map[string]error, len(claimRefs)) checkpoint, err := s.getCheckpoint(ctx) if err != nil { - return fmt.Errorf("unable to get checkpoint: %v", err) + for _, claimRef := range claimRefs { + results[string(claimRef.UID)] = fmt.Errorf("unable to get checkpoint: %v", err) + } + return results } + var removed []kubeletplugin.NamespacedObject + for _, claimRef := range claimRefs { + klog.V(6).Infof("Unprepare() for claim '%s'", claimRef.String()) + unprepared, err := s.unprepareClaim(ctx, checkpoint, claimRef) + results[string(claimRef.UID)] = err + if unprepared { + removed = append(removed, claimRef) + } + } + if len(removed) == 0 { + return results + } + + // Mutate checkpoint reflecting that all devices for these claims have been + // unprepared, by virtue of removing their entries (based on claim UID) from + // the PreparedClaims map. + err = s.updateCheckpoint(ctx, func(cp *CheckpointState) { + for _, claimRef := range removed { + delete(cp.PreparedClaims, string(claimRef.UID)) + } + }) + for _, claimRef := range removed { + if err != nil { + results[string(claimRef.UID)] = fmt.Errorf("error deleting claim from checkpoint: unable to update checkpoint: %w", err) + continue + } + klog.V(6).Infof("Deleted claim from checkpoint: %s", claimRef.String()) + } + return results +} + +// unprepareClaim tears down the devices of one claim. It reports whether the +// claim must be removed from the checkpoint. +func (s *DeviceState) unprepareClaim(ctx context.Context, checkpoint *CheckpointState, claimRef kubeletplugin.NamespacedObject) (bool, error) { claimUID := string(claimRef.UID) - pc, exists := checkpoint.V2.PreparedClaims[claimUID] + pc, exists := checkpoint.PreparedClaims[claimUID] if !exists { // Not an error: if this claim UID is not in the checkpoint then this // device was never prepared or has already been unprepared (assume that // Prepare+Checkpoint are done transactionally). Note that // claimRef.String() contains namespace, name, UID. klog.V(2).Infof("Unprepare noop: claim not found in checkpoint data: %v", claimRef.String()) - return nil + return false, nil } switch pc.CheckpointState { case ClaimCheckpointStatePrepareStarted: if err := s.unpreparePartiallyPrepairedClaim(claimUID, pc, checkpoint); err != nil { - return fmt.Errorf("unprepare failed for partially prepared claim %s failed: %w", claimRef.String(), err) + return false, fmt.Errorf("unprepare failed for partially prepared claim %s failed: %w", claimRef.String(), err) } case ClaimCheckpointStatePrepareCompleted: if err := s.unprepareDevices(ctx, claimUID, pc.PreparedDevices); err != nil { - return fmt.Errorf("unprepare devices failed for claim %s: %w", claimRef.String(), err) + return false, fmt.Errorf("unprepare devices failed for claim %s: %w", claimRef.String(), err) } default: - return fmt.Errorf("unsupported ClaimCheckpointState: %v", pc.CheckpointState) + return false, fmt.Errorf("unsupported ClaimCheckpointState: %v", pc.CheckpointState) } if featuregates.Enabled(featuregates.PassthroughSupport) { @@ -460,7 +589,7 @@ func (s *DeviceState) Unprepare(ctx context.Context, claimRef kubeletplugin.Name } err := s.discoverSiblingAllocatables(allocatableDevice) if err != nil { - return fmt.Errorf("error discovering sibling allocatables: %w", err) + return false, fmt.Errorf("error discovering sibling allocatables: %w", err) } } } @@ -474,15 +603,7 @@ func (s *DeviceState) Unprepare(ctx context.Context, claimRef kubeletplugin.Name // attempting to remove the claim from the checkpoint. klog.Errorf("unable to delete CDI spec file for claim %s: %s", claimRef.String(), err) } - - // Mutate checkpoint reflecting that all devices for this claim have been - // unprepared, by virtue of removing its entry (based on claim UID) from the - // PreparedClaims map. - err = s.deleteClaimFromCheckpoint(ctx, claimRef) - if err != nil { - return fmt.Errorf("error deleting claim from checkpoint: %w", err) - } - return nil + return true, nil } // Revert HAMi-Core cache setup or potentially partial MIG device creation (not @@ -525,7 +646,7 @@ func (s *DeviceState) Unprepare(ctx context.Context, claimRef kubeletplugin.Name // server) or for a claim that is not stale but that _we_ are currently // preparing. In both cases, the `checkpoint` data is fresh enough; there is no // other entity that currently legitimately owns the device represented in `pc`. -func (s *DeviceState) unpreparePartiallyPrepairedClaim(cuid string, pc PreparedClaim, checkpoint *Checkpoint) error { +func (s *DeviceState) unpreparePartiallyPrepairedClaim(cuid string, pc PreparedClaim, checkpoint *CheckpointState) error { if s.hamiCoreManager != nil { // The manager is created only when HAMiCoreSupport is enabled. // Prepare may have created the cache directory before a later step @@ -541,8 +662,8 @@ func (s *DeviceState) unpreparePartiallyPrepairedClaim(cuid string, pc PreparedC // When DynamicMIG is enabled, try to identify an orphaned MIG device // corresponding to `pc`. To that end, inspect which currently (completely) // prepared claims use which devices. - completedClaims := make(PreparedClaimsByUIDV2) - for cuid, c := range checkpoint.V2.PreparedClaims { + completedClaims := make(PreparedClaimsByUID) + for cuid, c := range checkpoint.PreparedClaims { if c.CheckpointState == ClaimCheckpointStatePrepareCompleted { completedClaims[cuid] = c } @@ -568,7 +689,7 @@ func (s *DeviceState) unpreparePartiallyPrepairedClaim(cuid string, pc PreparedC return nil } -func (s *DeviceState) createCheckpoint(ctx context.Context, cp *Checkpoint) error { +func (s *DeviceState) createCheckpoint(ctx context.Context, cp *CheckpointState) error { klog.V(6).Info("acquire cplock (create cp)") release, err := s.cplock.Acquire(ctx, flock.WithTimeout(10*time.Second)) if err != nil { @@ -576,12 +697,12 @@ func (s *DeviceState) createCheckpoint(ctx context.Context, cp *Checkpoint) erro } defer release() klog.V(7).Info("acquired cplock (createCheckpoint)") - err = s.checkpointManager.CreateCheckpoint(DriverPluginCheckpointFileBasename, cp) + err = s.checkpoints.Write(checkpointStateToAPI(cp)) klog.V(7).Info("create cp: done") return err } -func (s *DeviceState) getCheckpoint(ctx context.Context) (*Checkpoint, error) { +func (s *DeviceState) getCheckpoint(ctx context.Context) (*CheckpointState, error) { klog.V(7).Info("acquire cplock (getCheckpoint)") release, err := s.cplock.Acquire(ctx, flock.WithTimeout(10*time.Second)) if err != nil { @@ -590,13 +711,13 @@ func (s *DeviceState) getCheckpoint(ctx context.Context) (*Checkpoint, error) { defer release() klog.V(7).Info("acquired cplock (getCheckpoint)") - checkpoint := &Checkpoint{} - if err := s.checkpointManager.GetCheckpoint(DriverPluginCheckpointFileBasename, checkpoint); err != nil { + checkpoint, err := s.checkpoints.Read() + if err != nil { return nil, err } klog.V(7).Info("checkpoint read") - return checkpoint.ToLatestVersion(), nil + return checkpointStateFromAPI(checkpoint), nil } // Read checkpoint from store, perform mutation, and write checkpoint back. Any @@ -605,7 +726,7 @@ func (s *DeviceState) getCheckpoint(ctx context.Context) (*Checkpoint, error) { // certain that multiple read-mutate-write actions never overlap. Currently, // this is also ensured by the global PU lock -- but this inner lock is // explicit, tested, and can replace the global PU lock if desired. -func (s *DeviceState) updateCheckpoint(ctx context.Context, mutate func(*Checkpoint)) error { +func (s *DeviceState) updateCheckpoint(ctx context.Context, mutate func(*CheckpointState)) error { tucp0 := time.Now() klog.V(7).Info("acquire cplock (updateCheckpoint)") release, err := s.cplock.Acquire(ctx, flock.WithTimeout(10*time.Second)) @@ -615,18 +736,14 @@ func (s *DeviceState) updateCheckpoint(ctx context.Context, mutate func(*Checkpo defer release() klog.V(7).Info("acquired cplock (updateCheckpoint)") - checkpoint := &Checkpoint{} - if err := s.checkpointManager.GetCheckpoint(DriverPluginCheckpointFileBasename, checkpoint); err != nil { - return fmt.Errorf("updateCheckpoint: unable to get checkpoint: %w", err) - } - - // Potentially migrate to newest version. This also creates an empty - // `PreparedClaims` map if that field is so far `nil` (so that insertion is - // always safe). This is also called in the getCheckpoint() helper. - cp := checkpoint.ToLatestVersion() - mutate(cp) - - err = s.checkpointManager.CreateCheckpoint(DriverPluginCheckpointFileBasename, cp) + err = s.checkpoints.Update(func(checkpoint *checkpointapi.Checkpoint) error { + // The converted state always has a non-nil `PreparedClaims` map, so + // insertion is safe. + cp := checkpointStateFromAPI(checkpoint) + mutate(cp) + *checkpoint = *checkpointStateToAPI(cp) + return nil + }) if err != nil { return fmt.Errorf("unable to create checkpoint: %w", err) } @@ -634,17 +751,6 @@ func (s *DeviceState) updateCheckpoint(ctx context.Context, mutate func(*Checkpo return nil } -func (s *DeviceState) deleteClaimFromCheckpoint(ctx context.Context, claimRef kubeletplugin.NamespacedObject) error { - err := s.updateCheckpoint(ctx, func(cp *Checkpoint) { - delete(cp.V2.PreparedClaims, string(claimRef.UID)) - }) - if err != nil { - return fmt.Errorf("unable to update checkpoint: %w", err) - } - klog.V(6).Infof("Deleted claim from checkpoint: %s", claimRef.String()) - return nil -} - func (s *DeviceState) prepareDevices(ctx context.Context, claim *resourceapi.ResourceClaim) (PreparedDevices, error) { if claim.Status.Allocation == nil { return nil, fmt.Errorf("claim not yet allocated") @@ -1225,7 +1331,7 @@ func (s *DeviceState) requestedNonAdminDevices(claim *resourceapi.ResourceClaim) // validateNoOverlappingPreparedDevices checks whether the given claim requests any device that is // already allocated (non-admin) to a different claim that has completed preparation. -func (s *DeviceState) validateNoOverlappingPreparedDevices(checkpoint *Checkpoint, claim *resourceapi.ResourceClaim) error { +func (s *DeviceState) validateNoOverlappingPreparedDevices(checkpoint *CheckpointState, claim *resourceapi.ResourceClaim) error { claimUID := string(claim.UID) // Get the set of requested non-admin devices for the current claim. @@ -1234,7 +1340,7 @@ func (s *DeviceState) validateNoOverlappingPreparedDevices(checkpoint *Checkpoin return nil } - for existingClaimUID, pc := range checkpoint.V2.PreparedClaims { + for existingClaimUID, pc := range checkpoint.PreparedClaims { // Skip the current claim. if existingClaimUID == claimUID { continue diff --git a/cmd/hami-kubelet-plugin/device_state_test.go b/cmd/hami-kubelet-plugin/device_state_test.go index 15b6ae11..9d9a6a02 100644 --- a/cmd/hami-kubelet-plugin/device_state_test.go +++ b/cmd/hami-kubelet-plugin/device_state_test.go @@ -25,7 +25,6 @@ import ( resourceapi "k8s.io/api/resource/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/dynamic-resource-allocation/kubeletplugin" - "k8s.io/kubernetes/pkg/kubelet/checkpointmanager" "github.com/NVIDIA/k8s-dra-driver-gpu/pkg/flock" ) @@ -39,11 +38,12 @@ const ( func newTestDeviceState(t *testing.T) *DeviceState { dir := t.TempDir() - cm, err := checkpointmanager.NewCheckpointManager(dir) + checkpoints, err := newCheckpointStore(dir) require.NoError(t, err) return &DeviceState{ - checkpointManager: cm, - cplock: flock.NewFlock(filepath.Join(dir, "cp.lock")), + checkpointPath: filepath.Join(dir, DriverPluginCheckpointFileBasename), + checkpoints: checkpoints, + cplock: flock.NewFlock(filepath.Join(dir, "cp.lock")), } } @@ -68,7 +68,7 @@ func completedHAMiClaim() PreparedClaim { func TestInitCheckpoint(t *testing.T) { tests := []struct { name string - existing *CheckpointV2 + existing *CheckpointState wantClaims bool }{ { @@ -76,17 +76,17 @@ func TestInitCheckpoint(t *testing.T) { }, { name: "same boot keeps prepared claims", - existing: &CheckpointV2{NodeBootID: testBootID}, + existing: &CheckpointState{NodeBootID: testBootID}, wantClaims: true, }, { name: "legacy checkpoint without boot ID keeps prepared claims", - existing: &CheckpointV2{}, + existing: &CheckpointState{}, wantClaims: true, }, { name: "reboot discards prepared claims", - existing: &CheckpointV2{NodeBootID: testPreviousBootID}, + existing: &CheckpointState{NodeBootID: testPreviousBootID}, }, } @@ -96,15 +96,15 @@ func TestInitCheckpoint(t *testing.T) { s := newTestDeviceState(t) if tt.existing != nil { tt.existing.PreparedClaims = PreparedClaimsByUID{testClaimUID: completedHAMiClaim()} - require.NoError(t, s.createCheckpoint(ctx, &Checkpoint{V2: tt.existing})) + require.NoError(t, s.createCheckpoint(ctx, tt.existing)) } require.NoError(t, s.initCheckpoint(ctx, testBootID)) cp, err := s.getCheckpoint(ctx) require.NoError(t, err) - require.Equal(t, testBootID, cp.GetNodeBootID()) - _, exists := cp.V2.PreparedClaims[testClaimUID] + require.Equal(t, testBootID, cp.NodeBootID) + _, exists := cp.PreparedClaims[testClaimUID] require.Equal(t, tt.wantClaims, exists) }) } @@ -113,10 +113,10 @@ func TestInitCheckpoint(t *testing.T) { func TestPrepareReturnsCompletedHAMiClaim(t *testing.T) { ctx := context.Background() s := newTestDeviceState(t) - require.NoError(t, s.createCheckpoint(ctx, &Checkpoint{V2: &CheckpointV2{ + require.NoError(t, s.createCheckpoint(ctx, &CheckpointState{ NodeBootID: testBootID, PreparedClaims: PreparedClaimsByUID{testClaimUID: completedHAMiClaim()}, - }})) + })) claim := &resourceapi.ResourceClaim{ ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "claim", UID: testClaimUID}, diff --git a/cmd/hami-kubelet-plugin/driver.go b/cmd/hami-kubelet-plugin/driver.go index d230a7c6..02463263 100644 --- a/cmd/hami-kubelet-plugin/driver.go +++ b/cmd/hami-kubelet-plugin/driver.go @@ -311,32 +311,11 @@ func (d *driver) PrepareResourceClaims(ctx context.Context, claims []*resourceap klog.V(6).Infof("Prepare called for: %v", ClaimsToStrings(claims)) } - results := make(map[types.UID]kubeletplugin.PrepareResult) - - for _, claim := range claims { - results[claim.UID] = d.nodePrepareResource(ctx, claim) - } - - return results, nil -} - -func (d *driver) UnprepareResourceClaims(ctx context.Context, claimRefs []kubeletplugin.NamespacedObject) (map[types.UID]error, error) { - klog.V(6).Infof("Unprepare called for: %v", ClaimRefsToStrings(claimRefs)) - results := make(map[types.UID]error) - for _, claimRef := range claimRefs { - results[claimRef.UID] = d.nodeUnprepareResource(ctx, claimRef) + results := make(map[types.UID]kubeletplugin.PrepareResult, len(claims)) + if len(claims) == 0 { + return results, nil } - return results, nil -} - -func (d *driver) HandleError(ctx context.Context, err error, msg string) { - // For now we just follow the advice documented in the DRAPlugin API docs. - // See: https://pkg.go.dev/k8s.io/apimachinery/pkg/util/runtime#HandleErrorWithContext - runtime.HandleErrorWithContext(ctx, err, msg) -} - -func (d *driver) nodePrepareResource(ctx context.Context, claim *resourceapi.ResourceClaim) kubeletplugin.PrepareResult { // Instead of a global prepare/unprepare (PU) lock, we could rely on // fine-grained checkpoint locking, which was proven to work correctly in // case of DynamicMIG mode. However, out of caution, retain this global PU @@ -345,63 +324,91 @@ func (d *driver) nodePrepareResource(ctx context.Context, claim *resourceapi.Res t0 := time.Now() release, err := d.pulock.Acquire(ctx, flock.WithTimeout(10*time.Second)) if err != nil { - return kubeletplugin.PrepareResult{ - Err: fmt.Errorf("error acquiring prep/unprep lock: %w", err), + for _, claim := range claims { + results[claim.UID] = kubeletplugin.PrepareResult{Err: fmt.Errorf("error acquiring prep/unprep lock: %w", err)} } + return results, nil } defer release() klog.V(6).Infof("t_prep_lock_acq %.3f s", time.Since(t0).Seconds()) - cs := ResourceClaimToString(claim) tprep0 := time.Now() - devs, err := d.state.Prepare(ctx, claim) - klog.V(6).Infof("t_prep %.3f s (claim %s)", time.Since(tprep0).Seconds(), cs) - - if err != nil { - return kubeletplugin.PrepareResult{ - Err: fmt.Errorf("error preparing devices for claim %s: %w", cs, err), - } - } + prepared := d.state.PrepareClaims(ctx, claims) + klog.V(6).Infof("t_prep %.3f s (%d claim(s))", time.Since(tprep0).Seconds(), len(claims)) + var publishErr error if featuregates.Enabled(featuregates.PassthroughSupport) { // Re-advertise updated resourceslice after preparing devices. - if err = d.publishResources(ctx, d.state.config); err != nil { - return kubeletplugin.PrepareResult{ - Err: fmt.Errorf("error preparing devices for claim %v: %w", claim.UID, err), - } - } + publishErr = d.publishResources(ctx, d.state.config) } - klog.Infof("Returning newly prepared devices for claim '%s': %v", cs, devs) - return kubeletplugin.PrepareResult{Devices: devs} + for _, claim := range claims { + cs := ResourceClaimToString(claim) + r := prepared[string(claim.UID)] + switch { + case r.Err != nil: + results[claim.UID] = kubeletplugin.PrepareResult{Err: fmt.Errorf("error preparing devices for claim %s: %w", cs, r.Err)} + case publishErr != nil: + results[claim.UID] = kubeletplugin.PrepareResult{Err: fmt.Errorf("error preparing devices for claim %v: %w", claim.UID, publishErr)} + default: + klog.Infof("Returning newly prepared devices for claim '%s': %v", cs, r.Devices) + results[claim.UID] = kubeletplugin.PrepareResult{Devices: r.Devices} + } + } + return results, nil } -func (d *driver) nodeUnprepareResource(ctx context.Context, claimRef kubeletplugin.NamespacedObject) error { +func (d *driver) UnprepareResourceClaims(ctx context.Context, claimRefs []kubeletplugin.NamespacedObject) (map[types.UID]error, error) { + klog.V(6).Infof("Unprepare called for: %v", ClaimRefsToStrings(claimRefs)) + results := make(map[types.UID]error, len(claimRefs)) + if len(claimRefs) == 0 { + return results, nil + } + t0 := time.Now() release, err := d.pulock.Acquire(ctx, flock.WithTimeout(10*time.Second)) if err != nil { - return fmt.Errorf("error acquiring prep/unprep lock: %w", err) + for _, claimRef := range claimRefs { + results[claimRef.UID] = fmt.Errorf("error acquiring prep/unprep lock: %w", err) + } + return results, nil } defer release() klog.V(6).Infof("t_unprep_lock_acq %.3f s", time.Since(t0).Seconds()) - cs := claimRef.String() tunprep0 := time.Now() - err = d.state.Unprepare(ctx, claimRef) - klog.V(6).Infof("t_unprep %.3f s (claim %s)", time.Since(tunprep0).Seconds(), cs) - - if err != nil { - return fmt.Errorf("error unpreparing devices for claim %v: %w", claimRef.String(), err) - } + errs := d.state.UnprepareClaims(ctx, claimRefs) + klog.V(6).Infof("t_unprep %.3f s (%d claim(s))", time.Since(tunprep0).Seconds(), len(claimRefs)) + var publishErr error if featuregates.Enabled(featuregates.PassthroughSupport) { // Re-advertise updated resourceslice after unpreparing devices. - if err = d.publishResources(ctx, d.state.config); err != nil { - return fmt.Errorf("error publishing resources: %w", err) + publishErr = d.publishResources(ctx, d.state.config) + } + + for _, claimRef := range claimRefs { + switch err := errs[string(claimRef.UID)]; { + case err != nil: + results[claimRef.UID] = fmt.Errorf("error unpreparing devices for claim %v: %w", claimRef.String(), err) + case publishErr != nil: + results[claimRef.UID] = fmt.Errorf("error publishing resources: %w", publishErr) + default: + results[claimRef.UID] = nil } } + return results, nil +} - return nil +// nodeUnprepareResource unprepares one claim; used by the checkpoint cleanup. +func (d *driver) nodeUnprepareResource(ctx context.Context, claimRef kubeletplugin.NamespacedObject) error { + results, _ := d.UnprepareResourceClaims(ctx, []kubeletplugin.NamespacedObject{claimRef}) + return results[claimRef.UID] +} + +func (d *driver) HandleError(ctx context.Context, err error, msg string) { + // For now we just follow the advice documented in the DRAPlugin API docs. + // See: https://pkg.go.dev/k8s.io/apimachinery/pkg/util/runtime#HandleErrorWithContext + runtime.HandleErrorWithContext(ctx, err, msg) } func (d *driver) publishResources(ctx context.Context, config *Config) error { diff --git a/cmd/hami-kubelet-plugin/hami_contract_test.go b/cmd/hami-kubelet-plugin/hami_contract_test.go index e28d2a87..ba44d515 100644 --- a/cmd/hami-kubelet-plugin/hami_contract_test.go +++ b/cmd/hami-kubelet-plugin/hami_contract_test.go @@ -133,7 +133,7 @@ func newTestPrepareDeviceState(t *testing.T, claims ...*resourceapi.ResourceClai s.cdi = cdi s.hamiCoreManager = manager s.allocatable = AllocatableDevices{gpu.CanonicalName(): gpu} - require.NoError(t, s.createCheckpoint(context.Background(), &Checkpoint{V2: &CheckpointV2{NodeBootID: testBootID}})) + require.NoError(t, s.createCheckpoint(context.Background(), &CheckpointState{NodeBootID: testBootID})) return s } @@ -270,7 +270,7 @@ func TestHAMiPrepareWritesCDISpec(t *testing.T) { cp, err := s.getCheckpoint(ctx) require.NoError(t, err) - require.Equal(t, ClaimCheckpointStatePrepareCompleted, cp.V2.PreparedClaims["uid-a"].CheckpointState) + require.Equal(t, ClaimCheckpointStatePrepareCompleted, cp.PreparedClaims["uid-a"].CheckpointState) } func TestHAMiPrepareSharesDeviceAcrossClaims(t *testing.T) { @@ -352,8 +352,8 @@ func TestHAMiPrepareResumesStartedClaim(t *testing.T) { ctx := context.Background() claim := testHAMiClaim(t, "uid-a", 30, "4Gi") s := newTestPrepareDeviceState(t, claim) - require.NoError(t, s.updateCheckpoint(ctx, func(cp *Checkpoint) { - cp.V2.PreparedClaims["uid-a"] = PreparedClaim{ + require.NoError(t, s.updateCheckpoint(ctx, func(cp *CheckpointState) { + cp.PreparedClaims["uid-a"] = PreparedClaim{ CheckpointState: ClaimCheckpointStatePrepareStarted, Status: claim.Status, Name: claim.Name, @@ -366,7 +366,7 @@ func TestHAMiPrepareResumesStartedClaim(t *testing.T) { cp, err := s.getCheckpoint(ctx) require.NoError(t, err) - require.Equal(t, ClaimCheckpointStatePrepareCompleted, cp.V2.PreparedClaims["uid-a"].CheckpointState) + require.Equal(t, ClaimCheckpointStatePrepareCompleted, cp.PreparedClaims["uid-a"].CheckpointState) require.FileExists(t, claimSpecPath(s, "uid-a")) } @@ -391,7 +391,7 @@ func TestHAMiUnprepareRemovesClaimState(t *testing.T) { uid := string(claim.UID) cp, err := s.getCheckpoint(ctx) require.NoError(t, err) - require.Equal(t, ClaimCheckpointStatePrepareCompleted, cp.V2.PreparedClaims[uid].CheckpointState) + require.Equal(t, ClaimCheckpointStatePrepareCompleted, cp.PreparedClaims[uid].CheckpointState) edits := claimDeviceEdits(t, s, uid) const cacheEnv = "CUDA_DEVICE_MEMORY_SHARED_CACHE=" index := slices.IndexFunc(edits.Env, func(env string) bool { return strings.HasPrefix(env, cacheEnv) }) @@ -410,7 +410,7 @@ func TestHAMiUnprepareRemovesClaimState(t *testing.T) { require.NoFileExists(t, claimSpecPath(s, uid)) cp, err = s.getCheckpoint(ctx) require.NoError(t, err) - require.NotContains(t, cp.V2.PreparedClaims, uid) + require.NotContains(t, cp.PreparedClaims, uid) // The kubelet may repeat Unprepare. require.NoError(t, s.Unprepare(ctx, ref)) diff --git a/cmd/hami-kubelet-plugin/hami_core_legacy_test.go b/cmd/hami-kubelet-plugin/hami_core_legacy_test.go index 53fc9d9e..68849e4b 100644 --- a/cmd/hami-kubelet-plugin/hami_core_legacy_test.go +++ b/cmd/hami-kubelet-plugin/hami_core_legacy_test.go @@ -97,9 +97,9 @@ func TestLegacyClaimDirectoryPreservedUntilUnprepare(t *testing.T) { completed.Status.ReservedFor = []resourceapi.ResourceClaimConsumerReference{{Resource: "pods", Name: pod.Name, UID: pod.UID}} // Model an upgrade from a checkpoint without a boot ID. Neither boot-ID // migration nor same-boot restart may delete caches of running workloads. - require.NoError(t, s.createCheckpoint(ctx, &Checkpoint{V2: &CheckpointV2{ + require.NoError(t, s.createCheckpoint(ctx, &CheckpointState{ PreparedClaims: PreparedClaimsByUID{testClaimUID: completed}, - }})) + })) claim := &resourceapi.ResourceClaim{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "claim", UID: testClaimUID}} for range 2 { require.NoError(t, s.initCheckpoint(ctx, testBootID)) @@ -128,7 +128,7 @@ func TestLegacyClaimDirectoryPreservedUntilUnprepare(t *testing.T) { require.NoDirExists(t, legacy) cp, err := s.getCheckpoint(ctx) require.NoError(t, err) - require.NotContains(t, cp.V2.PreparedClaims, testClaimUID) + require.NotContains(t, cp.PreparedClaims, testClaimUID) } func TestLegacyClaimCleanupFailureCanRetry(t *testing.T) { @@ -145,16 +145,16 @@ func TestLegacyClaimCleanupFailureCanRetry(t *testing.T) { s := legacyCleanupTestState(t, root) completed := completedHAMiClaim() completed.PreparedDevices[0].Devices[0].HAMiGpu.Info = &HAMiGpuInfo{} - require.NoError(t, s.createCheckpoint(ctx, &Checkpoint{V2: &CheckpointV2{ + require.NoError(t, s.createCheckpoint(ctx, &CheckpointState{ NodeBootID: testBootID, PreparedClaims: PreparedClaimsByUID{testClaimUID: completed}, - }})) + })) spec := filepath.Join(s.cdi.cdiRoot, cdiapi.GenerateTransientSpecName(cdiVendor, cdiClaimClass, testClaimUID)+".yaml") require.NoError(t, os.WriteFile(spec, []byte("existing CDI spec"), 0600)) ref := kubeletplugin.NamespacedObject{UID: types.UID(testClaimUID)} require.ErrorContains(t, s.Unprepare(ctx, ref), "legacy claim cache directory") cp, err := s.getCheckpoint(ctx) require.NoError(t, err) - require.Equal(t, completed, cp.V2.PreparedClaims[testClaimUID]) + require.Equal(t, completed, cp.PreparedClaims[testClaimUID]) require.FileExists(t, spec, "failed cleanup must not remove the CDI spec") require.FileExists(t, marker, "failed legacy cleanup must not erase current ownership") @@ -169,7 +169,7 @@ func TestLegacyClaimCleanupFailureCanRetry(t *testing.T) { require.NoFileExists(t, spec) cp, err = s.getCheckpoint(ctx) require.NoError(t, err) - require.NotContains(t, cp.V2.PreparedClaims, testClaimUID) + require.NotContains(t, cp.PreparedClaims, testClaimUID) } func TestUnprepareLegacyRejectsUnsafeClaimUID(t *testing.T) { diff --git a/cmd/hami-kubelet-plugin/hami_core_test.go b/cmd/hami-kubelet-plugin/hami_core_test.go index bfe6919f..b1d5e3a7 100644 --- a/cmd/hami-kubelet-plugin/hami_core_test.go +++ b/cmd/hami-kubelet-plugin/hami_core_test.go @@ -1030,7 +1030,7 @@ func TestUnpreparePartialHAMiBeforeCUDAInitialization(t *testing.T) { CheckpointState: ClaimCheckpointStatePrepareStarted, Status: resourceapi.ResourceClaimStatus{Allocation: &resourceapi.AllocationResult{}}, } - require.NoError(t, state.unpreparePartiallyPrepairedClaim("claim-uid", partial, (&Checkpoint{}).ToLatestVersion())) + require.NoError(t, state.unpreparePartiallyPrepairedClaim("claim-uid", partial, newCheckpointState())) require.NoDirExists(t, directory) } diff --git a/cmd/hami-kubelet-plugin/testdata/legacy-checkpoint-v1.json b/cmd/hami-kubelet-plugin/testdata/legacy-checkpoint-v1.json new file mode 100644 index 00000000..f3750bb5 --- /dev/null +++ b/cmd/hami-kubelet-plugin/testdata/legacy-checkpoint-v1.json @@ -0,0 +1 @@ +{"checksum":2232786024,"v1":{"preparedClaims":{"claim-uid-1":{"status":{"allocation":{"devices":{"results":[{"request":"gpu","driver":"hami-core-gpu.project-hami.io","pool":"node-a","device":"gpu-0"}]}}},"preparedDevices":[{"devices":[{"hami-gpu":{"info":{"uuid":"GPU-bbbb"},"device":{"Requests":["hami"],"PoolName":"node-a","DeviceName":"hami-gpu-1","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=hami-gpu-1"]}},"gpu":null,"mig":null},{"hami-gpu":null,"gpu":{"info":{"uuid":"GPU-aaaa"},"device":{"Requests":["gpu"],"PoolName":"node-a","DeviceName":"gpu-0","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-0"]}},"mig":null}],"configState":{"mpsControlDaemonID":""}},{"devices":[{"hami-gpu":null,"gpu":null,"mig":{"concrete":{"parentMinor":1,"giId":2,"ciId":0,"migUUID":"MIG-cccc","parentUUID":"GPU-dddd"},"device":{"Requests":["mig"],"PoolName":"node-a","DeviceName":"gpu-1-mig-1g10gb-2","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-1-mig-1g10gb-2"]}}},{"hami-gpu":null,"gpu":null,"mig":null,"vfio":{"info":{"uuid":"GPU-eeee"},"device":{"Requests":["vfio"],"PoolName":"node-a","DeviceName":"gpu-3-vfio","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-3-vfio"]}}}],"configState":{"mpsControlDaemonID":"mps-claim-uid-1"}}]}}}} \ No newline at end of file diff --git a/cmd/hami-kubelet-plugin/testdata/legacy-checkpoint.json b/cmd/hami-kubelet-plugin/testdata/legacy-checkpoint.json new file mode 100644 index 00000000..acceeee4 --- /dev/null +++ b/cmd/hami-kubelet-plugin/testdata/legacy-checkpoint.json @@ -0,0 +1 @@ +{"checksum":2232786024,"v1":{"preparedClaims":{"claim-uid-1":{"status":{"allocation":{"devices":{"results":[{"request":"gpu","driver":"hami-core-gpu.project-hami.io","pool":"node-a","device":"gpu-0"}]}}},"preparedDevices":[{"devices":[{"hami-gpu":{"info":{"uuid":"GPU-bbbb"},"device":{"Requests":["hami"],"PoolName":"node-a","DeviceName":"hami-gpu-1","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=hami-gpu-1"]}},"gpu":null,"mig":null},{"hami-gpu":null,"gpu":{"info":{"uuid":"GPU-aaaa"},"device":{"Requests":["gpu"],"PoolName":"node-a","DeviceName":"gpu-0","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-0"]}},"mig":null}],"configState":{"mpsControlDaemonID":""}},{"devices":[{"hami-gpu":null,"gpu":null,"mig":{"concrete":{"parentMinor":1,"giId":2,"ciId":0,"migUUID":"MIG-cccc","parentUUID":"GPU-dddd"},"device":{"Requests":["mig"],"PoolName":"node-a","DeviceName":"gpu-1-mig-1g10gb-2","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-1-mig-1g10gb-2"]}}},{"hami-gpu":null,"gpu":null,"mig":null,"vfio":{"info":{"uuid":"GPU-eeee"},"device":{"Requests":["vfio"],"PoolName":"node-a","DeviceName":"gpu-3-vfio","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-3-vfio"]}}}],"configState":{"mpsControlDaemonID":"mps-claim-uid-1"}}]}}},"v2":{"checksum":1760879644,"preparedClaims":{"claim-uid-1":{"checkpointState":"PrepareCompleted","status":{"allocation":{"devices":{"results":[{"request":"gpu","driver":"hami-core-gpu.project-hami.io","pool":"node-a","device":"gpu-0"}]}}},"preparedDevices":[{"devices":[{"hami-gpu":{"info":{"uuid":"GPU-bbbb"},"device":{"Requests":["hami"],"PoolName":"node-a","DeviceName":"hami-gpu-1","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=hami-gpu-1"]}},"gpu":null,"mig":null},{"hami-gpu":null,"gpu":{"info":{"uuid":"GPU-aaaa"},"device":{"Requests":["gpu"],"PoolName":"node-a","DeviceName":"gpu-0","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-0"]}},"mig":null}],"configState":{"mpsControlDaemonID":""}},{"devices":[{"hami-gpu":null,"gpu":null,"mig":{"concrete":{"parentMinor":1,"giId":2,"ciId":0,"migUUID":"MIG-cccc","parentUUID":"GPU-dddd"},"device":{"Requests":["mig"],"PoolName":"node-a","DeviceName":"gpu-1-mig-1g10gb-2","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-1-mig-1g10gb-2"]}}},{"hami-gpu":null,"gpu":null,"mig":null,"vfio":{"info":{"uuid":"GPU-eeee"},"device":{"Requests":["vfio"],"PoolName":"node-a","DeviceName":"gpu-3-vfio","CDIDeviceIDs":["k8s.gpu.nvidia.com/device=gpu-3-vfio"]}}}],"configState":{"mpsControlDaemonID":"mps-claim-uid-1"}}],"name":"claim-1","namespace":"default"},"claim-uid-2":{"checkpointState":"PrepareStarted","status":{},"name":"claim-2","namespace":"team-a"}},"nodeBootID":"boot-id-1"}} \ No newline at end of file diff --git a/go.mod b/go.mod index 6310cf82..25312fdd 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/Project-HAMi/k8s-dra-driver -go 1.25.1 +go 1.26.0 require ( github.com/Masterminds/semver v1.5.0 @@ -8,6 +8,7 @@ require ( github.com/NVIDIA/go-nvml v0.13.0-1 github.com/NVIDIA/k8s-dra-driver-gpu v0.0.0-20260304152636-db70fc24dd3f github.com/NVIDIA/nvidia-container-toolkit v1.18.2 + github.com/Project-HAMi/dra-lib v0.1.0 github.com/google/uuid v1.6.0 github.com/sirupsen/logrus v1.9.4 github.com/spf13/pflag v1.0.10 @@ -22,7 +23,6 @@ require ( k8s.io/dynamic-resource-allocation v0.34.1 k8s.io/klog/v2 v2.130.1 k8s.io/kubelet v0.34.1 - k8s.io/kubernetes v1.34.2 k8s.io/mount-utils v0.34.1 k8s.io/utils v0.0.0-20250604170112-4c0f3b243397 tags.cncf.io/container-device-interface v1.1.0 @@ -57,6 +57,7 @@ require ( github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/opencontainers/runtime-spec v1.3.0 // indirect github.com/opencontainers/runtime-tools v0.9.1-0.20251114084447-edf4cb3d2116 // indirect + github.com/opencontainers/selinux v1.11.1 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/prometheus/client_golang v1.23.2 // indirect @@ -73,12 +74,12 @@ require ( go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.27.0 // indirect go.yaml.in/yaml/v2 v2.4.2 // indirect - golang.org/x/mod v0.29.0 // indirect - golang.org/x/net v0.47.0 // indirect + golang.org/x/mod v0.41.0 // indirect + golang.org/x/net v0.60.0 // indirect golang.org/x/oauth2 v0.32.0 // indirect - golang.org/x/sys v0.38.0 // indirect - golang.org/x/term v0.37.0 // indirect - golang.org/x/text v0.31.0 // indirect + golang.org/x/sys v0.48.0 // indirect + golang.org/x/term v0.46.0 // indirect + golang.org/x/text v0.42.0 // indirect golang.org/x/time v0.14.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20251029180050-ab9386a59fda // indirect google.golang.org/protobuf v1.36.10 // indirect diff --git a/go.sum b/go.sum index 322338c0..f503ae35 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,5 @@ github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww= github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= -github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= -github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= github.com/NVIDIA/go-nvlib v0.9.0 h1:GKLIvLJ0uhCtTLLZp2Q8QIDRxOYH45MM4Y5OO3U5Rho= github.com/NVIDIA/go-nvlib v0.9.0/go.mod h1:7mzx9FSdO9fXWP9NKuZmWkCwhkEcSWQFe2tmFwtLb9c= github.com/NVIDIA/go-nvml v0.13.0-1 h1:OLX8Jq3dONuPOQPC7rndB6+iDmDakw0XTYgzMxObkEw= @@ -10,6 +8,8 @@ github.com/NVIDIA/k8s-dra-driver-gpu v0.0.0-20260304152636-db70fc24dd3f h1:sud+W github.com/NVIDIA/k8s-dra-driver-gpu v0.0.0-20260304152636-db70fc24dd3f/go.mod h1:gQf1wA0RPy3ygdBpIsnkLYtUhUTUouPbMXYNrgRo/Y8= github.com/NVIDIA/nvidia-container-toolkit v1.18.2 h1:S46SDe5aez/qeRvTybHQqOXPNcRphLnIuXoqDDyx8YY= github.com/NVIDIA/nvidia-container-toolkit v1.18.2/go.mod h1:/mroSjCgjTpYH74dlaPw7KDQHIry/xDuQiii9SP5eCY= +github.com/Project-HAMi/dra-lib v0.1.0 h1:k5TfLThCcKUz+OYBt1DeCGkV04rn3yNVsuZGn2SG2X4= +github.com/Project-HAMi/dra-lib v0.1.0/go.mod h1:JeSmxMCH2CMFCO7QEqVzdNJdi+KWjBdVzLpbQPaqGNw= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM= @@ -182,14 +182,14 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA= -golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w= +golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= +golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY= -golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU= +golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= +golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= golang.org/x/oauth2 v0.32.0 h1:jsCblLleRMDrxMN29H3z/k1KliIvpLgCkE6R8FXXNgY= golang.org/x/oauth2 v0.32.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -198,22 +198,22 @@ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= -golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= -golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU= -golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254= +golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= +golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE= +golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= -golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= +golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= +golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ= -golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs= +golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= +golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -252,8 +252,6 @@ k8s.io/kube-openapi v0.0.0-20250710124328-f3f2b991d03b h1:MloQ9/bdJyIu9lb1PzujOP k8s.io/kube-openapi v0.0.0-20250710124328-f3f2b991d03b/go.mod h1:UZ2yyWbFTpuhSbFhv24aGNOdoRdJZgsIObGBUaYVsts= k8s.io/kubelet v0.34.1 h1:doAaTA9/Yfzbdq/u/LveZeONp96CwX9giW6b+oHn4m4= k8s.io/kubelet v0.34.1/go.mod h1:PtV3Ese8iOM19gSooFoQT9iyRisbmJdAPuDImuccbbA= -k8s.io/kubernetes v1.34.2 h1:WQdDvYJazkmkwSncgNwGvVtaCt4TYXIU3wSMRgvp3MI= -k8s.io/kubernetes v1.34.2/go.mod h1:m6pZk6a179pRo2wsTiCPORJ86iOEQmfIzUvtyEF8BwA= k8s.io/mount-utils v0.34.1 h1:zMBEFav8Rxwm54S8srzy5FxAc4KQ3X4ZcjnqTCzHmZk= k8s.io/mount-utils v0.34.1/go.mod h1:MIjjYlqJ0ziYQg0MO09kc9S96GIcMkhF/ay9MncF0GA= k8s.io/utils v0.0.0-20250604170112-4c0f3b243397 h1:hwvWFiBzdWw1FhfY1FooPn3kzWuJ8tmbZBHi4zVsl1Y=