/
pv_to_backingdiskobjectid_mapping.go
209 lines (181 loc) · 8.08 KB
/
pv_to_backingdiskobjectid_mapping.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
/*
Copyright 2022 The Kubernetes 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 syncer
import (
"context"
"strings"
cnstypes "github.com/vmware/govmomi/cns/types"
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
clientset "k8s.io/client-go/kubernetes"
"sigs.k8s.io/vsphere-csi-driver/v3/pkg/csi/service/logger"
)
// TODO: refactor pv to backingdiskobjectid and volume health code to reduce duplicated code
func csiGetPVtoBackingDiskObjectIdMapping(ctx context.Context, k8sclient clientset.Interface,
metadataSyncer *metadataSyncInformer, vc string) {
log := logger.GetLogger(ctx)
log.Debugf("csiGetPVtoBackingDiskObjectIdMapping for %s: start", vc)
// Call CNS QueryAll to get container volumes by cluster ID.
queryFilter := cnstypes.CnsQueryFilter{
ContainerClusterIds: []string{
clusterIDforVolumeMetadata,
},
}
querySelection := cnstypes.CnsQuerySelection{
Names: []string{
string(cnstypes.QuerySelectionNameTypeBackingObjectDetails),
string(cnstypes.QuerySelectionNameTypeVolumeType),
},
}
cnsVolumeMgr, err := getVolManagerForVcHost(ctx, vc, metadataSyncer)
if err != nil {
log.Errorf("csiGetPVtoBackingDiskObjectIdMapping for %s: Failed to get volume manager. Err: %v", vc, err)
return
}
queryAllResult, err := cnsVolumeMgr.QueryAllVolume(ctx, queryFilter, querySelection)
if err != nil {
log.Errorf("csiGetPVtoBackingDiskObjectIdMapping for %s: failed to QueryAllVolume with err=%+v", vc, err)
return
}
// Get K8s PVs in State "Bound".
k8sPVs, err := getBoundPVs(ctx, metadataSyncer)
if err != nil {
log.Errorf("csiGetPVtoBackingDiskObjectIdMapping for %s: Failed to get PVs from kubernetes. Err: %+v", vc, err)
return
}
// volumeHandleToPvcMap maps pv.Spec.CSI.VolumeHandle to the pvc object which
// bounded to the pv.
volumeHandleToPvcMap := make(volumeHandlePVCMap, len(k8sPVs))
// volumeHandleToPvUidMap maps volumehandle to pv uid
volumeHandleToPvUidMap := make(volumeIdToPvUidMap, len(k8sPVs))
for _, pv := range k8sPVs {
if pv.Spec.ClaimRef != nil && pv.Status.Phase == v1.VolumeBound {
pvc, err := metadataSyncer.pvcLister.PersistentVolumeClaims(
pv.Spec.ClaimRef.Namespace).Get(pv.Spec.ClaimRef.Name)
if err != nil {
log.Warnf("csiGetPVtoBackingDiskObjectIdMapping for %s: Failed to get pvc for namespace %s and name %s. err=%+v",
vc, pv.Spec.ClaimRef.Namespace, pv.Spec.ClaimRef.Name, err)
continue
}
volumeHandleToPvcMap[pv.Spec.CSI.VolumeHandle] = pvc
log.Debugf("csiGetPVtoBackingDiskObjectIdMapping for %s: pvc %s/%s is backed by pv %s volumeHandle %s, pv uid is %s",
vc, pvc.Namespace, pvc.Name, pv.Name, pv.Spec.CSI.VolumeHandle, string(pv.UID))
volumeHandleToPvUidMap[pv.Spec.CSI.VolumeHandle] = string(pv.UID)
}
}
// pv to backingDiskObjectId Map maps vol.VolumeId.Id to backingobjectId.
volumeIdToBackingObjectIdMap := make(volumeIdToPvUidMap, len(queryAllResult.Volumes))
for _, vol := range queryAllResult.Volumes {
// NOTE: BackingDiskObjectId is the id of vvol or vSan; BackingDiskId is the same as VolumeId.
// This is only supported for block volumes.
if vol.VolumeType != string(cnstypes.CnsVolumeTypeBlock) {
continue
}
val, ok := vol.BackingObjectDetails.(*cnstypes.CnsBlockBackingDetails)
if ok {
volumeIdToBackingObjectIdMap[vol.VolumeId.Id] = val.BackingDiskObjectId
}
}
for volID, pvc := range volumeHandleToPvcMap {
if _, ok := volumeIdToBackingObjectIdMap[volID]; !ok {
log.Debugf("csiGetPVtoBackingDiskObjectIdMapping for %s: Skipping vol %s as it is not found on this VC.",
vc, volID)
continue
}
pvToBackingDiskObjectIdPair := volumeHandleToPvUidMap[volID] + ":" + volumeIdToBackingObjectIdMap[volID]
updated, err := updatePVtoBackingDiskObjectIdMappingStatus(ctx, k8sclient, pvc, pvToBackingDiskObjectIdPair)
if err != nil {
log.Error("csiGetPVtoBackingDiskObjectIdMapping for %s: Failed to update pv to backingDiskObjectId mapping",
vc)
return
}
if updated {
log.Infof("csiGetPVtoBackingDiskObjectIdMapping for %s: pvc %s is updated with pv to backingDiskObjectId mapping %s",
vc, pvc.Name, pvToBackingDiskObjectIdPair)
}
}
log.Debugf("csiGetPVtoBackingDiskObjectIdMapping for %s: end", vc)
}
func validatePvToBackingDiskObjectIdPair(pvToBackingDiskObjectIdPair string) bool {
split := strings.Split(pvToBackingDiskObjectIdPair, ":")
if len(split) < 2 {
return false
}
if split[0] == "" || split[1] == "" {
return false
}
return true
}
func updatePVtoBackingDiskObjectIdMappingStatus(ctx context.Context, k8sclient clientset.Interface,
pvc *v1.PersistentVolumeClaim, pvToBackingDiskObjectIdPair string) (bool, error) {
log := logger.GetLogger(ctx)
val, found := pvc.Annotations[annPVtoBackingDiskObjectId]
isValidate := validatePvToBackingDiskObjectIdPair(pvToBackingDiskObjectIdPair)
if !isValidate {
if !found {
log.Debugf("updatePVtoBackingDiskObjectIdMappingStatus: no previous mapping found in annotation. No need to update.")
return false, nil
} else {
// If there is any previous pv to backingdiskobjectid mapping found,
// set it as empty as queryAll returns nothing in this cycle
pvToBackingDiskObjectIdPair = ""
}
}
if !found || val != pvToBackingDiskObjectIdPair {
// PVToBackingDiskObjectId annotation on pvc is changed, set it to new value.
metav1.SetMetaDataAnnotation(&pvc.ObjectMeta, annPVtoBackingDiskObjectId, pvToBackingDiskObjectIdPair)
log.Infof("updatePVtoBackingDiskObjectIdMappingStatus: set pv to backingdiskobjectid annotation for "+
"pvc %s/%s from old value %s to new value %s",
pvc.Namespace, pvc.Name, val, pvToBackingDiskObjectIdPair)
_, err := k8sclient.CoreV1().PersistentVolumeClaims(pvc.Namespace).Update(ctx, pvc, metav1.UpdateOptions{})
if err != nil {
if apierrors.IsConflict(err) {
log.Debugf("updatePVtoBackingDiskObjectIdMappingStatus: Failed to update pvc %s/%s with err:%+v, "+
"will retry the update", pvc.Namespace, pvc.Name, err)
// pvc get from pvcLister may be stale, try to get updated pvc which
// bound to pv from API server.
newPvc, err := k8sclient.CoreV1().PersistentVolumeClaims(pvc.Namespace).Get(
ctx, pvc.Name, metav1.GetOptions{})
if err != nil {
log.Errorf("updatePVtoBackingDiskObjectIdMappingStatus: pv to backingdiskobjectid annotation for "+
"pvc %s/%s is not updated because failed to get pvc from API server. err=%+v",
pvc.Namespace, pvc.Name, err)
return false, err
}
log.Infof("updatePVtoBackingDiskObjectIdMappingStatus: updating pv to backingdiskobjectid annotation "+
"for pvc %s/%s which get from API server from old value %s to new value %s",
newPvc.Namespace, newPvc.Name, val, pvToBackingDiskObjectIdPair)
metav1.SetMetaDataAnnotation(&newPvc.ObjectMeta, annPVtoBackingDiskObjectId, pvToBackingDiskObjectIdPair)
_, err = k8sclient.CoreV1().PersistentVolumeClaims(newPvc.Namespace).Update(ctx,
newPvc, metav1.UpdateOptions{})
if err != nil {
log.Errorf("updatePVtoBackingDiskObjectIdMappingStatus: Failed to update pvc %s/%s with err:%+v",
newPvc.Namespace, newPvc.Name, err)
return false, err
} else {
return true, nil
}
} else {
log.Errorf("updatePVtoBackingDiskObjectIdMappingStatus: pv to backingdiskobjectid annotation for "+
"pvc %s/%s is not updated because failed to get pvc from API server. err=%+v",
pvc.Namespace, pvc.Name, err)
return false, err
}
}
log.Debug("updatePVtoBackingDiskObjectIdMappingStatus: annotation on pvc updated")
return true, nil
}
log.Debug("updatePVtoBackingDiskObjectIdMappingStatus: no change to annotation on pvc, skip update")
return false, nil
}