forked from libopenstorage/stork
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmigrationschedule.go
366 lines (341 loc) · 12 KB
/
migrationschedule.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
package controllers
import (
"context"
"fmt"
"reflect"
"strings"
"time"
"github.com/libopenstorage/stork/drivers/volume"
"github.com/libopenstorage/stork/pkg/apis/stork"
stork_api "github.com/libopenstorage/stork/pkg/apis/stork/v1alpha1"
"github.com/libopenstorage/stork/pkg/controller"
"github.com/libopenstorage/stork/pkg/log"
"github.com/libopenstorage/stork/pkg/schedule"
"github.com/operator-framework/operator-sdk/pkg/sdk"
"github.com/portworx/sched-ops/k8s"
v1 "k8s.io/api/core/v1"
apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
"k8s.io/apimachinery/pkg/api/errors"
meta "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/tools/record"
)
const (
nameTimeSuffixFormat string = "2006-01-02-150405"
domainsRetryInterval = 5 * time.Second
domainsMaxRetries = 5
)
// MigrationScheduleController reconciles MigrationSchedule objects
type MigrationScheduleController struct {
Driver volume.Driver
Recorder record.EventRecorder
}
// Init Initialize the migration schedule controller
func (m *MigrationScheduleController) Init() error {
err := m.createCRD()
if err != nil {
return err
}
return controller.Register(
&schema.GroupVersionKind{
Group: stork.GroupName,
Version: stork_api.SchemeGroupVersion.Version,
Kind: reflect.TypeOf(stork_api.MigrationSchedule{}).Name(),
},
"",
1*time.Minute,
m)
}
// Handle updates for MigrationSchedule objects
func (m *MigrationScheduleController) Handle(ctx context.Context, event sdk.Event) error {
switch o := event.Object.(type) {
case *stork_api.MigrationSchedule:
migrationSchedule := o
// Delete any migrations created by the schedule
if event.Deleted {
return m.deleteMigrations(migrationSchedule)
}
migrationSchedule.Spec.Template.Spec = setDefaults(migrationSchedule.Spec.Template.Spec)
// First update the status of any pending migrations
err := m.updateMigrationStatus(migrationSchedule)
if err != nil {
msg := fmt.Sprintf("Error updating migration status: %v", err)
m.Recorder.Event(migrationSchedule,
v1.EventTypeWarning,
string(stork_api.MigrationStatusFailed),
msg)
log.MigrationScheduleLog(migrationSchedule).Error(msg)
return err
}
// Then check if any of the policies require a trigger if it is enabled
if migrationSchedule.Spec.Suspend == nil || !*migrationSchedule.Spec.Suspend {
var err error
var clusterDomains *stork_api.ClusterDomains
for i := 0; i < domainsMaxRetries; i++ {
clusterDomains, err = m.Driver.GetClusterDomains()
if err == nil {
break
}
time.Sleep(domainsRetryInterval)
}
// Ignore errors
if err == nil {
for _, domainInfo := range clusterDomains.ClusterDomainInfos {
if domainInfo.Name == clusterDomains.LocalDomain &&
domainInfo.State == stork_api.ClusterDomainInactive {
suspend := true
migrationSchedule.Spec.Suspend = &suspend
msg := "Suspending migration schedule since local clusterdomain is inactive"
m.Recorder.Event(migrationSchedule,
v1.EventTypeWarning,
"Suspended",
msg)
log.MigrationScheduleLog(migrationSchedule).Warn(msg)
return sdk.Update(migrationSchedule)
}
}
}
policyType, start, err := m.shouldStartMigration(migrationSchedule)
if err != nil {
msg := fmt.Sprintf("Error checking if migration should be triggered: %v", err)
m.Recorder.Event(migrationSchedule,
v1.EventTypeWarning,
string(stork_api.MigrationStatusFailed),
msg)
log.MigrationScheduleLog(migrationSchedule).Error(msg)
return nil
}
// Start a migration for a policy if required
if start {
err := m.startMigration(migrationSchedule, policyType)
if err != nil {
msg := fmt.Sprintf("Error triggering migration for schedule(%v): %v", policyType, err)
m.Recorder.Event(migrationSchedule,
v1.EventTypeWarning,
string(stork_api.MigrationStatusFailed),
msg)
log.MigrationScheduleLog(migrationSchedule).Error(msg)
return err
}
}
}
// Finally, prune any old migrations that were triggered for this
// schedule
err = m.pruneMigrations(migrationSchedule)
if err != nil {
msg := fmt.Sprintf("Error pruning old migrations: %v", err)
m.Recorder.Event(migrationSchedule,
v1.EventTypeWarning,
string(stork_api.MigrationStatusFailed),
msg)
log.MigrationScheduleLog(migrationSchedule).Error(msg)
return err
}
}
return nil
}
func (m *MigrationScheduleController) updateMigrationStatus(migrationSchedule *stork_api.MigrationSchedule) error {
updated := false
for _, policyMigration := range migrationSchedule.Status.Items {
for _, migration := range policyMigration {
// Get the updated status if we see it as not completed
if !m.isMigrationComplete(migration.Status) {
var updatedStatus stork_api.MigrationStatusType
pendingMigration, err := k8s.Instance().GetMigration(migration.Name, migrationSchedule.Namespace)
if err != nil {
m.Recorder.Event(migrationSchedule,
v1.EventTypeWarning,
string(stork_api.MigrationStatusFailed),
fmt.Sprintf("Error getting status of migration %v: %v", migration.Name, err))
updatedStatus = stork_api.MigrationStatusFailed
} else {
updatedStatus = pendingMigration.Status.Status
}
if updatedStatus == stork_api.MigrationStatusInitial {
updatedStatus = stork_api.MigrationStatusPending
}
// Check again and update the status if it is completed
migration.Status = updatedStatus
if m.isMigrationComplete(migration.Status) {
migration.FinishTimestamp = meta.NewTime(schedule.GetCurrentTime())
if updatedStatus == stork_api.MigrationStatusSuccessful {
m.Recorder.Event(migrationSchedule,
v1.EventTypeNormal,
string(stork_api.MigrationStatusSuccessful),
fmt.Sprintf("Scheduled migration (%v) completed successfully", migration.Name))
} else {
m.Recorder.Event(migrationSchedule,
v1.EventTypeWarning,
string(stork_api.MigrationStatusFailed),
fmt.Sprintf("Scheduled migration (%v) status %v", migration.Name, updatedStatus))
}
}
updated = true
}
}
}
if updated {
err := sdk.Update(migrationSchedule)
if err != nil {
return err
}
}
return nil
}
func (m *MigrationScheduleController) isMigrationComplete(status stork_api.MigrationStatusType) bool {
if status == stork_api.MigrationStatusPending ||
status == stork_api.MigrationStatusCaptured ||
status == stork_api.MigrationStatusInProgress {
return false
}
return true
}
// Returns if a migration should be triggered given the status and times of the
// previous migrations. If a migration should be triggered it also returns the
// type of polivy that should trigger it.
func (m *MigrationScheduleController) shouldStartMigration(
migrationSchedule *stork_api.MigrationSchedule,
) (stork_api.SchedulePolicyType, bool, error) {
// Don't trigger a new migration if one is already in progress
for _, policyType := range stork_api.GetValidSchedulePolicyTypes() {
policyMigration, present := migrationSchedule.Status.Items[policyType]
if present {
for _, migration := range policyMigration {
if !m.isMigrationComplete(migration.Status) {
return stork_api.SchedulePolicyTypeInvalid, false, nil
}
}
}
}
for _, policyType := range stork_api.GetValidSchedulePolicyTypes() {
var latestMigrationTimestamp meta.Time
policyMigration, present := migrationSchedule.Status.Items[policyType]
if present {
for _, migration := range policyMigration {
if latestMigrationTimestamp.Before(&migration.CreationTimestamp) {
latestMigrationTimestamp = migration.CreationTimestamp
}
}
}
trigger, err := schedule.TriggerRequired(
migrationSchedule.Spec.SchedulePolicyName,
policyType,
latestMigrationTimestamp,
)
if err != nil {
return stork_api.SchedulePolicyTypeInvalid, false, err
}
if trigger {
return policyType, true, nil
}
}
return stork_api.SchedulePolicyTypeInvalid, false, nil
}
func (m *MigrationScheduleController) formatMigrationName(
migrationSchedule *stork_api.MigrationSchedule,
policyType stork_api.SchedulePolicyType,
) string {
return strings.Join([]string{migrationSchedule.Name,
strings.ToLower(string(policyType)),
time.Now().Format(nameTimeSuffixFormat)}, "-")
}
func (m *MigrationScheduleController) startMigration(
migrationSchedule *stork_api.MigrationSchedule,
policyType stork_api.SchedulePolicyType,
) error {
migrationName := m.formatMigrationName(migrationSchedule, policyType)
if migrationSchedule.Status.Items == nil {
migrationSchedule.Status.Items = make(map[stork_api.SchedulePolicyType][]*stork_api.ScheduledMigrationStatus)
}
if migrationSchedule.Status.Items[policyType] == nil {
migrationSchedule.Status.Items[policyType] = make([]*stork_api.ScheduledMigrationStatus, 0)
}
migrationSchedule.Status.Items[policyType] = append(migrationSchedule.Status.Items[policyType],
&stork_api.ScheduledMigrationStatus{
Name: migrationName,
CreationTimestamp: meta.NewTime(schedule.GetCurrentTime()),
Status: stork_api.MigrationStatusPending,
})
err := sdk.Update(migrationSchedule)
if err != nil {
return err
}
migration := &stork_api.Migration{
ObjectMeta: meta.ObjectMeta{
Name: migrationName,
Namespace: migrationSchedule.Namespace,
OwnerReferences: []meta.OwnerReference{
{
Name: migrationSchedule.Name,
UID: migrationSchedule.UID,
Kind: migrationSchedule.GetObjectKind().GroupVersionKind().Kind,
APIVersion: migrationSchedule.GetObjectKind().GroupVersionKind().GroupVersion().String(),
},
},
},
Spec: migrationSchedule.Spec.Template.Spec,
}
log.MigrationScheduleLog(migrationSchedule).Infof("Starting migration %v", migrationName)
_, err = k8s.Instance().CreateMigration(migration)
return err
}
func (m *MigrationScheduleController) pruneMigrations(migrationSchedule *stork_api.MigrationSchedule) error {
updated := false
for policyType, policyMigration := range migrationSchedule.Status.Items {
// Keep only one successful migration status and all failed migrations
// until there is a successful one
numMigrations := len(policyMigration)
deleteBefore := 0
if numMigrations > 1 {
// Start from the end and find the last successful migration
for i := range policyMigration {
if policyMigration[(numMigrations-i-1)].Status == stork_api.MigrationStatusSuccessful {
deleteBefore = numMigrations - i - 1
break
}
}
for i := 0; i < deleteBefore; i++ {
err := k8s.Instance().DeleteMigration(policyMigration[i].Name, migrationSchedule.Namespace)
if err != nil {
log.MigrationScheduleLog(migrationSchedule).Warnf("Error deleting %v: %v", policyMigration[i].Name, err)
}
}
migrationSchedule.Status.Items[policyType] = policyMigration[deleteBefore:]
if deleteBefore > 0 {
updated = true
}
}
}
if updated {
return sdk.Update(migrationSchedule)
}
return nil
}
func (m *MigrationScheduleController) deleteMigrations(migrationSchedule *stork_api.MigrationSchedule) error {
var lastError error
for _, policyMigration := range migrationSchedule.Status.Items {
for _, migration := range policyMigration {
err := k8s.Instance().DeleteMigration(migration.Name, migrationSchedule.Namespace)
if err != nil && !errors.IsNotFound(err) {
log.MigrationScheduleLog(migrationSchedule).Warnf("Error deleting %v: %v", migration.Name, err)
lastError = err
}
}
}
return lastError
}
func (m *MigrationScheduleController) createCRD() error {
resource := k8s.CustomResource{
Name: stork_api.MigrationScheduleResourceName,
Plural: stork_api.MigrationScheduleResourcePlural,
Group: stork.GroupName,
Version: stork_api.SchemeGroupVersion.Version,
Scope: apiextensionsv1beta1.NamespaceScoped,
Kind: reflect.TypeOf(stork_api.MigrationSchedule{}).Name(),
}
err := k8s.Instance().CreateCRD(resource)
if err != nil && !errors.IsAlreadyExists(err) {
return err
}
return k8s.Instance().ValidateCRD(resource, validateCRDTimeout, validateCRDInterval)
}