/
fallback.go
273 lines (232 loc) · 6.47 KB
/
fallback.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
// Copyright (C) 2020-2021, IrineSistiana
//
// This file is part of mosdns.
//
// mosdns is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) or later version.
//
// mosdns 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package executable_seq
import (
"context"
"errors"
"fmt"
"github.com/IrineSistiana/mosdns/v3/dispatcher/handler"
"github.com/IrineSistiana/mosdns/v3/dispatcher/pkg/pool"
"go.uber.org/zap"
"sync"
"time"
)
type FallbackConfig struct {
// Primary exec sequence.
Primary interface{} `yaml:"primary"`
// Secondary exec sequence.
Secondary interface{} `yaml:"secondary"`
StatLength int `yaml:"stat_length"` // A Zero value disables the normal fallback.
Threshold int `yaml:"threshold"`
// FastFallback threshold in milliseconds. Zero means fast fallback is disabled.
FastFallback int `yaml:"fast_fallback"`
// AlwaysStandby: secondary should always stand by in fast fallback.
AlwaysStandby bool `yaml:"always_standby"`
}
type FallbackNode struct {
primary handler.ExecutableChainNode
secondary handler.ExecutableChainNode
fastFallbackDuration time.Duration
alwaysStandby bool
primaryST *statusTracker // nil if normal fallback is disabled
logger *zap.Logger // not nil
}
type statusTracker struct {
sync.Mutex
threshold int
status []uint8 // 0 means success, !0 means failed
p int
s int
f int
}
func newStatusTracker(threshold, statLength int) *statusTracker {
return &statusTracker{
threshold: threshold,
status: make([]uint8, statLength),
s: statLength,
}
}
func (t *statusTracker) good() bool {
t.Lock()
defer t.Unlock()
return t.f < t.threshold
}
func (t *statusTracker) update(s uint8) {
t.Lock()
defer t.Unlock()
if s > 0 {
t.f++
} else {
t.s++
}
if t.p >= len(t.status) {
t.p = 0
}
oldS := t.status[t.p]
if oldS > 0 {
t.f--
} else {
t.s--
}
t.status[t.p] = s
t.p++
}
func ParseFallbackNode(c *FallbackConfig, logger *zap.Logger) (*FallbackNode, error) {
if c.Primary == nil {
return nil, errors.New("primary is empty")
}
if c.Secondary == nil {
return nil, errors.New("secondary is empty")
}
primaryECS, err := ParseExecutableNode(c.Primary, logger)
if err != nil {
return nil, fmt.Errorf("invalid primary sequence: %w", err)
}
secondaryECS, err := ParseExecutableNode(c.Secondary, logger)
if err != nil {
return nil, fmt.Errorf("invalid secondary sequence: %w", err)
}
fallbackECS := &FallbackNode{
primary: primaryECS,
secondary: secondaryECS,
fastFallbackDuration: time.Duration(c.FastFallback) * time.Millisecond,
alwaysStandby: c.AlwaysStandby,
}
if c.StatLength > 0 {
if c.Threshold > c.StatLength {
c.Threshold = c.StatLength
}
fallbackECS.primaryST = newStatusTracker(c.Threshold, c.StatLength)
}
if logger != nil {
fallbackECS.logger = logger
} else {
fallbackECS.logger = zap.NewNop()
}
return fallbackECS, nil
}
func (f *FallbackNode) Exec(ctx context.Context, qCtx *handler.Context, next handler.ExecutableChainNode) error {
if err := f.exec(ctx, qCtx); err != nil {
return err
}
return handler.ExecChainNode(ctx, qCtx, next)
}
func (f *FallbackNode) exec(ctx context.Context, qCtx *handler.Context) error {
if f.primaryST == nil || f.primaryST.good() {
if f.fastFallbackDuration > 0 {
return f.doFastFallback(ctx, qCtx)
} else {
return f.doPrimary(ctx, qCtx)
}
}
f.logger.Debug("primary is not good", qCtx.InfoField())
return f.doFallback(ctx, qCtx)
}
func (f *FallbackNode) isolateDoPrimary(ctx context.Context, qCtx *handler.Context) (err error) {
qCtxCopy := qCtx.Copy()
err = f.doPrimary(ctx, qCtxCopy)
qCtx.SetResponse(qCtxCopy.R(), qCtxCopy.Status())
return err
}
func (f *FallbackNode) doPrimary(ctx context.Context, qCtx *handler.Context) (err error) {
err = handler.ExecChainNode(ctx, qCtx, f.primary)
if f.primaryST != nil {
if err != nil || qCtx.R() == nil {
f.primaryST.update(1)
} else {
f.primaryST.update(0)
}
}
return err
}
func (f *FallbackNode) doFastFallback(ctx context.Context, qCtx *handler.Context) (err error) {
fCtx, cancel := context.WithCancel(ctx)
defer cancel()
timer := pool.GetTimer(f.fastFallbackDuration)
defer pool.ReleaseTimer(timer)
c := make(chan *parallelECSResult, 2)
primFailed := make(chan struct{}) // will be closed if primary returns an error.
qCtxP := qCtx.Copy()
go func() {
err := f.doPrimary(fCtx, qCtxP)
if err != nil || qCtxP.R() == nil {
close(primFailed)
}
c <- ¶llelECSResult{
qCtx: qCtxP,
err: err,
from: 1,
}
}()
qCtxS := qCtx.Copy()
go func() {
if !f.alwaysStandby { // not always standby, wait here.
select {
case <-fCtx.Done(): // primary is done, no need to exec this.
return
case <-primFailed: // primary failed or timeout, exec now.
case <-timer.C:
}
}
err := f.doSecondary(fCtx, qCtxS)
res := ¶llelECSResult{
qCtx: qCtxS,
err: err,
from: 2,
}
if f.alwaysStandby { // always standby
select {
case <-fCtx.Done():
return
case <-primFailed: // only send secondary result when primary is failed.
c <- res
case <-timer.C: // or timeout.
c <- res
}
} else {
c <- res // not always standby, send the result asap.
}
}()
return asyncWait(ctx, qCtx, f.logger, c, 2)
}
func (f *FallbackNode) doSecondary(ctx context.Context, qCtx *handler.Context) (err error) {
return handler.ExecChainNode(ctx, qCtx, f.secondary)
}
func (f *FallbackNode) doFallback(ctx context.Context, qCtx *handler.Context) error {
fCtx, cancel := context.WithCancel(ctx)
defer cancel()
c := make(chan *parallelECSResult, 2) // buf size is 2, avoid blocking.
qCtxP := qCtx.Copy()
go func() {
err := f.doPrimary(fCtx, qCtxP)
c <- ¶llelECSResult{
qCtx: qCtxP,
err: err,
from: 1,
}
}()
qCtxS := qCtx.Copy()
go func() {
err := f.doSecondary(fCtx, qCtxS)
c <- ¶llelECSResult{
qCtx: qCtxS,
err: err,
from: 2,
}
}()
return asyncWait(ctx, qCtx, f.logger, c, 2)
}