k8s.io/kubernetes@v1.29.3/test/e2e/storage/drivers/csi-test/mock/cache/SnapshotCache.go (about) 1 /* 2 Copyright 2021 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package cache 18 19 import ( 20 "strings" 21 "sync" 22 23 "github.com/container-storage-interface/spec/lib/go/csi" 24 ) 25 26 type SnapshotCache interface { 27 Add(snapshot Snapshot) 28 29 Delete(i int) 30 31 List(ready bool) []csi.Snapshot 32 33 FindSnapshot(k, v string) (int, Snapshot) 34 } 35 36 type Snapshot struct { 37 Name string 38 Parameters map[string]string 39 SnapshotCSI csi.Snapshot 40 } 41 42 type snapshotCache struct { 43 snapshotsRWL sync.RWMutex 44 snapshots []Snapshot 45 } 46 47 func NewSnapshotCache() SnapshotCache { 48 return &snapshotCache{ 49 snapshots: make([]Snapshot, 0), 50 } 51 } 52 53 func (snap *snapshotCache) Add(snapshot Snapshot) { 54 snap.snapshotsRWL.Lock() 55 defer snap.snapshotsRWL.Unlock() 56 57 snap.snapshots = append(snap.snapshots, snapshot) 58 } 59 60 func (snap *snapshotCache) Delete(i int) { 61 snap.snapshotsRWL.Lock() 62 defer snap.snapshotsRWL.Unlock() 63 64 copy(snap.snapshots[i:], snap.snapshots[i+1:]) 65 snap.snapshots = snap.snapshots[:len(snap.snapshots)-1] 66 } 67 68 func (snap *snapshotCache) List(ready bool) []csi.Snapshot { 69 snap.snapshotsRWL.RLock() 70 defer snap.snapshotsRWL.RUnlock() 71 72 snapshots := make([]csi.Snapshot, 0) 73 for _, v := range snap.snapshots { 74 if v.SnapshotCSI.GetReadyToUse() { 75 snapshots = append(snapshots, v.SnapshotCSI) 76 } 77 } 78 79 return snapshots 80 } 81 82 func (snap *snapshotCache) FindSnapshot(k, v string) (int, Snapshot) { 83 snap.snapshotsRWL.RLock() 84 defer snap.snapshotsRWL.RUnlock() 85 86 snapshotIdx := -1 87 for i, vi := range snap.snapshots { 88 switch k { 89 case "id": 90 if strings.EqualFold(v, vi.SnapshotCSI.GetSnapshotId()) { 91 return i, vi 92 } 93 case "sourceVolumeId": 94 if strings.EqualFold(v, vi.SnapshotCSI.SourceVolumeId) { 95 return i, vi 96 } 97 case "name": 98 if vi.Name == v { 99 return i, vi 100 } 101 } 102 } 103 104 return snapshotIdx, Snapshot{} 105 }