/
volume_snapshotter.go
478 lines (408 loc) · 14.1 KB
/
volume_snapshotter.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
466
467
468
469
470
471
472
473
474
475
476
477
478
/*
Copyright 2017, 2019 the Velero contributors.
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"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"regexp"
"strings"
uuid "github.com/gofrs/uuid"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/oauth2/google"
"google.golang.org/api/compute/v1"
"google.golang.org/api/googleapi"
"google.golang.org/api/option"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
veleroplugin "github.com/vmware-tanzu/velero/pkg/plugin/framework"
)
const (
zoneSeparator = "__"
projectKey = "project"
snapshotLocationKey = "snapshotLocation"
volumeProjectKey = "volumeProject"
)
var pdCSIDriver = map[string]bool{
"pd.csi.storage.gke.io": true,
"gcp.csi.confidential.cloud": true,
}
var pdVolRegexp = regexp.MustCompile(`^projects\/[^\/]+\/(zones|regions)\/[^\/]+\/disks\/[^\/]+$`)
type VolumeSnapshotter struct {
log logrus.FieldLogger
gce *compute.Service
snapshotLocation string
volumeProject string
snapshotProject string
}
func newVolumeSnapshotter(logger logrus.FieldLogger) *VolumeSnapshotter {
return &VolumeSnapshotter{log: logger}
}
func (b *VolumeSnapshotter) Init(config map[string]string) error {
if err := veleroplugin.ValidateVolumeSnapshotterConfigKeys(config,
snapshotLocationKey, projectKey, credentialsFileConfigKey, volumeProjectKey); err != nil {
return err
}
clientOptions := []option.ClientOption{
option.WithScopes(compute.ComputeScope),
}
// Credentials used to connect to GCP compute service.
var creds *google.Credentials
var err error
// If credential is provided for the VSL, use it instead of default credential.
if credentialsFile, ok := config[credentialsFileConfigKey]; ok {
b, err := ioutil.ReadFile(credentialsFile)
if err != nil {
return errors.Wrapf(err, "error reading provided credentials file %v", credentialsFile)
}
creds, err = google.CredentialsFromJSON(context.TODO(), b)
if err != nil {
return errors.WithStack(err)
}
// If using a credentials file, we also need to pass it when creating the client.
clientOptions = append(clientOptions, option.WithCredentialsFile(credentialsFile))
} else {
/* Use default credential, when no credential is provisioned in VSL. */
creds, err = google.FindDefaultCredentials(context.TODO(), compute.ComputeScope)
if err != nil {
return errors.WithStack(err)
}
clientOptions = append(clientOptions, option.WithTokenSource(creds.TokenSource))
}
b.snapshotLocation = config[snapshotLocationKey]
b.volumeProject = config[volumeProjectKey]
if b.volumeProject == "" {
b.volumeProject = creds.ProjectID
}
// get snapshot project from 'project' config key if specified,
// otherwise from the credentials file
b.snapshotProject = config[projectKey]
if b.snapshotProject == "" {
b.snapshotProject = b.volumeProject
}
gce, err := compute.NewService(context.TODO(), clientOptions...)
if err != nil {
return errors.WithStack(err)
}
b.gce = gce
return nil
}
// isMultiZone returns true if the failure-domain tag contains
// double underscore, which is the separator used
// by GKE when a storage class spans multiple availability
// zones.
func isMultiZone(volumeAZ string) bool {
return strings.Contains(volumeAZ, zoneSeparator)
}
// parseRegion parses a failure-domain tag with multiple zones
// and returns a single region. Zones are separated by double underscores (__).
// For example
//
// input: us-central1-a__us-central1-b
// return: us-central1
//
// When a custom storage class spans multiple geographical zones,
// such as us-central1 and us-west1 only the zone matching the cluster is used
// in the failure-domain tag.
// For example
//
// Cluster nodes in us-central1-c, us-central1-f
// Storage class zones us-central1-a, us-central1-f, us-east1-a, us-east1-d
// The failure-domain tag would be: us-central1-a__us-central1-f
func parseRegion(volumeAZ string) (string, error) {
zones := strings.Split(volumeAZ, zoneSeparator)
zone := zones[0]
parts := strings.SplitAfterN(zone, "-", 3)
if len(parts) < 2 {
return "", errors.Errorf("failed to parse region from zone: %q", volumeAZ)
}
return parts[0] + strings.TrimSuffix(parts[1], "-"), nil
}
// Retrieve the URLs for zones via the GCP API.
func (b *VolumeSnapshotter) getZoneURLs(volumeAZ string) ([]string, error) {
zones := strings.Split(volumeAZ, zoneSeparator)
var zoneURLs []string
for _, z := range zones {
zone, err := b.gce.Zones.Get(b.volumeProject, z).Do()
if err != nil {
return nil, errors.WithStack(err)
}
zoneURLs = append(zoneURLs, zone.SelfLink)
}
return zoneURLs, nil
}
func (b *VolumeSnapshotter) CreateVolumeFromSnapshot(snapshotID, volumeType, volumeAZ string, iops *int64) (volumeID string, err error) {
// get the snapshot so we can apply its tags to the volume
res, err := b.gce.Snapshots.Get(b.snapshotProject, snapshotID).Do()
if err != nil {
return "", errors.WithStack(err)
}
// Kubernetes uses the description field of GCP disks to store a JSON doc containing
// tags.
//
// use the snapshot's description (which contains tags from the snapshotted disk
// plus Velero-specific tags) to set the new disk's description.
uid, err := uuid.NewV4()
if err != nil {
return "", errors.WithStack(err)
}
disk := &compute.Disk{
Name: "restore-" + uid.String(),
SourceSnapshot: res.SelfLink,
Type: volumeType,
Description: res.Description,
}
if isMultiZone(volumeAZ) {
volumeRegion, err := parseRegion(volumeAZ)
if err != nil {
return "", err
}
// URLs for zones that the volume is replicated to within GCP
zoneURLs, err := b.getZoneURLs(volumeAZ)
if err != nil {
return "", err
}
disk.ReplicaZones = zoneURLs
if _, err = b.gce.RegionDisks.Insert(b.volumeProject, volumeRegion, disk).Do(); err != nil {
return "", errors.WithStack(err)
}
} else {
if _, err = b.gce.Disks.Insert(b.volumeProject, volumeAZ, disk).Do(); err != nil {
return "", errors.WithStack(err)
}
}
return disk.Name, nil
}
func (b *VolumeSnapshotter) GetVolumeInfo(volumeID, volumeAZ string) (string, *int64, error) {
var (
res *compute.Disk
err error
)
if isMultiZone(volumeAZ) {
volumeRegion, err := parseRegion(volumeAZ)
if err != nil {
return "", nil, errors.WithStack(err)
}
res, err = b.gce.RegionDisks.Get(b.volumeProject, volumeRegion, volumeID).Do()
if err != nil {
return "", nil, errors.WithStack(err)
}
} else {
res, err = b.gce.Disks.Get(b.volumeProject, volumeAZ, volumeID).Do()
if err != nil {
return "", nil, errors.WithStack(err)
}
}
return res.Type, nil, nil
}
func (b *VolumeSnapshotter) CreateSnapshot(volumeID, volumeAZ string, tags map[string]string) (string, error) {
// snapshot names must adhere to RFC1035 and be 1-63 characters
// long
var snapshotName string
uid, err := uuid.NewV4()
if err != nil {
return "", errors.WithStack(err)
}
suffix := "-" + uid.String()
// List all project quotas and check the "SNAPSHOTS" quota.
// If the limit is reached, return an error, so that snapshot
// won't get created.
p, err := b.gce.Projects.Get(b.volumeProject).Do()
if err != nil {
return "", errors.WithStack(err)
}
for _, quota := range p.Quotas {
if quota.Metric == "SNAPSHOTS" {
if quota.Usage == quota.Limit {
err := fmt.Errorf("snapshots quota on Google Cloud Platform has been reached")
return "", errors.WithStack(err)
}
break
}
}
if len(volumeID) <= (63 - len(suffix)) {
snapshotName = volumeID + suffix
} else {
snapshotName = volumeID[0:63-len(suffix)] + suffix
}
if isMultiZone(volumeAZ) {
volumeRegion, err := parseRegion(volumeAZ)
if err != nil {
return "", errors.WithStack(err)
}
return b.createRegionSnapshot(snapshotName, volumeID, volumeRegion, tags)
} else {
return b.createSnapshot(snapshotName, volumeID, volumeAZ, tags)
}
}
func (b *VolumeSnapshotter) createSnapshot(snapshotName, volumeID, volumeAZ string, tags map[string]string) (string, error) {
disk, err := b.gce.Disks.Get(b.volumeProject, volumeAZ, volumeID).Do()
if err != nil {
return "", errors.WithStack(err)
}
gceSnap := compute.Snapshot{
Name: snapshotName,
Description: getSnapshotTags(tags, disk.Description, b.log),
SourceDisk: disk.SelfLink,
}
if b.snapshotLocation != "" {
gceSnap.StorageLocations = []string{b.snapshotLocation}
}
_, err = b.gce.Snapshots.Insert(b.snapshotProject, &gceSnap).Do()
if err != nil {
return "", errors.WithStack(err)
}
return gceSnap.Name, nil
}
func (b *VolumeSnapshotter) createRegionSnapshot(snapshotName, volumeID, volumeRegion string, tags map[string]string) (string, error) {
disk, err := b.gce.RegionDisks.Get(b.volumeProject, volumeRegion, volumeID).Do()
if err != nil {
return "", errors.WithStack(err)
}
gceSnap := compute.Snapshot{
Name: snapshotName,
Description: getSnapshotTags(tags, disk.Description, b.log),
SourceDisk: disk.SelfLink,
}
if b.snapshotLocation != "" {
gceSnap.StorageLocations = []string{b.snapshotLocation}
}
_, err = b.gce.Snapshots.Insert(b.snapshotProject, &gceSnap).Do()
if err != nil {
return "", errors.WithStack(err)
}
return gceSnap.Name, nil
}
func getSnapshotTags(veleroTags map[string]string, diskDescription string, log logrus.FieldLogger) string {
// Kubernetes uses the description field of GCP disks to store a JSON doc containing
// tags.
//
// use the tags in the disk's description (if a valid JSON doc) plus the tags arg
// to set the snapshot's description.
var snapshotTags map[string]string
if diskDescription != "" {
if err := json.Unmarshal([]byte(diskDescription), &snapshotTags); err != nil {
// error decoding the disk's description, so just use the Velero-assigned tags
log.WithField("error", err.Error()).Warning("unable to decode disk's description as JSON, so only applying Velero-assigned tags to snapshot")
snapshotTags = veleroTags
} else {
// merge Velero-assigned tags with the disk's tags (note that we want current
// Velero-assigned tags to overwrite any older versions of them that may exist
// due to prior snapshots/restores)
for k, v := range veleroTags {
snapshotTags[k] = v
}
}
} else {
// no disk description provided, assign velero tags
snapshotTags = veleroTags
}
if len(snapshotTags) == 0 {
return ""
}
tagsJSON, err := json.Marshal(snapshotTags)
if err != nil {
log.WithError(err).Error("unable to encode snapshot's tags to JSON, so not tagging snapshot")
return ""
}
return string(tagsJSON)
}
func (b *VolumeSnapshotter) DeleteSnapshot(snapshotID string) error {
_, err := b.gce.Snapshots.Delete(b.snapshotProject, snapshotID).Do()
// if it's a 404 (not found) error, we don't need to return an error
// since the snapshot is not there.
if gcpErr, ok := err.(*googleapi.Error); ok && gcpErr.Code == http.StatusNotFound {
return nil
}
if err != nil {
return errors.WithStack(err)
}
return nil
}
func (b *VolumeSnapshotter) GetVolumeID(unstructuredPV runtime.Unstructured) (string, error) {
pv := new(v1.PersistentVolume)
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(unstructuredPV.UnstructuredContent(), pv); err != nil {
return "", errors.WithStack(err)
}
if pv.Spec.CSI != nil {
driver := pv.Spec.CSI.Driver
if pdCSIDriver[driver] {
handle := pv.Spec.CSI.VolumeHandle
if !pdVolRegexp.MatchString(handle) {
return "", fmt.Errorf("invalid volumeHandle for CSI driver:%s, expected projects/{project}/zones/{zone}/disks/{name}, got %s",
driver, handle)
}
l := strings.Split(handle, "/")
return l[len(l)-1], nil
}
b.log.Infof("Unable to handle CSI driver: %s", driver)
}
if pv.Spec.GCEPersistentDisk != nil {
if pv.Spec.GCEPersistentDisk.PDName == "" {
return "", errors.New("spec.gcePersistentDisk.pdName not found")
}
return pv.Spec.GCEPersistentDisk.PDName, nil
}
return "", nil
}
func (b *VolumeSnapshotter) SetVolumeID(unstructuredPV runtime.Unstructured, volumeID string) (runtime.Unstructured, error) {
pv := new(v1.PersistentVolume)
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(unstructuredPV.UnstructuredContent(), pv); err != nil {
return nil, errors.WithStack(err)
}
if pv.Spec.CSI != nil {
// PV is provisioned by CSI driver
driver := pv.Spec.CSI.Driver
if pdCSIDriver[driver] {
handle := pv.Spec.CSI.VolumeHandle
// To restore in the same AZ, here we only replace the 'disk' chunk.
if !pdVolRegexp.MatchString(handle) {
return nil, fmt.Errorf("invalid volumeHandle for restore with CSI driver:%s, expected projects/{project}/zones/{zone}/disks/{name}, got %s",
driver, handle)
}
if b.IsVolumeCreatedCrossProjects(handle) == true {
projectRE := regexp.MustCompile(`projects\/[^\/]+\/`)
handle = projectRE.ReplaceAllString(handle, "projects/"+b.volumeProject+"/")
}
pv.Spec.CSI.VolumeHandle = handle[:strings.LastIndex(handle, "/")+1] + volumeID
} else {
return nil, fmt.Errorf("unable to handle CSI driver: %s", driver)
}
} else if pv.Spec.GCEPersistentDisk != nil {
// PV is provisioned by in-tree driver
pv.Spec.GCEPersistentDisk.PDName = volumeID
} else {
return nil, errors.New("spec.csi and spec.gcePersistentDisk not found")
}
res, err := runtime.DefaultUnstructuredConverter.ToUnstructured(pv)
if err != nil {
return nil, errors.WithStack(err)
}
return &unstructured.Unstructured{Object: res}, nil
}
func (b *VolumeSnapshotter) IsVolumeCreatedCrossProjects(volumeHandle string) bool {
// Get project ID from volume handle
parsedStr := strings.Split(volumeHandle, "/")
if len(parsedStr) < 2 {
return false
}
projectID := parsedStr[1]
if projectID != b.volumeProject {
return true
}
return false
}