-
Notifications
You must be signed in to change notification settings - Fork 5
/
scheduler.go
328 lines (280 loc) · 7.18 KB
/
scheduler.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
package server
import (
"bytes"
"encoding/json"
"sort"
"sync"
"time"
"github.com/doomsday-project/doomsday/server/logger"
)
type taskKind uint
const (
//the order of these actually matters, because it is used for
// prioritization when sorting the queue
queueTaskKindAuth taskKind = iota
queueTaskKindRefresh
)
func (t taskKind) String() string {
switch t {
case queueTaskKindAuth:
return "auth"
case queueTaskKindRefresh:
return "refresh"
default:
return "unknown"
}
}
type runReason uint
const (
runReasonSchedule runReason = iota
runReasonAdhoc
)
func (r runReason) String() string {
switch r {
case runReasonSchedule:
return "scheduled"
case runReasonAdhoc:
return "adhoc"
default:
return "unknown"
}
}
type taskState uint
const (
//the order of these actually matters, because it is used for
// prioritization when sorting the queue
queueTaskStatePending = iota
queueTaskStateReady
queueTaskStateSkip
)
func (s taskState) String() string {
switch s {
case queueTaskStatePending:
return "pending"
case queueTaskStateReady:
return "ready"
case queueTaskStateSkip:
return "skipping"
default:
return "unknown"
}
}
type managerTask struct {
id uint
kind taskKind
source *Source
runTime time.Time
reason runReason
state taskState
assignedWorker *taskWorker
}
func (m *managerTask) durationUntil() time.Duration {
return m.runTime.Sub(time.Now())
}
func (m *managerTask) run(cache *Cache, log *logger.Logger) {
switch m.kind {
case queueTaskKindAuth:
m.source.Auth(log)
case queueTaskKindRefresh:
m.source.Refresh(cache, log)
}
}
type managerTasks []managerTask
type taskQueue struct {
data managerTasks
running managerTasks
lock *sync.Mutex
cond *sync.Cond
log *logger.Logger
globalCache *Cache
numWorkers uint
workers []*taskWorker
nextTaskID uint
}
func newTaskQueue(cache *Cache, numWorkers uint, log *logger.Logger) *taskQueue {
lock := &sync.Mutex{}
return &taskQueue{
lock: lock,
log: log,
cond: sync.NewCond(lock),
globalCache: cache,
numWorkers: numWorkers,
}
}
//enqueue puts a task into the queue, unique by the tuple source, taskType. If
//there already exists a task for this source/taskType, it will be removed and
//replaced with this new one atomically.
func (t *taskQueue) enqueue(task managerTask) {
t.lock.Lock()
task.id = t.nextTaskID
t.nextTaskID++
t.log.WriteF("Enqueuing new %s %s task for backend `%s' with id %d", task.reason, task.kind, task.source.Core.Name, task.id)
t.data = append(t.data, task)
t.data.sort()
t.lock.Unlock()
time.AfterFunc(time.Until(task.runTime), func() {
t.lock.Lock()
defer t.lock.Unlock()
foundTask := t.data.findTaskWithID(task.id)
if foundTask == nil {
t.log.WriteF("Skipping marking task as ready because it has been removed pre-emptively (id %d)",
task.id)
return
}
if t.data.sameTaskExistsAndReady(foundTask) || t.running.sameTaskExistsAndReady(foundTask) {
t.log.WriteF("Marking %s %s task for backend `%s' as to skip (id %d)",
foundTask.reason, foundTask.kind, foundTask.source.Core.Name, task.id)
foundTask.state = queueTaskStateSkip
} else {
t.log.WriteF("Marking %s %s task for backend `%s' as ready (id %d)",
foundTask.reason, foundTask.kind, foundTask.source.Core.Name, task.id)
foundTask.state = queueTaskStateReady
}
t.data.sort()
t.cond.Signal()
})
}
func (t managerTasks) idxWithID(id uint) int {
var ret int = -1
for i := range t {
if t[i].id == id {
ret = i
break
}
}
return ret
}
//sort priority:
// 1. skip<ready<pending
// 2. auth before refresh if both are ready
// 3. scheduled time
// 4. id
func (t managerTasks) sort() {
sort.Slice(t, func(i, j int) bool {
if t[i].state != t[j].state {
return t[i].state > t[j].state
}
if t[i].kind != t[j].kind {
return t[i].kind < t[j].kind
}
if !t[i].runTime.Equal(t[j].runTime) {
return t[i].runTime.Before(t[j].runTime)
}
return t[i].id < t[j].id
})
}
//If the queue order is shuffled in any way after a call to this function, the
// returned pointer is invalidated. Therefore, you should only call this and
// manipulate the returned object while you are holding the lock
func (t managerTasks) findTaskWithID(id uint) *managerTask {
var ret *managerTask
if idx := t.idxWithID(id); idx >= 0 {
ret = &t[idx]
}
return ret
}
//no lock
//considered the same task if the associated source core has the same name, and
// the kind of task is the same. Considered ready if the ready member of the task
// is true.
func (t managerTasks) sameTaskExistsAndReady(task *managerTask) bool {
for i := range t {
if t[i].source.Core.Name == task.source.Core.Name &&
t[i].kind == task.kind &&
t[i].state == queueTaskStateReady {
return true
}
}
return false
}
func (t *managerTasks) deleteTaskWithID(id uint) {
if idx := t.idxWithID(id); idx >= 0 {
(*t)[idx] = (*t)[len(*t)-1]
*t = (*t)[:len(*t)-1]
(*t).sort()
}
}
func (t *taskQueue) dequeueNoLock() managerTask {
ret := t.data[0]
t.data[0] = t.data[len(t.data)-1]
t.data = t.data[:len(t.data)-1]
t.data.sort()
return ret
}
func (t *taskQueue) empty() bool {
return len(t.data) == 0
}
func (t *taskQueue) start() {
workerFactory := newTaskWorkerFactory(t, t.globalCache, t.log)
for i := uint(0); i < t.numWorkers; i++ {
t.workers = append(t.workers, workerFactory.newWorker())
t.workers[i].consumeScheduler()
}
}
type SchedulerState struct {
Running []SchedulerTask `json:"running"`
Pending []SchedulerTask `json:"pending"`
Workers []WorkerDump `json:"workers"`
}
func (s SchedulerState) String() string {
b, _ := json.Marshal(s)
bOut := bytes.Buffer{}
json.Indent(&bOut, b, "", " ")
return bOut.String()
}
type SchedulerTask struct {
ID uint `json:"id"`
At time.Time `json:"at"`
Backend string `json:"backend"`
Reason string `json:"reason"`
Kind string `json:"kind"`
State string `json:"state"`
WorkerID int `json:"worker"`
}
type WorkerDump struct {
ID uint `json:"id"`
State string `json:"state"`
StateAt time.Time `json:"state_at"`
}
func (t *taskQueue) dumpState() SchedulerState {
t.lock.Lock()
defer t.lock.Unlock()
return t.dumpStateNoLock()
}
func (t *taskQueue) dumpStateNoLock() SchedulerState {
ret := SchedulerState{
Running: []SchedulerTask{},
Pending: []SchedulerTask{},
}
for _, task := range t.running {
ret.Running = append(ret.Running, SchedulerTask{
ID: task.id,
At: task.runTime,
Backend: task.source.Core.Name,
Reason: task.reason.String(),
Kind: task.kind.String(),
State: task.state.String(),
WorkerID: int(task.assignedWorker.id),
})
}
for _, task := range t.data {
ret.Pending = append(ret.Pending, SchedulerTask{
ID: task.id,
At: task.runTime,
Backend: task.source.Core.Name,
Reason: task.reason.String(),
Kind: task.kind.String(),
State: task.state.String(),
WorkerID: -1,
})
}
for _, worker := range t.workers {
state, stateAt := worker.State()
ret.Workers = append(ret.Workers, WorkerDump{
ID: worker.id,
State: state.String(),
StateAt: stateAt,
})
}
return ret
}