-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathtimeout_handler.go
290 lines (260 loc) · 9.85 KB
/
timeout_handler.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
/*
Copyright 2019 The Tekton Authors
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 reconciler
import (
"math"
"math/rand"
"sync"
"time"
"github.com/tektoncd/pipeline/pkg/apis/config"
"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1"
clientset "github.com/tektoncd/pipeline/pkg/client/clientset/versioned"
"go.uber.org/zap"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
const (
maxBackoffSeconds = 120
)
var (
defaultFunc = func(i interface{}) {}
maxBackoffExponent = math.Ceil(math.Log2(maxBackoffSeconds))
)
// StatusKey interface to be implemented by Taskrun Pipelinerun types
type StatusKey interface {
GetRunKey() string
}
// backoff contains state of exponential backoff for a given StatusKey
type backoff struct {
// NumAttempts reflects the number of times a given StatusKey has been delayed
NumAttempts uint
// NextAttempt is the point in time at which this backoff expires
NextAttempt time.Time
}
// jitterFunc is a func applied to a computed backoff duration to remove uniformity
// from its results. A jitterFunc receives the number of seconds calculated by a
// backoff algorithm and returns the "jittered" result.
type jitterFunc func(numSeconds int) (jitteredSeconds int)
// TimeoutSet contains required k8s interfaces to handle build timeouts
type TimeoutSet struct {
logger *zap.SugaredLogger
taskRunCallbackFunc func(interface{})
pipelineRunCallbackFunc func(interface{})
stopCh <-chan struct{}
done map[string]chan bool
doneMut sync.Mutex
backoffs map[string]backoff
backoffsMut sync.Mutex
}
// NewTimeoutHandler returns TimeoutSet filled structure
func NewTimeoutHandler(
stopCh <-chan struct{},
logger *zap.SugaredLogger,
) *TimeoutSet {
return &TimeoutSet{
stopCh: stopCh,
done: make(map[string]chan bool),
backoffs: make(map[string]backoff),
logger: logger,
}
}
// SetTaskRunCallbackFunc sets the callback function when timeout occurs for taskrun objects
func (t *TimeoutSet) SetTaskRunCallbackFunc(f func(interface{})) {
t.taskRunCallbackFunc = f
}
// SetPipelineRunCallbackFunc sets the callback function when timeout occurs for pipelinerun objects
func (t *TimeoutSet) SetPipelineRunCallbackFunc(f func(interface{})) {
t.pipelineRunCallbackFunc = f
}
// Release deletes channels and data that are specific to a StatusKey object.
func (t *TimeoutSet) Release(runObj StatusKey) {
key := runObj.GetRunKey()
t.doneMut.Lock()
defer t.doneMut.Unlock()
t.backoffsMut.Lock()
defer t.backoffsMut.Unlock()
if finished, ok := t.done[key]; ok {
delete(t.done, key)
close(finished)
}
delete(t.backoffs, key)
}
func (t *TimeoutSet) getOrCreateFinishedChan(runObj StatusKey) chan bool {
var finished chan bool
key := runObj.GetRunKey()
t.doneMut.Lock()
defer t.doneMut.Unlock()
if existingfinishedChan, ok := t.done[key]; ok {
finished = existingfinishedChan
} else {
finished = make(chan bool)
}
t.done[key] = finished
return finished
}
// GetBackoff records the number of times it has seen a TaskRun and calculates an
// appropriate backoff deadline based on that count. Only one backoff per TaskRun
// may be active at any moment. Requests for a new backoff in the face of an
// existing one will be ignored and details of the existing backoff will be returned
// instead. Further, if a calculated backoff time is after the timeout of the TaskRun
// then the time of the timeout will be returned instead.
//
// Returned values are a backoff struct containing a NumAttempts field with the
// number of attempts performed for this TaskRun and a NextAttempt field
// describing the time at which the next attempt should be performed.
// Additionally a boolean is returned indicating whether a backoff for the
// TaskRun is already in progress.
func (t *TimeoutSet) GetBackoff(tr *v1alpha1.TaskRun) (backoff, bool) {
t.backoffsMut.Lock()
defer t.backoffsMut.Unlock()
b := t.backoffs[tr.GetRunKey()]
if time.Now().Before(b.NextAttempt) {
return b, true
}
b.NumAttempts += 1
b.NextAttempt = time.Now().Add(backoffDuration(b.NumAttempts, rand.Intn))
timeoutDeadline := tr.Status.StartTime.Time.Add(tr.Spec.Timeout.Duration)
if timeoutDeadline.Before(b.NextAttempt) {
b.NextAttempt = timeoutDeadline
}
t.backoffs[tr.GetRunKey()] = b
return b, false
}
func backoffDuration(count uint, jf jitterFunc) time.Duration {
exp := float64(count)
if exp > maxBackoffExponent {
exp = maxBackoffExponent
}
seconds := int(math.Exp2(exp))
jittered := 1 + jf(seconds)
if jittered > maxBackoffSeconds {
jittered = maxBackoffSeconds
}
return time.Duration(jittered) * time.Second
}
// checkPipelineRunTimeouts function creates goroutines to wait for pipelinerun to
// finish/timeout in a given namespace
func (t *TimeoutSet) checkPipelineRunTimeouts(namespace string, pipelineclientset clientset.Interface) {
pipelineRuns, err := pipelineclientset.TektonV1alpha1().PipelineRuns(namespace).List(metav1.ListOptions{})
if err != nil {
t.logger.Errorf("Can't get pipelinerun list in namespace %s: %s", namespace, err)
return
}
for _, pipelineRun := range pipelineRuns.Items {
pipelineRun := pipelineRun
if pipelineRun.IsDone() || pipelineRun.IsCancelled() {
continue
}
if pipelineRun.HasStarted() {
go t.WaitPipelineRun(&pipelineRun, pipelineRun.Status.StartTime)
}
}
}
// CheckTimeouts function iterates through all namespaces and calls corresponding
// taskrun/pipelinerun timeout functions
func (t *TimeoutSet) CheckTimeouts(kubeclientset kubernetes.Interface, pipelineclientset clientset.Interface) {
namespaces, err := kubeclientset.CoreV1().Namespaces().List(metav1.ListOptions{})
if err != nil {
t.logger.Errorf("Can't get namespaces list: %s", err)
return
}
for _, namespace := range namespaces.Items {
t.checkTaskRunTimeouts(namespace.GetName(), pipelineclientset)
t.checkPipelineRunTimeouts(namespace.GetName(), pipelineclientset)
}
}
// checkTaskRunTimeouts function creates goroutines to wait for pipelinerun to
// finish/timeout in a given namespace
func (t *TimeoutSet) checkTaskRunTimeouts(namespace string, pipelineclientset clientset.Interface) {
taskruns, err := pipelineclientset.TektonV1alpha1().TaskRuns(namespace).List(metav1.ListOptions{})
if err != nil {
t.logger.Errorf("Can't get taskrun list in namespace %s: %s", namespace, err)
return
}
for _, taskrun := range taskruns.Items {
taskrun := taskrun
if taskrun.IsDone() || taskrun.IsCancelled() {
continue
}
if taskrun.HasStarted() {
go t.WaitTaskRun(&taskrun, taskrun.Status.StartTime)
}
}
}
// WaitTaskRun function creates a blocking function for taskrun to wait for
// 1. Stop signal, 2. TaskRun to complete or 3. Taskrun to time out, which is
// determined by checking if the tr's timeout has occurred since the startTime
func (t *TimeoutSet) WaitTaskRun(tr *v1alpha1.TaskRun, startTime *metav1.Time) {
var timeout time.Duration
if tr.Spec.Timeout == nil {
timeout = config.DefaultTimeoutMinutes * time.Minute
} else {
timeout = tr.Spec.Timeout.Duration
}
t.waitRun(tr, timeout, startTime, t.taskRunCallbackFunc)
}
// WaitPipelineRun function creates a blocking function for pipelinerun to wait for
// 1. Stop signal, 2. pipelinerun to complete or 3. pipelinerun to time out which is
// determined by checking if the tr's timeout has occurred since the startTime
func (t *TimeoutSet) WaitPipelineRun(pr *v1alpha1.PipelineRun, startTime *metav1.Time) {
var timeout time.Duration
if pr.Spec.Timeout == nil {
timeout = config.DefaultTimeoutMinutes * time.Minute
} else {
timeout = pr.Spec.Timeout.Duration
}
t.waitRun(pr, timeout, startTime, t.pipelineRunCallbackFunc)
}
func (t *TimeoutSet) waitRun(runObj StatusKey, timeout time.Duration, startTime *metav1.Time, callback func(interface{})) {
if startTime == nil {
t.logger.Errorf("startTime must be specified in order for a timeout to be calculated accurately for %s", runObj.GetRunKey())
return
}
if callback == nil {
callback = defaultFunc
}
runtime := time.Since(startTime.Time)
t.logger.Infof("About to start timeout timer for %s. started at %s, timeout is %s, running for %s", runObj.GetRunKey(), startTime.Time, timeout, runtime)
defer t.Release(runObj)
t.setTimer(runObj, timeout-runtime, callback)
}
// SetTaskRunTimer creates a blocking function for taskrun to wait for
// 1. Stop signal, 2. TaskRun to complete or 3. a given Duration to elapse.
//
// Since the timer's duration is a parameter rather than being tied to
// the lifetime of the TaskRun no resources are released after the timer
// fires. It is the caller's responsibility to Release() the TaskRun when
// work with it has completed.
func (t *TimeoutSet) SetTaskRunTimer(tr *v1alpha1.TaskRun, d time.Duration) {
callback := t.taskRunCallbackFunc
if callback == nil {
t.logger.Errorf("attempted to set a timer for %q but no task run callback has been assigned", tr.Name)
return
}
t.setTimer(tr, d, callback)
}
func (t *TimeoutSet) setTimer(runObj StatusKey, timeout time.Duration, callback func(interface{})) {
finished := t.getOrCreateFinishedChan(runObj)
started := time.Now()
select {
case <-t.stopCh:
t.logger.Infof("stopping timer for %q", runObj.GetRunKey())
return
case <-finished:
t.logger.Infof("%q finished, stopping timer", runObj.GetRunKey())
return
case <-time.After(timeout):
t.logger.Infof("timer for %q has activated after %s", runObj.GetRunKey(), time.Since(started).String())
callback(runObj)
}
}