/
volumegroup.go
465 lines (424 loc) · 15.8 KB
/
volumegroup.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
/*
Copyright 2021 The OpenYurt 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 volumegroup
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/openyurtio/node-resource-manager/pkg/config"
CusErr "github.com/openyurtio/node-resource-manager/pkg/err"
"github.com/openyurtio/node-resource-manager/pkg/utils"
yaml "gopkg.in/yaml.v2"
v1 "k8s.io/api/core/v1"
"k8s.io/client-go/tools/record"
klog "k8s.io/klog/v2"
)
const (
StorageCmNameSpace = "kube-system"
StorageCmName = "cm-node-resource"
VGConfigKey = "volumegroup.json"
AliyunLocalDisk = "aliyun-local-disk"
VgConfigFile = "/etc/unified-config/volumegroup"
VgTypeDevice = "device"
VgTypePvc = "pvc"
VgTypeLocal = "alibabacloud-local-disk"
VgTypePmem = "pmem"
)
// ResourceManager ...
type ResourceManager struct {
volumeGroupDeviceMap map[string]*VgDeviceConfig
volumeGroupRegionMap map[string][]string
mounter utils.Mounter
pmemer utils.Pmemer
lvmer utils.LVM
configPath string
recorder record.EventRecorder
}
// NewResourceManager ...
func NewResourceManager() *ResourceManager {
return &ResourceManager{
volumeGroupDeviceMap: make(map[string]*VgDeviceConfig),
volumeGroupRegionMap: make(map[string][]string),
pmemer: utils.NewNodePmemer(),
mounter: utils.NewMounter(),
lvmer: utils.NewNodeLVM(),
configPath: "/etc/unified-config/volumegroup",
recorder: utils.NewEventRecorder(),
}
}
// DeviceChars ...
var DeviceChars = []string{"b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
// Create VolumeGroup
func (vrm *ResourceManager) createVg(vgName string, desirePvList []string) error {
pvListStr := strings.Join(desirePvList, " ")
tagList := []string{}
out, err := vrm.lvmer.CreateVG(vgName, pvListStr, tagList)
if err != nil {
klog.Errorf("createVg:: Create Vg(%s) error with: %s", vgName, err.Error())
return err
}
klog.Infof("createVg:: Successful Create Vg(%s) with out: %s", vgName, out)
return nil
}
// Upgrade VolumeGroup, only support extend pv;
func (vrm *ResourceManager) updateVg(vgName string, expectPvList, realPvList []string) error {
if len(expectPvList) < len(realPvList) {
msg := fmt.Sprintf("updateVg:: VolumeGroup: %s, expected pv list should be more than current pv list when update volume group: %v, %v", vgName, expectPvList, realPvList)
klog.Errorf(msg)
return errors.New(msg)
}
// removed pv: pv exist in current node, but not in expect
removePv := difference(realPvList, expectPvList)
if len(removePv) > 0 {
msg := fmt.Sprintf("updateVg:: VolumeGroup: %s, expected pv list should be more than current pv list when update volume group: expect %v, current %v, and not support remove pv now", vgName, expectPvList, realPvList)
klog.Errorf(msg)
return errors.New(msg)
}
// added pv: pv exist in expect, but not in current node.
addedPv := difference(expectPvList, realPvList)
if len(addedPv) == 0 {
msg := fmt.Sprintf("updateVg:: VolumeGroup: %s, expected pv list same with current pv list, expect %v, current %v", vgName, expectPvList, realPvList)
klog.Errorf(msg)
return errors.New(msg)
}
pvListStr := strings.Join(addedPv, " ")
_, err := vrm.lvmer.ExtendVG(vgName, pvListStr)
if err != nil {
msg := fmt.Sprintf("updateVg:: Extend vg(%s) error: %v", vgName, err)
klog.Errorf(msg)
return errors.New(msg)
}
klog.Infof("updateVg:: Successful Add pvs %s to VolumeGroup %s", addedPv, vgName)
return nil
}
// difference returns the elements in `a` that aren't in `b`.
func difference(a, b []string) []string {
mb := make(map[string]struct{}, len(b))
for _, x := range b {
mb[x] = struct{}{}
}
var diff []string
for _, x := range a {
if _, found := mb[x]; !found {
diff = append(diff, x)
}
}
return diff
}
func getPvListForLocalDisk(mounter utils.Mounter) []string {
// Step 2: Get LocalDisk Number
localDeviceList := []string{}
localDeviceNum, err := getLocalDeviceNum()
if err != nil {
klog.Errorf("getPvListForLocalDisk:: LocalDiskMount:: Get Local Disk Number Error, Error: %s", err.Error())
return localDeviceList
}
if localDeviceNum < 1 {
klog.Errorf("getPvListForLocalDisk:: VG not exist and also not local disk exist, localDeivceNum: %v", localDeviceNum)
return localDeviceList
}
// Step 3: Get LocalDisk device
deviceStartWith := "vdb"
deviceNamePrefix := "vd"
deviceStartIndex := 0
deviceNameLen := len(deviceStartWith)
if deviceNameLen > 1 {
deviceStartChar := deviceStartWith[deviceNameLen-1 : deviceNameLen]
for index := 0; index < 15; index++ {
if deviceStartChar == DeviceChars[index] {
deviceStartIndex = index
}
}
deviceNamePrefix = deviceStartWith[0 : deviceNameLen-1]
}
if mounter.FileExists(deviceNamePrefix + DeviceChars[deviceStartIndex]) {
for i := deviceStartIndex; i < localDeviceNum; i++ {
deviceName := deviceNamePrefix + DeviceChars[i]
devicePath := filepath.Join("/dev", deviceName)
localDeviceList = append(localDeviceList, devicePath)
}
}
// nvmeDevicePattern := "nvme%vn1"
// nvmeStartIndex := 0
// if mounter.FileExists(fmt.Sprintf(nvmeDevicePattern, nvmeStartIndex)) {
// for i :=nvmeStartIndex; i < localDeviceNum; i++ {
// devicePath := filepath.Join("/dev", fmt.Sprintf(nvmeDevicePattern, i))
// localDeviceList = append(localDeviceList, devicePath)
// }
// }
klog.V(3).Infof("getPvListForLocalDisk:: Starting LocalDisk Mount: LocalDisk Number: %d, LocalDisk: %v", localDeviceNum, localDeviceList)
return localDeviceList
}
// Get Local Disk Number from ecs API
// Requirements: The instance must have role which contains ecs::DescribeInstances, ecs::DescribeInstancesType.
func getLocalDeviceNum() (int, error) {
instanceID := GetMetaData(InstanceID)
regionID := GetMetaData(RegionIDTag)
localDeviceNum := 0
akID, akSecret, token := GetDefaultAK()
client := NewEcsClient(regionID, akID, akSecret, token)
// Get Instance Type
request := ecs.CreateDescribeInstancesRequest()
request.RegionId = regionID
request.InstanceIds = "[\"" + instanceID + "\"]"
instanceResponse, err := client.DescribeInstances(request)
if err != nil {
klog.Errorf("getLocalDeviceNum:: Describe Instance: %s Error: %s", instanceID, err.Error())
return -1, err
}
if instanceResponse == nil || len(instanceResponse.Instances.Instance) == 0 {
klog.Infof("getLocalDeviceNum:: Describe Instance Error, with empty response: %s", instanceID)
return -1, err
}
// Get Instance LocalDisk Number
instanceTypeID := instanceResponse.Instances.Instance[0].InstanceType
instanceTypeFamily := instanceResponse.Instances.Instance[0].InstanceTypeFamily
instanceTypeRequest := ecs.CreateDescribeInstanceTypesRequest()
instanceTypeRequest.InstanceTypeFamily = instanceTypeFamily
response, err := client.DescribeInstanceTypes(instanceTypeRequest)
if err != nil {
klog.Errorf("getLocalDeviceNum:: Describe Instance: %s, Type: %s, Family: %s Error: %s", instanceID, instanceTypeID, instanceTypeFamily, err.Error())
return -1, err
}
for _, instance := range response.InstanceTypes.InstanceType {
if instance.InstanceTypeId == instanceTypeID {
localDeviceNum = instance.LocalStorageAmount
klog.Infof("getLocalDeviceNum:: Instance: %s, InstanceType: %s, InstanceLocalDiskNum: %d", instanceID, instanceTypeID, localDeviceNum)
break
}
}
return localDeviceNum, nil
}
// Get current VolumeGroup in node
// echo vgOjbect contains: vgName, pvList;
func (vrm *ResourceManager) getRealVgList() ([]*VgDeviceConfig, error) {
physicalVolumeList, err := vrm.lvmer.ListPhysicalVolume()
if err != nil {
klog.Errorf("List PhysicalVolume get error %v", err)
return nil, err
}
klog.V(3).Infof("Real VolumeGroup List: %+v", physicalVolumeList)
nodeVgList := []*VgDeviceConfig{}
for _, physicalVolume := range physicalVolumeList {
isAlreadyAdded := false
for _, nodeVg := range nodeVgList {
if nodeVg.Name == physicalVolume.VgName {
nodeVg.PhysicalVolumes = append(nodeVg.PhysicalVolumes, physicalVolume.Name)
isAlreadyAdded = true
klog.V(3).Infof("getRealVgList:: physicalVolumes: %v, physicalVolumeName: %s, volumeGroupName: %v", nodeVg.PhysicalVolumes, physicalVolume.Name, physicalVolume.VgName)
}
}
if isAlreadyAdded == false {
vgPvConfig := &VgDeviceConfig{}
vgPvConfig.Name = physicalVolume.VgName
vgPvConfig.PhysicalVolumes = append(vgPvConfig.PhysicalVolumes, physicalVolume.Name)
nodeVgList = append(nodeVgList, vgPvConfig)
klog.V(3).Infof("Add New VolumeGroupPvConfig: %s, %s, %v", physicalVolume.Name, physicalVolume.VgName, vgPvConfig)
}
}
return nodeVgList, nil
}
// AnalyseConfigMap analyse pmem resource config
func (vrm *ResourceManager) AnalyseConfigMap() error {
ref := &v1.ObjectReference{
Kind: "pods",
Name: os.Getenv("POD_NAME"),
Namespace: "kube-system",
}
getExistDevices := func(storages []string) (exists []string) {
for _, device := range storages {
cerr := &CusErr.DeviceNotExistsErr{Device: device}
if !vrm.mounter.FileExists(device) {
vrm.recorder.Event(ref, v1.EventTypeNormal, "DeviceNotExists", cerr.Error())
} else {
exists = append(exists, device)
}
}
return
}
vgDeviceMap := map[string]*VgDeviceConfig{}
vgRegionMap := map[string][]string{}
volumeGroupList := &VgList{}
yamlFile, err := ioutil.ReadFile(vrm.configPath)
if err != nil {
if os.IsNotExist(err) {
klog.Errorf("volume config file %s not exist", vrm.configPath)
return nil
}
klog.Errorf("AnalyseConfigMap:: ReadFile: yamlFile.Get error #%v ", err)
return err
}
err = yaml.Unmarshal(yamlFile, volumeGroupList)
if err != nil {
klog.Errorf("AnalyseConfigMap:: Unmarshal: parse yaml file error: %v", err)
return err
}
nodeInfo := config.GlobalConfigVar.NodeInfo
for _, devConfig := range volumeGroupList.VolumeGroups {
vgDeviceConfig := &VgDeviceConfig{}
isMatched := utils.NodeFilter(devConfig.Operator, devConfig.Key, devConfig.Value, nodeInfo)
klog.V(3).Infof("AnalyseConfigMap:: isMatched: %v, devConfig: %+v", isMatched, devConfig)
if isMatched {
switch devConfig.Topology.Type {
case VgTypeDevice:
vgDeviceConfig.PhysicalVolumes = getExistDevices(devConfig.Topology.Devices)
vgDeviceMap[devConfig.Name] = vgDeviceConfig
case VgTypeLocal:
tmpConfig := &VgDeviceConfig{}
tmpConfig.PhysicalVolumes = getPvListForLocalDisk(vrm.mounter)
vgDeviceMap[devConfig.Name] = tmpConfig
case VgTypePvc:
// not support yet
continue
case VgTypePmem:
vgRegionMap[devConfig.Name] = devConfig.Topology.Regions
default:
klog.Errorf("AnalyseConfigMap:: Get unsupported volumegroup type: %s", devConfig.Topology.Type)
continue
}
}
}
vrm.volumeGroupDeviceMap = vgDeviceMap
vrm.volumeGroupRegionMap = vgRegionMap
return nil
}
// ApplyResourceDiff apply volume group resource to current node
func (vrm *ResourceManager) ApplyResourceDiff() error {
// Get Actual VolumeGroup on node.
actualVgConfig, err := vrm.getRealVgList()
if err != nil {
klog.Errorf("ApplyResourceDiff:: Get Node Actual VolumeGroup Error: %s", err.Error())
return err
}
if len(vrm.volumeGroupDeviceMap) > 0 {
vrm.applyDeivce(actualVgConfig)
}
if len(vrm.volumeGroupRegionMap) > 0 {
vrm.applyRegion(actualVgConfig)
}
klog.Infof("ApplyResourceDiff:: Finish volumegroup loop...")
return nil
}
func (vrm *ResourceManager) applyDeivce(actualVgConfig []*VgDeviceConfig) error {
// process each expect volume group
for expectVgName, expectVg := range vrm.volumeGroupDeviceMap {
klog.Infof("applyDevice:: expectName: %s, expectVgDevices: %v", expectVgName, expectVg.PhysicalVolumes)
isVgExist := false
isVgNeedUpdate := false
realPhysicalVolumeList := []string{}
for _, realVg := range actualVgConfig {
if expectVgName == realVg.Name {
isVgExist = true
diffs := difference(expectVg.PhysicalVolumes, realVg.PhysicalVolumes)
if len(diffs) != 0 {
realPhysicalVolumeList = realVg.PhysicalVolumes
isVgNeedUpdate = true
}
break
}
}
if !isVgExist {
klog.Infof("Create VolumeGroup:: %+v, %+v", expectVgName, expectVg.PhysicalVolumes)
return vrm.createVg(expectVgName, expectVg.PhysicalVolumes)
} else if isVgNeedUpdate {
klog.Infof("Update VolumeGroup:: %+v, %+v", expectVgName, expectVg.PhysicalVolumes)
return vrm.updateVg(expectVgName, expectVg.PhysicalVolumes, realPhysicalVolumeList)
}
}
return nil
}
func (vrm *ResourceManager) applyRegion(actualVgConfig []*VgDeviceConfig) error {
regions, err := vrm.pmemer.GetRegions()
if err != nil {
klog.Errorf("applyRegion: get pmem regions error: %v", err)
return err
}
for _, expectRegions := range vrm.volumeGroupRegionMap {
expectNamespaces := []string{}
for _, expectRegion := range expectRegions {
expectRegionExists := false
for _, region := range regions.Regions {
if expectRegion == region.Dev {
expectRegionExists = true
if len(region.Namespaces) == 0 {
vrm.pmemer.CreateNamespace(region.Dev, "lvm")
}
}
}
if !expectRegionExists {
err := fmt.Errorf("applyRegion:: expect region %s not exists", expectRegion)
return err
}
expectNamespaces = append(expectNamespaces, utils.ConvertRegion2Namespace(expectRegion))
}
}
updatedRegions, err := vrm.pmemer.GetRegions()
if err != nil {
klog.Errorf("applyRegion: get pmem regions error: %v", err)
return err
}
for expectVgName, expectRegions := range vrm.volumeGroupRegionMap {
klog.Infof("applyDevice:: expectVgName: %v, expectRegions: %v", expectVgName, expectRegions)
expectLvmInUseDevices := []string{}
expectLvmNotInUseDevices := []string{}
for _, expectRegion := range expectRegions {
devicePath := utils.ConvertNamespace2LVMDevicePath(utils.ConvertRegion2Namespace(expectRegion), updatedRegions)
if devicePath == "" {
klog.Errorf("applyRegion:: did not get namespace.Blockdev from expectRegion: %s, regions: %v", expectRegion, updatedRegions)
}
if vrm.pmemer.CheckNamespaceUsed(devicePath) {
klog.Errorf("NameSpace heen used region: %v, devicePath: %s", expectRegion, devicePath)
expectLvmInUseDevices = append(expectLvmInUseDevices, devicePath)
}
expectLvmNotInUseDevices = append(expectLvmNotInUseDevices, devicePath)
}
isVgNeedCreate := true
for _, actualVg := range actualVgConfig {
if expectVgName == actualVg.Name {
isVgNeedCreate = false
if otherUsage := difference(expectLvmInUseDevices, actualVg.PhysicalVolumes); len(otherUsage) != 0 {
klog.Errorf("applyRegion:: device [%s] is used in other usage", otherUsage)
break
}
updatePvs := difference(expectLvmNotInUseDevices, actualVg.PhysicalVolumes)
if len(updatePvs) == 0 {
break
}
vrm.updatePmemVg(expectVgName, expectLvmNotInUseDevices)
}
}
if isVgNeedCreate {
if len(expectLvmInUseDevices) != 0 {
klog.Errorf("applyRegion:: attempt to use inused devices [%s] to create volumegroup", expectLvmInUseDevices)
continue
}
vrm.createVg(expectVgName, expectLvmNotInUseDevices)
}
}
return nil
}
func (vrm *ResourceManager) updatePmemVg(vgName string, addedPv []string) error {
pvListStr := strings.Join(addedPv, " ")
_, err := vrm.lvmer.ExtendVG(vgName, pvListStr)
if err != nil {
msg := fmt.Sprintf("updatePmemVg:: Extend vg(%s) error: %v", vgName, err)
klog.Errorf(msg)
return errors.New(msg)
}
klog.Infof("updatePmemVg:: Successful Add pvs %s to VolumeGroup %s", addedPv, vgName)
return nil
}