-
Notifications
You must be signed in to change notification settings - Fork 88
/
restore.go
240 lines (199 loc) · 7.61 KB
/
restore.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
package snapshot
import (
"context"
"fmt"
"math"
"strings"
"time"
units "github.com/docker/go-units"
"github.com/pkg/errors"
"github.com/replicatedhq/kots/pkg/k8sutil"
"github.com/replicatedhq/kots/pkg/kotsadmsnapshot/types"
"github.com/replicatedhq/kots/pkg/logger"
kotssnapshot "github.com/replicatedhq/kots/pkg/snapshot"
velerov1 "github.com/vmware-tanzu/velero/pkg/apis/velero/v1"
veleroclientv1 "github.com/vmware-tanzu/velero/pkg/generated/clientset/versioned/typed/velero/v1"
velerolabel "github.com/vmware-tanzu/velero/pkg/label"
"go.uber.org/zap"
kuberneteserrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func GetRestore(ctx context.Context, kotsadmNamespace string, snapshotName string) (*velerov1.Restore, error) {
bsl, err := kotssnapshot.FindBackupStoreLocation(ctx, kotsadmNamespace)
if err != nil {
return nil, errors.Wrap(err, "failed to get velero namespace")
}
veleroNamespace := bsl.Namespace
cfg, err := k8sutil.GetClusterConfig()
if err != nil {
return nil, errors.Wrap(err, "failed to get cluster config")
}
veleroClient, err := veleroclientv1.NewForConfig(cfg)
if err != nil {
return nil, errors.Wrap(err, "failed to create clientset")
}
restore, err := veleroClient.Restores(veleroNamespace).Get(ctx, snapshotName, metav1.GetOptions{})
if err != nil {
if kuberneteserrors.IsNotFound(err) {
return nil, nil
}
return nil, errors.Wrap(err, "failed to get restore")
}
return restore, nil
}
func CreateApplicationRestore(ctx context.Context, kotsadmNamespace string, snapshotName string, appSlug string) error {
// Reference https://github.com/vmware-tanzu/velero/blob/42b612645863c2b3e451b447f9bf798295dd7dba/pkg/cmd/cli/restore/create.go#L222
logger.Debug("creating restore",
zap.String("snapshotName", snapshotName))
bsl, err := kotssnapshot.FindBackupStoreLocation(ctx, kotsadmNamespace)
if err != nil {
return errors.Wrap(err, "failed to get velero namespace")
}
veleroNamespace := bsl.Namespace
// get the backup
cfg, err := k8sutil.GetClusterConfig()
if err != nil {
return errors.Wrap(err, "failed to get cluster config")
}
veleroClient, err := veleroclientv1.NewForConfig(cfg)
if err != nil {
return errors.Wrap(err, "failed to create clientset")
}
backup, err := veleroClient.Backups(veleroNamespace).Get(ctx, snapshotName, metav1.GetOptions{})
if err != nil {
return errors.Wrap(err, "failed to find backup")
}
trueVal := true
restore := &velerov1.Restore{
ObjectMeta: metav1.ObjectMeta{
Namespace: veleroNamespace,
Name: snapshotName, // restore name same as snapshot name
},
Spec: velerov1.RestoreSpec{
BackupName: snapshotName,
RestorePVs: &trueVal,
IncludeClusterResources: &trueVal,
},
}
if backup.Annotations["kots.io/instance"] == "true" {
// only restore app-specific objects
restore.ObjectMeta.Name = fmt.Sprintf("%s.%s", snapshotName, appSlug)
restore.ObjectMeta.Annotations = map[string]string{
"kots.io/instance": "true",
}
restore.Spec.LabelSelector = &metav1.LabelSelector{
MatchLabels: map[string]string{
"kots.io/app-slug": appSlug,
},
}
}
_, err = veleroClient.Restores(veleroNamespace).Create(ctx, restore, metav1.CreateOptions{})
if err != nil {
return errors.Wrap(err, "failed to create restore")
}
return nil
}
func DeleteRestore(ctx context.Context, kotsadmNamespace string, snapshotName string) error {
bsl, err := kotssnapshot.FindBackupStoreLocation(ctx, kotsadmNamespace)
if err != nil {
return errors.Wrap(err, "failed to get velero namespace")
}
veleroNamespace := bsl.Namespace
cfg, err := k8sutil.GetClusterConfig()
if err != nil {
return errors.Wrap(err, "failed to get cluster config")
}
veleroClient, err := veleroclientv1.NewForConfig(cfg)
if err != nil {
return errors.Wrap(err, "failed to create clientset")
}
err = veleroClient.Restores(veleroNamespace).Delete(ctx, snapshotName, metav1.DeleteOptions{})
if err != nil && !strings.Contains(err.Error(), "not found") {
return errors.Wrapf(err, "failed to delete restore %s", snapshotName)
}
return nil
}
func GetRestoreDetails(ctx context.Context, kotsadmNamespace string, restoreName string) (*types.RestoreDetail, error) {
cfg, err := k8sutil.GetClusterConfig()
if err != nil {
return nil, errors.Wrap(err, "failed to get cluster config")
}
veleroClient, err := veleroclientv1.NewForConfig(cfg)
if err != nil {
return nil, errors.Wrap(err, "failed to create clientset")
}
backendStorageLocation, err := kotssnapshot.FindBackupStoreLocation(ctx, kotsadmNamespace)
if err != nil {
return nil, errors.Wrap(err, "failed to find backupstoragelocations")
}
veleroNamespace := backendStorageLocation.Namespace
restore, err := veleroClient.Restores(veleroNamespace).Get(ctx, restoreName, metav1.GetOptions{})
if err != nil {
return nil, errors.Wrap(err, "failed to get restore")
}
restoreVolumes, err := veleroClient.PodVolumeRestores(veleroNamespace).List(ctx, metav1.ListOptions{
LabelSelector: fmt.Sprintf("velero.io/restore-name=%s", velerolabel.GetValidName(restore.Name)),
})
if err != nil {
return nil, errors.Wrap(err, "failed to list volumes")
}
result := &types.RestoreDetail{
Name: restore.Name,
Phase: restore.Status.Phase,
Volumes: listRestoreVolumes(restoreVolumes.Items),
Errors: make([]types.SnapshotError, 0),
Warnings: make([]types.SnapshotError, 0),
}
if restore.Status.Phase == velerov1.RestorePhaseCompleted || restore.Status.Phase == velerov1.RestorePhasePartiallyFailed || restore.Status.Phase == velerov1.RestorePhaseFailed {
warnings, errs, err := DownloadRestoreResults(ctx, veleroNamespace, restore.Name)
if err != nil {
// do not fail on error
logger.Error(errors.Wrap(err, "failed to download restore results"))
}
result.Errors = errs
filtered, err := filterWarnings(restore, warnings, &filterGetter{})
if err != nil {
logger.Infof("failed to filter warnings: %v", err)
result.Warnings = warnings
} else {
result.Warnings = filtered
}
}
return result, nil
}
func listRestoreVolumes(restoreVolumes []velerov1.PodVolumeRestore) []types.RestoreVolume {
volumes := []types.RestoreVolume{}
for _, restoreVolume := range restoreVolumes {
v := types.RestoreVolume{
Name: restoreVolume.Name,
PodName: restoreVolume.Spec.Pod.Name,
PodNamespace: restoreVolume.Spec.Pod.Namespace,
PodVolumeName: restoreVolume.Spec.Volume,
SizeBytesHuman: units.HumanSize(float64(restoreVolume.Status.Progress.TotalBytes)),
DoneBytesHuman: units.HumanSize(float64(restoreVolume.Status.Progress.BytesDone)),
Phase: string(restoreVolume.Status.Phase),
}
if restoreVolume.Status.Progress.TotalBytes > 0 {
v.CompletionPercent = int(math.Round(float64(restoreVolume.Status.Progress.BytesDone/restoreVolume.Status.Progress.TotalBytes) * 100))
}
if restoreVolume.Status.StartTimestamp != nil {
v.StartedAt = &restoreVolume.Status.StartTimestamp.Time
if restoreVolume.Status.Progress.TotalBytes > 0 {
if restoreVolume.Status.Progress.BytesDone > 0 {
bytesPerSecond := float64(restoreVolume.Status.Progress.BytesDone) / time.Now().Sub(*v.StartedAt).Seconds()
bytesRemaining := float64(restoreVolume.Status.Progress.TotalBytes - restoreVolume.Status.Progress.BytesDone)
v.RemainingSecondsExist = true
v.TimeRemainingSeconds = int(math.Round(bytesRemaining / bytesPerSecond))
} else {
v.RemainingSecondsExist = false
v.TimeRemainingSeconds = 0
}
}
}
if restoreVolume.Status.CompletionTimestamp != nil {
v.FinishedAt = &restoreVolume.Status.CompletionTimestamp.Time
}
volumes = append(volumes, v)
}
return volumes
}