forked from Kuper-Tech/work
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dead_pool_reaper.go
179 lines (149 loc) · 4.44 KB
/
dead_pool_reaper.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
package work
import (
"fmt"
"math/rand"
"strings"
"time"
"github.com/gomodule/redigo/redis"
)
const (
deadTime = 10 * time.Second // 2 x heartbeat
reapPeriod = 10 * time.Minute
reapJitterSecs = 30
requeueKeysPerJob = 4
)
type deadPoolReaper struct {
namespace string
pool *redis.Pool
deadTime time.Duration
reapPeriod time.Duration
curJobTypes []string
stopChan chan struct{}
doneStoppingChan chan struct{}
}
func newDeadPoolReaper(namespace string, pool *redis.Pool, curJobTypes []string) *deadPoolReaper {
return &deadPoolReaper{
namespace: namespace,
pool: pool,
deadTime: deadTime,
reapPeriod: reapPeriod,
curJobTypes: curJobTypes,
stopChan: make(chan struct{}),
doneStoppingChan: make(chan struct{}),
}
}
func (r *deadPoolReaper) start() {
go r.loop()
}
func (r *deadPoolReaper) stop() {
r.stopChan <- struct{}{}
<-r.doneStoppingChan
}
func (r *deadPoolReaper) loop() {
// Reap immediately after we provide some time for initialization
timer := time.NewTimer(r.deadTime)
defer timer.Stop()
for {
select {
case <-r.stopChan:
r.doneStoppingChan <- struct{}{}
return
case <-timer.C:
// Schedule next occurrence periodically with jitter
timer.Reset(r.reapPeriod + time.Duration(rand.Intn(reapJitterSecs))*time.Second)
// Reap
if err := r.reap(); err != nil {
logError("dead_pool_reaper.reap", err)
}
}
}
}
func (r *deadPoolReaper) reap() error {
deadPoolIDs, err := r.removeDeadPools()
if err != nil {
return err
}
conn := r.pool.Get()
defer conn.Close()
// Cleanup all dead pools
for deadPoolID, jobTypes := range deadPoolIDs {
lockJobTypes := jobTypes
// if we found jobs from the heartbeat, requeue them and remove the heartbeat
if len(jobTypes) > 0 {
r.requeueInProgressJobs(deadPoolID, jobTypes)
if _, err = conn.Do("DEL", redisKeyHeartbeat(r.namespace, deadPoolID)); err != nil {
return err
}
} else {
// try to clean up locks for the current set of jobs if heartbeat was not found
lockJobTypes = r.curJobTypes
}
// Cleanup any stale lock info
if err = r.cleanStaleLockInfo(deadPoolID, lockJobTypes); err != nil {
return err
}
}
return nil
}
func (r *deadPoolReaper) cleanStaleLockInfo(poolID string, jobTypes []string) error {
numKeys := len(jobTypes) * 2
redisReapLocksScript := redis.NewScript(numKeys, redisLuaReapStaleLocks)
var scriptArgs = make([]interface{}, 0, numKeys+1) // +1 for argv[1]
for _, jobType := range jobTypes {
scriptArgs = append(scriptArgs, redisKeyJobsLock(r.namespace, jobType), redisKeyJobsLockInfo(r.namespace, jobType))
}
scriptArgs = append(scriptArgs, poolID) // ARGV[1]
conn := r.pool.Get()
defer conn.Close()
if _, err := redisReapLocksScript.Do(conn, scriptArgs...); err != nil {
return err
}
return nil
}
func (r *deadPoolReaper) requeueInProgressJobs(poolID string, jobTypes []string) error {
numKeys := len(jobTypes) * requeueKeysPerJob
redisRequeueScript := redis.NewScript(numKeys, redisLuaReenqueueJob)
var scriptArgs = make([]interface{}, 0, numKeys+1)
for _, jobType := range jobTypes {
// pops from in progress, push into job queue and decrement the queue lock
scriptArgs = append(scriptArgs, redisKeyJobsInProgress(r.namespace, poolID, jobType), redisKeyJobs(r.namespace, jobType), redisKeyJobsLock(r.namespace, jobType), redisKeyJobsLockInfo(r.namespace, jobType)) // KEYS[1-4 * N]
}
scriptArgs = append(scriptArgs, poolID) // ARGV[1]
conn := r.pool.Get()
defer conn.Close()
// Keep moving jobs until all queues are empty
for {
values, err := redis.Values(redisRequeueScript.Do(conn, scriptArgs...))
if err == redis.ErrNil {
return nil
} else if err != nil {
return err
}
if len(values) != 3 {
return fmt.Errorf("need 3 elements back")
}
}
}
// removeDeadPools removes staled pools and returns their IDs and associated jobs.
func (r *deadPoolReaper) removeDeadPools() (map[string][]string, error) {
var scriptArgs []interface{} = []interface{}{
redisKeyWorkerPools(r.namespace),
r.deadTime.Seconds(),
nowEpochSeconds(),
}
conn := r.pool.Get()
defer conn.Close()
dpools, err := redis.StringMap(redisTakeDeadPoolsScript.Do(conn, scriptArgs...))
if err != nil {
return nil, err
}
deadPools := make(map[string][]string, len(dpools))
for k, v := range dpools {
if v == "" {
deadPools[k] = []string{}
} else {
deadPools[k] = strings.Split(v, ",")
}
}
return deadPools, nil
}