-
Notifications
You must be signed in to change notification settings - Fork 61
/
machine.go
299 lines (262 loc) · 8.61 KB
/
machine.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
/*
Copyright 2022 The VolSync authors.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package statemachine
import (
"context"
"time"
"github.com/go-logr/logr"
cron "github.com/robfig/cron/v3"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
ctrl "sigs.k8s.io/controller-runtime"
)
// replicationState is the different states that replication object can be in
type replicationState string
const (
initialState replicationState = "Initial"
synchronizingState replicationState = "Synchronizing"
cleaningUpState replicationState = "CleaningUp"
)
// triggerType represents the different ways we can trigger data synchronization
type triggerType string
const (
scheduleTrigger triggerType = "ScheduleTrigger"
manualTrigger triggerType = "ManualTrigger"
noTrigger triggerType = "NoTrigger"
)
// Run the state machine to reconcile the ReplicationController
func Run(ctx context.Context, r ReplicationMachine, l logr.Logger) (ctrl.Result, error) {
// Set out-of-sync metrics flag if necessary
if r.LastSyncTime() == nil {
r.SetOutOfSync(true)
} else {
missed, err := missedDeadline(r)
if err != nil {
setConditionError(r, l, err)
return ctrl.Result{}, err
}
if missed {
r.SetOutOfSync(true)
}
}
var result ctrl.Result
var err error
switch currentState(r) {
case initialState:
result, err = doInitialState(ctx, r, l)
case synchronizingState:
result, err = doSynchronizingState(ctx, r, l)
case cleaningUpState:
result, err = doCleanupState(ctx, r, l)
default:
l.Error(nil, "invalid state detected; switching to Synchronizing")
err = transitionToSynchronizing(r, l)
}
if err != nil {
setConditionError(r, l, err)
}
return result, err
}
func getTrigger(r ReplicationMachine) triggerType {
switch {
case len(r.ManualTag()) > 0:
return manualTrigger
case len(r.Cronspec()) > 0:
return scheduleTrigger
default:
return noTrigger
}
}
// ctrl.Result is always empty, but leave it as a return param to be consistent with other funcs
// nolint:unparam
func doInitialState(_ context.Context, r ReplicationMachine, l logr.Logger) (ctrl.Result, error) {
err := transitionToSynchronizing(r, l)
// We don't need to explicitly re-queue because the transition will
// cause a .status update
return ctrl.Result{}, err
}
func doSynchronizingState(ctx context.Context, r ReplicationMachine, l logr.Logger) (ctrl.Result, error) {
result, err := r.Synchronize(ctx)
if err != nil {
return ctrl.Result{}, err
}
if result.Completed {
// Just finished a sync, so we're in-sync
r.SetOutOfSync(false)
err = transitionToCleaningUp(r, l)
if err != nil {
return ctrl.Result{}, err
}
} else {
setConditionSyncing(r, l)
}
return result.ReconcileResult(), nil
}
func doCleanupState(ctx context.Context, r ReplicationMachine, l logr.Logger) (ctrl.Result, error) {
result, err := r.Cleanup(ctx)
if err != nil {
return ctrl.Result{}, err
}
// Ensure nextSyncTime picks up any changes made to the schedule
if err := updateNextSyncStartTime(r, l); err != nil {
return ctrl.Result{}, err
}
// If we have finished cleaning up, we remain in this state until the
// next reconcile is triggered, but we tell the user that we are "idle".
if result.Completed {
if shouldSync(r, l) { // Time to start syncing again
err := transitionToSynchronizing(r, l)
if err != nil {
return ctrl.Result{}, err
}
} else { // We're idle
if getTrigger(r) == scheduleTrigger {
setConditionScheduled(r, l)
} else {
setConditionManual(r, l)
}
timeToNext := timeToNextSync(r)
switch {
case timeToNext == nil:
return ctrl.Result{}, nil
default:
return ctrl.Result{RequeueAfter: *timeToNext}, nil
}
}
} else {
setConditionCleanup(r, l)
}
return result.ReconcileResult(), nil
}
// Determine which state we're in by looking at the CR
func currentState(r ReplicationMachine) replicationState {
// If we've never completed a sync and we're not trying to sync, we must be
// in the initial state
if r.LastSyncTime().IsZero() && r.LastSyncStartTime().IsZero() {
return initialState
}
// If we're trying to sync, then we're in the synchronizing state
if !r.LastSyncStartTime().IsZero() {
return synchronizingState
}
// Otherwise, we're in cleanup
return cleaningUpState
}
//nolint:unparam
func transitionToSynchronizing(r ReplicationMachine, l logr.Logger) error {
l.V(1).Info("transitioning to synchronization state")
now := metav1.Now()
r.SetLastSyncStartTime(&now)
setConditionSyncing(r, l)
return nil
}
func transitionToCleaningUp(r ReplicationMachine, l logr.Logger) error {
l.V(1).Info("transitioning to cleanup state")
// If we took too long, update the miss count. We update here since
// we only want to count each miss once (ideally), so we do the
// update only when we try to transition.
missed, err := missedDeadline(r)
if err != nil {
return err
}
if missed {
r.IncMissedIntervals()
}
// Record the synchronization end time
now := metav1.Now()
r.SetLastSyncTime(&now)
// Calculate how long the synchronization took
syncDuration := now.Sub(r.LastSyncStartTime().Time)
r.SetLastSyncDuration(&metav1.Duration{Duration: syncDuration})
r.ObserveSyncDuration(syncDuration)
// Determine when our next synchronization should start
if err := updateNextSyncStartTime(r, l); err != nil {
return err
}
// Update manual trigger tag in .status to match the one in .spec
r.SetLastManualTag(r.ManualTag())
// Since we're done syncing, clear LSST. In addition to being useful for
// duration calculation, it serves as the indicator of which state we're in
r.SetLastSyncStartTime(nil)
setConditionCleanup(r, l)
return nil
}
// Given that we've finished cleanup, should we start syncing again?
func shouldSync(r ReplicationMachine, l logr.Logger) bool {
switch getTrigger(r) {
case scheduleTrigger:
// When schedule-based, we trigger a sync once we pass the appointed
// time
return time.Now().After(r.NextSyncTime().Time)
case manualTrigger:
// We need to do a sync if the manual trigger tags don't match
return r.ManualTag() != r.LastManualTag()
case noTrigger:
// When there's no trigger specified, we run in a tight loop,
// immediately synchronizing as soon as we finish cleanup
return true
}
// We should never get here
l.Error(nil, "unable to determine whether to sync; defaulting to true")
return true
}
// How long long until the next sync should start (or nil if not
// schedule-based).
func timeToNextSync(r ReplicationMachine) *time.Duration {
if r.NextSyncTime().IsZero() {
return nil
}
next := time.Until(r.NextSyncTime().Time)
return &next
}
func getSchedule(cronspec string) (cron.Schedule, error) {
parser := cron.NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor)
return parser.Parse(cronspec)
}
// pastScheduleDeadline returns true if a scheduled sync hasn't been completed
// within the synchronization period.
func pastScheduleDeadline(schedule cron.Schedule, lastCompleted time.Time, now time.Time) bool {
// Each synchronization should complete before the next scheduled start
// time. This means that, starting from the last completed, the next sync
// would start at last->next, and must finish before last->next->next.
return schedule.Next(schedule.Next(lastCompleted)).Before(now)
}
// Returns true if we're schedule-based and have missed our deadline
func missedDeadline(r ReplicationMachine) (bool, error) {
if getTrigger(r) == scheduleTrigger && !r.LastSyncTime().IsZero() {
schedule, err := getSchedule(r.Cronspec())
if err != nil {
return false, err
}
if pastScheduleDeadline(schedule, r.LastSyncTime().Time, time.Now()) {
return true, nil
}
}
return false, nil
}
func updateNextSyncStartTime(r ReplicationMachine, l logr.Logger) error {
lastSync := r.LastSyncTime()
switch getTrigger(r) {
case scheduleTrigger:
schedule, err := getSchedule(r.Cronspec())
if err != nil {
l.Error(err, "error parsing schedule", "cronspec", r.Cronspec())
return err
}
next := schedule.Next(lastSync.Time)
r.SetNextSyncTime(&metav1.Time{Time: next})
case manualTrigger, noTrigger:
r.SetNextSyncTime(nil)
}
return nil
}