-
Notifications
You must be signed in to change notification settings - Fork 659
/
state.go
323 lines (286 loc) · 8.36 KB
/
state.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
// Copyright (C) 2019-2021, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package queue
import (
"fmt"
"github.com/ava-labs/avalanchego/cache"
"github.com/ava-labs/avalanchego/cache/metercacher"
"github.com/ava-labs/avalanchego/database"
"github.com/ava-labs/avalanchego/database/linkeddb"
"github.com/ava-labs/avalanchego/database/prefixdb"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/utils/wrappers"
"github.com/prometheus/client_golang/prometheus"
)
const (
dependentsCacheSize = 1024
jobsCacheSize = 2048
)
var (
runnableJobIDsPrefix = []byte("runnable")
jobsPrefix = []byte("jobs")
dependenciesPrefix = []byte("dependencies")
missingJobIDsPrefix = []byte("missing job IDs")
metadataPrefix = []byte("metadata")
numJobsKey = []byte("numJobs")
)
type state struct {
parser Parser
runnableJobIDs linkeddb.LinkedDB
cachingEnabled bool
jobsCache cache.Cacher
jobsDB database.Database
// Should be prefixed with the jobID that we are attempting to find the
// dependencies of. This prefixdb.Database should then be wrapped in a
// linkeddb.LinkedDB to read the dependencies.
dependenciesDB database.Database
// This is a cache that tracks LinkedDB iterators that have recently been
// made.
dependentsCache cache.Cacher
missingJobIDs linkeddb.LinkedDB
// This tracks the summary values of this state. Currently, this only
// contains the last known checkpoint of how many jobs are currently in the
// queue to execute.
metadataDB database.Database
// This caches the number of jobs that are currently in the queue to
// execute.
numJobs uint64
}
func newState(
db database.Database,
metricsNamespace string,
metricsRegisterer prometheus.Registerer,
) (*state, error) {
jobsCacheMetricsNamespace := fmt.Sprintf("%s_jobs_cache", metricsNamespace)
jobsCache, err := metercacher.New(jobsCacheMetricsNamespace, metricsRegisterer, &cache.LRU{Size: jobsCacheSize})
if err != nil {
return nil, fmt.Errorf("couldn't create metered cache: %w", err)
}
metadataDB := prefixdb.New(metadataPrefix, db)
jobs := prefixdb.New(jobsPrefix, db)
numJobs, err := getNumJobs(metadataDB, jobs)
if err != nil {
return nil, fmt.Errorf("couldn't initialize pending jobs: %w", err)
}
return &state{
runnableJobIDs: linkeddb.NewDefault(prefixdb.New(runnableJobIDsPrefix, db)),
cachingEnabled: true,
jobsCache: jobsCache,
jobsDB: jobs,
dependenciesDB: prefixdb.New(dependenciesPrefix, db),
dependentsCache: &cache.LRU{Size: dependentsCacheSize},
missingJobIDs: linkeddb.NewDefault(prefixdb.New(missingJobIDsPrefix, db)),
metadataDB: metadataDB,
numJobs: numJobs,
}, nil
}
func getNumJobs(d database.Database, jobs database.Iteratee) (uint64, error) {
numJobs, err := database.GetUInt64(d, numJobsKey)
if err == database.ErrNotFound {
// If we don't have a checkpoint, we need to initialize it.
count, err := database.Count(jobs)
return uint64(count), err
}
return numJobs, err
}
func (s *state) Clear() error {
var (
runJobsIter = s.runnableJobIDs.NewIterator()
jobsIter = s.jobsDB.NewIterator()
depsIter = s.dependenciesDB.NewIterator()
missJobsIter = s.missingJobIDs.NewIterator()
)
defer func() {
runJobsIter.Release()
jobsIter.Release()
depsIter.Release()
missJobsIter.Release()
}()
// clear runnableJobIDs
for runJobsIter.Next() {
if err := s.runnableJobIDs.Delete(runJobsIter.Key()); err != nil {
return err
}
}
// clear jobs
s.jobsCache.Flush()
for jobsIter.Next() {
if err := s.jobsDB.Delete(jobsIter.Key()); err != nil {
return err
}
}
// clear dependencies
s.dependentsCache.Flush()
for depsIter.Next() {
if err := s.dependenciesDB.Delete(depsIter.Key()); err != nil {
return err
}
}
// clear missing jobs IDs
for missJobsIter.Next() {
if err := s.missingJobIDs.Delete(missJobsIter.Key()); err != nil {
return err
}
}
// clear number of pending jobs
s.numJobs = 0
if err := database.PutUInt64(s.metadataDB, numJobsKey, s.numJobs); err != nil {
return err
}
errs := wrappers.Errs{}
errs.Add(
runJobsIter.Error(),
jobsIter.Error(),
depsIter.Error(),
missJobsIter.Error(),
)
return errs.Err
}
// AddRunnableJob adds [jobID] to the runnable queue
func (s *state) AddRunnableJob(jobID ids.ID) error {
return s.runnableJobIDs.Put(jobID[:], nil)
}
// HasRunnableJob returns true if there is a job that can be run on the queue
func (s *state) HasRunnableJob() (bool, error) {
isEmpty, err := s.runnableJobIDs.IsEmpty()
return !isEmpty, err
}
// RemoveRunnableJob fetches and deletes the next job from the runnable queue
func (s *state) RemoveRunnableJob() (Job, error) {
jobIDBytes, err := s.runnableJobIDs.HeadKey()
if err != nil {
return nil, err
}
if err := s.runnableJobIDs.Delete(jobIDBytes); err != nil {
return nil, err
}
jobID, err := ids.ToID(jobIDBytes)
if err != nil {
return nil, fmt.Errorf("couldn't convert job ID bytes to job ID: %w", err)
}
job, err := s.GetJob(jobID)
if err != nil {
return nil, err
}
if err := s.jobsDB.Delete(jobIDBytes); err != nil {
return job, err
}
// Guard rail to make sure we don't underflow.
if s.numJobs == 0 {
return job, nil
}
s.numJobs--
return job, database.PutUInt64(s.metadataDB, numJobsKey, s.numJobs)
}
// PutJob adds the job to the queue
func (s *state) PutJob(job Job) error {
id := job.ID()
if s.cachingEnabled {
s.jobsCache.Put(id, job)
}
if err := s.jobsDB.Put(id[:], job.Bytes()); err != nil {
return err
}
s.numJobs++
return database.PutUInt64(s.metadataDB, numJobsKey, s.numJobs)
}
// HasJob returns true if the job [id] is in the queue
func (s *state) HasJob(id ids.ID) (bool, error) {
if s.cachingEnabled {
if _, exists := s.jobsCache.Get(id); exists {
return true, nil
}
}
return s.jobsDB.Has(id[:])
}
// GetJob returns the job [id]
func (s *state) GetJob(id ids.ID) (Job, error) {
if s.cachingEnabled {
if job, exists := s.jobsCache.Get(id); exists {
return job.(Job), nil
}
}
jobBytes, err := s.jobsDB.Get(id[:])
if err != nil {
return nil, err
}
job, err := s.parser.Parse(jobBytes)
if err == nil && s.cachingEnabled {
s.jobsCache.Put(id, job)
}
return job, err
}
// AddDependency adds [dependent] as blocking on [dependency] being completed
func (s *state) AddDependency(dependency, dependent ids.ID) error {
dependentsDB := s.getDependentsDB(dependency)
return dependentsDB.Put(dependent[:], nil)
}
// RemoveDependencies removes the set of IDs that are blocking on the completion
// of [dependency] from the database and returns them.
func (s *state) RemoveDependencies(dependency ids.ID) ([]ids.ID, error) {
dependentsDB := s.getDependentsDB(dependency)
iterator := dependentsDB.NewIterator()
defer iterator.Release()
dependents := []ids.ID(nil)
for iterator.Next() {
dependentKey := iterator.Key()
if err := dependentsDB.Delete(dependentKey); err != nil {
return nil, err
}
dependent, err := ids.ToID(dependentKey)
if err != nil {
return nil, err
}
dependents = append(dependents, dependent)
}
return dependents, iterator.Error()
}
func (s *state) DisableCaching() {
s.dependentsCache.Flush()
s.jobsCache.Flush()
s.cachingEnabled = false
}
func (s *state) AddMissingJobIDs(missingIDs ids.Set) error {
for missingID := range missingIDs {
missingID := missingID
if err := s.missingJobIDs.Put(missingID[:], nil); err != nil {
return err
}
}
return nil
}
func (s *state) RemoveMissingJobIDs(missingIDs ids.Set) error {
for missingID := range missingIDs {
missingID := missingID
if err := s.missingJobIDs.Delete(missingID[:]); err != nil {
return err
}
}
return nil
}
func (s *state) MissingJobIDs() ([]ids.ID, error) {
iterator := s.missingJobIDs.NewIterator()
defer iterator.Release()
missingIDs := []ids.ID(nil)
for iterator.Next() {
missingID, err := ids.ToID(iterator.Key())
if err != nil {
return nil, err
}
missingIDs = append(missingIDs, missingID)
}
return missingIDs, nil
}
func (s *state) getDependentsDB(dependency ids.ID) linkeddb.LinkedDB {
if s.cachingEnabled {
if dependentsDBIntf, ok := s.dependentsCache.Get(dependency); ok {
return dependentsDBIntf.(linkeddb.LinkedDB)
}
}
dependencyDB := prefixdb.New(dependency[:], s.dependenciesDB)
dependentsDB := linkeddb.NewDefault(dependencyDB)
if s.cachingEnabled {
s.dependentsCache.Put(dependency, dependentsDB)
}
return dependentsDB
}