/
periodic.go
217 lines (195 loc) · 6.03 KB
/
periodic.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
// Copyright 2018 Anapaya Systems
//
// 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 periodic
import (
"context"
"time"
"github.com/opentracing/opentracing-go"
"github.com/scionproto/scion/pkg/log"
"github.com/scionproto/scion/pkg/metrics"
legacymetrics "github.com/scionproto/scion/private/periodic/internal/metrics"
)
// A Task that has to be periodically executed.
type Task interface {
// Run executes the task once, it should return within the context's timeout.
Run(context.Context)
// Name returns the task's name for use in metrics and tracing. Each
// successive call should return the same value as the first call. Names
// must only contain [a-z] and _ characters.
Name() string
}
const (
// EventStop indicates a stop event took place.
EventStop = "stop"
// EventKill indicates a kill event took place.
EventKill = "kill"
// EventTrigger indicates a trigger event took place.
EventTrigger = "triggered"
)
// Metrics contains the relevant metrics for a periodic task.
type Metrics struct {
// Events tracks the amount of occurrences of Events defined above.
Events func(string) metrics.Counter
// Period is a Gauge describing the current Period.
Period metrics.Gauge
// Runtime tracks how long the task has been running.
Runtime metrics.Gauge
// StartTime is a timestamp of when the task was started.
StartTime metrics.Gauge
}
func (m *Metrics) setStartTimestamp(t time.Time) {
metrics.GaugeSet(m.StartTime, float64(t.UnixNano()/1e9))
}
func (m *Metrics) setPeriod(d time.Duration) {
metrics.GaugeSet(m.Period, d.Seconds())
}
func (m *Metrics) setRuntime(d time.Duration) {
metrics.GaugeAdd(m.Runtime, float64(d)/1e9)
}
func (m *Metrics) event(s string) {
metrics.CounterAdd(m.Events(s), 1)
}
// Func implements the Task interface.
type Func struct {
// Task is the function that is executed on Run.
Task func(context.Context)
// TaskName is the name returned by Name,
TaskName string
}
// Run runs the task function.
func (f Func) Run(ctx context.Context) {
f.Task(ctx)
}
// Name returns the task name.
func (f Func) Name() string {
return f.TaskName
}
// Runner runs a task periodically.
type Runner struct {
task Task
ticker *time.Ticker
timeout time.Duration
stop chan struct{}
loopFinished chan struct{}
ctx context.Context
cancelF context.CancelFunc
trigger chan struct{}
metric *Metrics
}
// Start creates and starts a new Runner to run the given task periodically.
// The timeout is used for the context timeout of the task. The timeout can be
// larger than the periodicity of the task. That means if a tasks takes a long
// time it will be immediately retriggered.
//
// Deprecated: Start exists for compatibility reasons, use StartWithMetrics instead.
func Start(task Task, period, timeout time.Duration) *Runner {
genMetric := legacymetrics.NewMetric(task.Name())
metric := Metrics{
Events: genMetric.Events,
Period: genMetric.Period,
Runtime: genMetric.Runtime,
StartTime: genMetric.Timestamp,
}
return StartWithMetrics(task, &metric, period, timeout)
}
// StartWithMetrics is identical to Start but allows the caller to
// specify the metric or no metric at all to be used.
func StartWithMetrics(task Task, metric *Metrics, period, timeout time.Duration) *Runner {
ctx, cancelF := context.WithCancel(context.Background())
logger := log.New("debug_id", log.NewDebugID())
ctx = log.CtxWith(ctx, logger)
r := &Runner{
task: task,
ticker: time.NewTicker(period),
timeout: timeout,
stop: make(chan struct{}),
loopFinished: make(chan struct{}),
ctx: ctx,
cancelF: cancelF,
trigger: make(chan struct{}),
metric: metric,
}
logger.Info("Starting periodic task", "task", task.Name())
r.metric.setPeriod(period)
r.metric.setStartTimestamp(time.Now())
go func() {
defer log.HandlePanic()
r.runLoop()
}()
return r
}
// Stop stops the periodic execution of the Runner.
// If the task is currently running this method will block until it is done.
func (r *Runner) Stop() {
r.ticker.Stop()
close(r.stop)
<-r.loopFinished
r.metric.event(EventStop)
}
// Kill is like stop but it also cancels the context of the current running method.
func (r *Runner) Kill() {
if r == nil {
return
}
r.ticker.Stop()
close(r.stop)
r.cancelF()
<-r.loopFinished
r.metric.event(EventKill)
}
// TriggerRun triggers the periodic task to run now.
// This does not impact the normal periodicity of this task.
// That means if the periodicity is 5m and you call TriggerNow() after 2 minutes,
// the next execution will be in 3 minutes.
//
// The method blocks until either the triggered run was started or the runner was stopped,
// in which case the triggered run will not be executed.
func (r *Runner) TriggerRun() {
select {
// Either we were stopped or we can put something in the trigger channel.
case <-r.stop:
case r.trigger <- struct{}{}:
}
r.metric.event(EventTrigger)
}
func (r *Runner) runLoop() {
defer close(r.loopFinished)
defer r.cancelF()
for {
select {
case <-r.stop:
return
case <-r.ticker.C:
r.onTick()
case <-r.trigger:
r.onTick()
}
}
}
func (r *Runner) onTick() {
select {
// Make sure that stop case is evaluated first,
// so that when we kill and both channels are ready we always go into stop first.
case <-r.stop:
return
default:
ctx, cancelF := context.WithTimeout(r.ctx, r.timeout)
span, ctx := opentracing.StartSpanFromContext(ctx, "periodic."+r.task.Name())
defer span.Finish()
start := time.Now()
r.task.Run(ctx)
r.metric.setRuntime(time.Since(start))
cancelF()
}
}