-
Notifications
You must be signed in to change notification settings - Fork 302
/
tasks.go
209 lines (187 loc) · 6.16 KB
/
tasks.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
// Copyright © 2019 The Things Network Foundation, The Things Industries B.V.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package component
import (
"context"
"fmt"
"os"
"runtime/debug"
"time"
"go.thethings.network/lorawan-stack/v3/pkg/errors"
"go.thethings.network/lorawan-stack/v3/pkg/log"
"go.thethings.network/lorawan-stack/v3/pkg/random"
)
// TaskFunc is the task function.
type TaskFunc func(context.Context) error
func (f TaskFunc) Execute(ctx context.Context) (err error) {
defer func() {
if p := recover(); p != nil {
fmt.Fprintf(os.Stderr, "%s\n%s", p, debug.Stack())
if pErr, ok := p.(error); ok {
err = errTaskRecovered.WithCause(pErr)
} else {
err = errTaskRecovered.WithAttributes("panic", p)
}
}
}()
return f(ctx)
}
// TaskRestart defines a task's restart policy.
type TaskRestart uint8
const (
// TaskRestartNever denotes a restart policy that never restarts tasks after success or failure.
TaskRestartNever TaskRestart = iota
// TaskRestartAlways denotes a restart policy that always restarts tasks, on success and failure.
TaskRestartAlways
// TaskRestartOnFailure denotes a restart policy that restarts tasks on failure.
TaskRestartOnFailure
)
const (
DefaultTaskBackoffResetDuration = time.Minute
DefaultTaskBackoffJitter = 0.1
)
// TaskBackoffIntervalFunc is a function that decides the backoff interval based on the attempt history.
// invocation is a counter, which starts at 1 and is incremented after each task function invocation.
type TaskBackoffIntervalFunc func(ctx context.Context, executionDuration time.Duration, invocation uint, err error) time.Duration
// TaskBackoffConfig represents task backoff configuration.
type TaskBackoffConfig struct {
Jitter float64
IntervalFunc TaskBackoffIntervalFunc
}
// MakeTaskBackoffIntervalFunc returns a new TaskBackoffIntervalFunc.
func MakeTaskBackoffIntervalFunc(onFailure bool, resetDuration time.Duration, intervals ...time.Duration) TaskBackoffIntervalFunc {
return func(ctx context.Context, executionDuration time.Duration, invocation uint, err error) time.Duration {
switch {
case onFailure && err == nil:
return 0
case executionDuration > resetDuration:
return intervals[0]
case invocation >= uint(len(intervals)):
return intervals[len(intervals)-1]
default:
return intervals[invocation-1]
}
}
}
var (
// DefaultTaskBackoffIntervals are the default task backoff intervals.
DefaultTaskBackoffIntervals = [...]time.Duration{
10 * time.Millisecond,
50 * time.Millisecond,
100 * time.Millisecond,
time.Second,
}
// DefaultTaskBackoffIntervalFunc is the default TaskBackoffIntervalFunc.
DefaultTaskBackoffIntervalFunc = MakeTaskBackoffIntervalFunc(false, DefaultTaskBackoffResetDuration, DefaultTaskBackoffIntervals[:]...)
// DefaultTaskBackoffConfig is the default task backoff config.
DefaultTaskBackoffConfig = &TaskBackoffConfig{
Jitter: DefaultTaskBackoffJitter,
IntervalFunc: DefaultTaskBackoffIntervalFunc,
}
// DialTaskBackoffIntervals are the default task backoff intervals for tasks using Dial.
DialTaskBackoffIntervals = [...]time.Duration{
100 * time.Millisecond,
time.Second,
10 * time.Second,
}
// DialTaskBackoffIntervalFunc is the default TaskBackoffIntervalFunc for tasks using Dial.
DialTaskBackoffIntervalFunc = MakeTaskBackoffIntervalFunc(false, DefaultTaskBackoffResetDuration, DialTaskBackoffIntervals[:]...)
// DialTaskBackoffConfig is the default task backoff config for tasks using Dial.
DialTaskBackoffConfig = &TaskBackoffConfig{
Jitter: DefaultTaskBackoffJitter,
IntervalFunc: DialTaskBackoffIntervalFunc,
}
)
type TaskConfig struct {
Context context.Context
ID string
Func TaskFunc
Done func()
Restart TaskRestart
Backoff *TaskBackoffConfig
}
// RegisterTask registers a task, optionally with restart policy and backoff, to be started after the component started.
func (c *Component) RegisterTask(conf *TaskConfig) {
c.taskConfigs = append(c.taskConfigs, conf)
}
type TaskStarter interface {
// StartTask starts the specified task function, optionally with restart policy and backoff.
StartTask(*TaskConfig)
}
type StartTaskFunc func(*TaskConfig)
func (f StartTaskFunc) StartTask(conf *TaskConfig) {
f(conf)
}
var errTaskRecovered = errors.Define("task_recovered", "task recovered")
func DefaultStartTask(conf *TaskConfig) {
logger := log.FromContext(conf.Context).WithField("task_id", conf.ID)
go func() {
defer func() {
if done := conf.Done; done != nil {
done()
}
}()
for invocation := uint(1); ; invocation++ {
if invocation == 0 {
logger.Warn("Invocation count rollover detected")
invocation = 1
}
startTime := time.Now()
err := conf.Func.Execute(conf.Context)
executionDuration := time.Since(startTime)
if err != nil && err != context.Canceled {
logger.WithField("invocation", invocation).WithError(err).Warn("Task failed")
}
switch conf.Restart {
case TaskRestartNever:
return
case TaskRestartAlways:
case TaskRestartOnFailure:
if err == nil {
return
}
default:
panic("Invalid TaskConfig.Restart value")
}
select {
case <-conf.Context.Done():
return
default:
}
if conf.Backoff == nil {
continue
}
s := conf.Backoff.IntervalFunc(conf.Context, executionDuration, invocation, err)
if s == 0 {
continue
}
if conf.Backoff.Jitter != 0 {
s = random.Jitter(s, conf.Backoff.Jitter)
}
select {
case <-conf.Context.Done():
return
case <-time.After(s):
}
}
}()
}
func (c *Component) StartTask(conf *TaskConfig) {
c.taskStarter.StartTask(conf)
}
func (c *Component) startTasks() {
for _, conf := range c.taskConfigs {
c.taskStarter.StartTask(conf)
}
}