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
|
// Copyright 2024 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
package dispatcher
import (
"context"
"io"
"sync"
"time"
"github.com/google/syzkaller/pkg/log"
"github.com/google/syzkaller/pkg/stat"
)
type Instance interface {
io.Closer
}
type UpdateInfo func(cb func(info *Info))
type Runner[T Instance] func(ctx context.Context, inst T, updInfo UpdateInfo)
type CreateInstance[T Instance] func(int) (T, error)
// Pool[T] provides the functionality of a generic pool of instances.
// The instance is assumed to boot, be controlled by one Runner and then be re-created.
// The pool is assumed to have one default Runner (e.g. to be used for fuzzing), while a
// dynamically controlled sub-pool might be reserved for the arbitrary Runners.
type Pool[T Instance] struct {
BootErrors chan error
BootTime stat.AverageValue[time.Duration]
creator CreateInstance[T]
defaultJob Runner[T]
jobs chan Runner[T]
// The mutex serializes ReserveForRun() and SetDefault() calls.
mu *sync.Mutex
cv *sync.Cond
instances []*poolInstance[T]
paused bool
}
func NewPool[T Instance](count int, creator CreateInstance[T], def Runner[T]) *Pool[T] {
instances := make([]*poolInstance[T], count)
for i := 0; i < count; i++ {
inst := &poolInstance[T]{
job: def,
idx: i,
}
inst.reset(func() {})
instances[i] = inst
}
mu := new(sync.Mutex)
return &Pool[T]{
BootErrors: make(chan error, 16),
creator: creator,
defaultJob: def,
instances: instances,
jobs: make(chan Runner[T]),
mu: mu,
cv: sync.NewCond(mu),
}
}
// UpdateDefault forces all VMs to restart.
func (p *Pool[T]) SetDefault(def Runner[T]) {
p.mu.Lock()
defer p.mu.Unlock()
p.defaultJob = def
p.kickDefault()
}
func (p *Pool[T]) kickDefault() {
for _, inst := range p.instances {
if !inst.reserved() {
inst.free(p.defaultJob)
}
}
}
func (p *Pool[T]) TogglePause(paused bool) {
p.mu.Lock()
defer p.mu.Unlock()
p.paused = paused
if paused {
p.kickDefault()
} else {
p.cv.Broadcast()
}
}
func (p *Pool[T]) waitUnpaused() {
p.mu.Lock()
defer p.mu.Unlock()
for p.paused {
p.cv.Wait()
}
}
func (p *Pool[T]) Loop(ctx context.Context) {
var wg sync.WaitGroup
wg.Add(len(p.instances))
for _, inst := range p.instances {
inst := inst
go func() {
for ctx.Err() == nil {
p.runInstance(ctx, inst)
}
wg.Done()
}()
}
wg.Wait()
}
func (p *Pool[T]) runInstance(ctx context.Context, inst *poolInstance[T]) {
p.waitUnpaused()
ctx, cancel := context.WithCancel(ctx)
log.Logf(2, "pool: booting instance %d", inst.idx)
inst.reset(cancel)
start := time.Now()
inst.status(StateBooting)
defer inst.status(StateOffline)
obj, err := p.creator(inst.idx)
if err != nil {
p.BootErrors <- err
return
}
defer obj.Close()
p.BootTime.Save(time.Since(start))
inst.status(StateWaiting)
// The job and jobChan fields are subject to concurrent updates.
inst.mu.Lock()
job, jobChan := inst.job, inst.jobChan
inst.mu.Unlock()
if job == nil {
select {
case newJob := <-jobChan:
job = newJob
case newJob := <-inst.switchToJob:
job = newJob
case <-ctx.Done():
return
}
}
inst.status(StateRunning)
job(ctx, obj, inst.updateInfo)
}
// ReserveForRun specifies the size of the sub-pool for the execution of custom runners.
// The reserved instances will be booted, but the pool will not start the default runner.
// To unreserve all instances, execute ReserveForRun(0).
func (p *Pool[T]) ReserveForRun(count int) {
p.mu.Lock()
defer p.mu.Unlock()
if count > len(p.instances) {
panic("trying to reserve more VMs than present")
}
var free, reserved []*poolInstance[T]
for _, inst := range p.instances {
if inst.reserved() {
reserved = append(reserved, inst)
} else {
free = append(free, inst)
}
}
needReserve := count - len(reserved)
for i := 0; i < needReserve; i++ {
log.Logf(2, "pool: reserving instance %d", free[i].idx)
free[i].reserve(p.jobs)
}
needFree := len(reserved) - count
for i := 0; i < needFree; i++ {
log.Logf(2, "pool: releasing instance %d", reserved[i].idx)
reserved[i].free(p.defaultJob)
}
}
// Run blocks until it has found an instance to execute job and until job has finished.
func (p *Pool[T]) Run(job Runner[T]) {
done := make(chan struct{})
p.jobs <- func(ctx context.Context, inst T, upd UpdateInfo) {
job(ctx, inst, upd)
close(done)
}
<-done
}
func (p *Pool[T]) Total() int {
return len(p.instances)
}
type Info struct {
State InstanceState
Status string
LastUpdate time.Time
Reserved bool
// The optional callbacks.
MachineInfo func() []byte
DetailedStatus func() []byte
}
func (p *Pool[T]) State() []Info {
p.mu.Lock()
defer p.mu.Unlock()
ret := make([]Info, len(p.instances))
for i, inst := range p.instances {
ret[i] = inst.getInfo()
}
return ret
}
// poolInstance is not thread safe.
type poolInstance[T Instance] struct {
mu sync.Mutex
info Info
idx int
// Either job or jobChan will be set.
job Runner[T]
jobChan chan Runner[T]
switchToJob chan Runner[T]
stop func()
}
type InstanceState int
const (
StateOffline InstanceState = iota
StateBooting
StateWaiting
StateRunning
)
// reset() and status() may be called concurrently to all other methods.
// Other methods themselves are serialized.
func (pi *poolInstance[T]) reset(stop func()) {
pi.mu.Lock()
defer pi.mu.Unlock()
pi.info = Info{
State: StateOffline,
LastUpdate: time.Now(),
Reserved: pi.info.Reserved,
}
pi.stop = stop
pi.switchToJob = make(chan Runner[T])
}
func (pi *poolInstance[T]) updateInfo(upd func(*Info)) {
pi.mu.Lock()
defer pi.mu.Unlock()
upd(&pi.info)
pi.info.LastUpdate = time.Now()
}
func (pi *poolInstance[T]) status(status InstanceState) {
pi.updateInfo(func(info *Info) {
info.State = status
})
}
func (pi *poolInstance[T]) reserved() bool {
return pi.jobChan != nil
}
func (pi *poolInstance[T]) getInfo() Info {
pi.mu.Lock()
defer pi.mu.Unlock()
return pi.info
}
func (pi *poolInstance[T]) reserve(ch chan Runner[T]) {
pi.mu.Lock()
// If we don't take the lock, it's possible that instance restart would race with job/jobChan update.
pi.stop()
pi.jobChan = ch
pi.job = nil
pi.info.Reserved = true
pi.mu.Unlock()
}
func (pi *poolInstance[T]) free(job Runner[T]) {
pi.mu.Lock()
if pi.job != nil {
// A change of a default job, let's force restart the instance.
pi.stop()
}
pi.job = job
pi.jobChan = nil
switchToJob := pi.switchToJob
pi.info.Reserved = false
pi.mu.Unlock()
select {
case switchToJob <- job:
// Just in case the instance has been waiting.
return
default:
}
}
|