-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecoverer.go
136 lines (111 loc) · 2.47 KB
/
recoverer.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
package flowstate
import (
"context"
"errors"
"log"
"strconv"
"time"
)
type RecovererDoer struct {
failoverDur time.Duration
wl WatchListener
e Engine
doneCh chan struct{}
stoppedCh chan struct{}
log []State
}
func Recoverer(failoverDur time.Duration) Doer {
return &RecovererDoer{
failoverDur: failoverDur,
doneCh: make(chan struct{}),
stoppedCh: make(chan struct{}),
}
}
func (d *RecovererDoer) Do(_ Command) error {
return ErrCommandNotSupported
}
func (d *RecovererDoer) Init(e Engine) error {
cmd := Watch(nil)
if err := e.Do(cmd); err != nil {
return err
}
d.wl = cmd.Listener
d.e = e
go func() {
defer close(d.stoppedCh)
t := time.NewTicker(d.failoverDur)
defer t.Stop()
for {
select {
case <-d.doneCh:
return
case state0 := <-d.wl.Listen():
state := state0.CopyTo(&State{})
d.log = append(d.log, state)
case <-t.C:
if err := d.checkLog(); err != nil {
log.Printf("ERROR: recovery: check log: %v", err)
}
}
}
}()
return nil
}
func (d *RecovererDoer) checkLog() error {
visited := make(map[StateID]struct{})
failoverTime := time.Now().Add(-d.failoverDur)
newLog := make([]State, 0, len(d.log))
for i := len(d.log) - 1; i >= 0; i-- {
state := d.log[i]
if Paused(state) || Ended(state) {
continue
} else if _, ok := visited[state.ID]; ok {
continue
}
if !state.CommittedAt().Before(failoverTime) {
visited[state.ID] = struct{}{}
newLog = append(newLog, state)
continue
}
conflictErr := &ErrCommitConflict{}
recoveryAttempt := RecoveryAttempt(state)
if recoveryAttempt >= 2 {
stateCtx := state.CopyToCtx(&StateCtx{})
if err := d.e.Do(
Commit(End(stateCtx)),
); errors.As(err, conflictErr) {
visited[state.ID] = struct{}{}
continue
} else if err != nil {
return err
}
visited[state.ID] = struct{}{}
continue
}
stateCtx := state.CopyToCtx(&StateCtx{})
stateCtx.Current.Transition.SetAnnotation(RecoveryAttemptAnnotation, strconv.Itoa(recoveryAttempt+1))
if err := d.e.Do(
Commit(CommitStateCtx(stateCtx)),
Execute(stateCtx),
); errors.As(err, conflictErr) {
visited[state.ID] = struct{}{}
continue
} else if err != nil {
return err
}
visited[state.ID] = struct{}{}
continue
}
d.log = newLog
return nil
}
func (d *RecovererDoer) Shutdown(ctx context.Context) error {
d.wl.Close()
close(d.doneCh)
select {
case <-d.stoppedCh:
return nil
case <-ctx.Done():
return ctx.Err()
}
}