-
Notifications
You must be signed in to change notification settings - Fork 25
feat: Implement RandomQueue scheduler strategy #1914
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 6 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
3d8b1a4
feat: Add queue based scheduler
erezrokah a261b70
test: Fix tests
erezrokah 215ffbe
chore: Cleanup
erezrokah 0a60b22
Implement random queue scheduler strategy.
marianogappa 9c58946
Remove commented lines. Change incorrect const name.
marianogappa 6869f4e
Implement review comments.
marianogappa 3748166
Implement review comment: shuffle-queue rename.
marianogappa 2977ae3
Merge branch 'main' into mariano/priority-queue-changes
marianogappa File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,4 @@ | ||
package scheduler | ||
package metrics | ||
|
||
import "testing" | ||
|
||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
package queue | ||
|
||
import ( | ||
"sync" | ||
"sync/atomic" | ||
) | ||
|
||
// activeWorkSignal is a thread-safe coordinator for awaiting a worker pool | ||
// that relies on a queue that might be temporarily empty. | ||
// | ||
// If queue is empty and workers idle, done! | ||
// | ||
// If the queue is empty but a worker is working on a task, we must wait and check | ||
// if it's empty after that worker finishes. That's why we need this. | ||
// | ||
// Use it like this: | ||
// | ||
// - When a worker picks up a task, call `Add()` (like a WaitGroup) | ||
// - When a worker finishes a task, call `Done()` (like a WaitGroup) | ||
// | ||
// - If the queue is empty, check `IsIdle()` to check if no workers are active. | ||
// - If workers are still active, call `Wait()` to block until state changes. | ||
type activeWorkSignal struct { | ||
countChangeSignal *sync.Cond | ||
activeWorkUnitCount *atomic.Int32 | ||
isStarted *atomic.Bool | ||
} | ||
|
||
func newActiveWorkSignal() *activeWorkSignal { | ||
return &activeWorkSignal{ | ||
countChangeSignal: sync.NewCond(&sync.Mutex{}), | ||
activeWorkUnitCount: &atomic.Int32{}, | ||
isStarted: &atomic.Bool{}, | ||
} | ||
} | ||
|
||
// Add means a worker has started working on a task. | ||
// | ||
// Wake up the work queuing goroutine. | ||
func (s *activeWorkSignal) Add() { | ||
s.activeWorkUnitCount.Add(1) | ||
s.isStarted.Store(true) | ||
s.countChangeSignal.Signal() | ||
} | ||
|
||
// Done means a worker has finished working on a task. | ||
// | ||
// If the count became zero, wake up the work queuing goroutine (might have finished). | ||
func (s *activeWorkSignal) Done() { | ||
s.activeWorkUnitCount.Add(-1) | ||
s.countChangeSignal.Signal() | ||
} | ||
|
||
// IsIdle returns true if no workers are active. If queue is empty and workers idle, done! | ||
func (s *activeWorkSignal) IsIdle() bool { | ||
return s.isStarted.Load() && s.activeWorkUnitCount.Load() <= 0 | ||
} | ||
|
||
// Wait blocks until the count of active workers changes. | ||
func (s *activeWorkSignal) Wait() { | ||
if s.activeWorkUnitCount.Load() <= 0 { | ||
return | ||
} | ||
s.countChangeSignal.L.Lock() | ||
defer s.countChangeSignal.L.Unlock() | ||
s.countChangeSignal.Wait() | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
package queue | ||
|
||
import ( | ||
"math/rand" | ||
"sync" | ||
) | ||
|
||
// ConcurrentRandomQueue is a generic, thread-safe queue | ||
// that pops random elements in O(1) time. | ||
type ConcurrentRandomQueue[T any] struct { | ||
mu sync.Mutex | ||
queue []T | ||
random *rand.Rand | ||
} | ||
|
||
func NewConcurrentRandomQueue[T any](seed int64, capacityHint int) *ConcurrentRandomQueue[T] { | ||
return &ConcurrentRandomQueue[T]{queue: make([]T, 0, capacityHint), random: rand.New(rand.NewSource(seed))} | ||
} | ||
|
||
func (q *ConcurrentRandomQueue[T]) Push(item T) { | ||
q.mu.Lock() | ||
defer q.mu.Unlock() | ||
|
||
q.queue = append(q.queue, item) | ||
} | ||
|
||
func (q *ConcurrentRandomQueue[T]) Pop() *T { | ||
q.mu.Lock() | ||
defer q.mu.Unlock() | ||
|
||
if len(q.queue) == 0 { | ||
return nil | ||
} | ||
idx := q.random.Intn(len(q.queue)) | ||
erezrokah marked this conversation as resolved.
Show resolved
Hide resolved
|
||
lastIdx := len(q.queue) - 1 | ||
q.queue[idx], q.queue[lastIdx] = q.queue[lastIdx], q.queue[idx] | ||
item := q.queue[lastIdx] | ||
q.queue = q.queue[:lastIdx] | ||
|
||
return &item | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,138 @@ | ||
package queue | ||
|
||
import ( | ||
"context" | ||
|
||
"github.com/cloudquery/plugin-sdk/v4/caser" | ||
"github.com/cloudquery/plugin-sdk/v4/scheduler/metrics" | ||
"github.com/cloudquery/plugin-sdk/v4/schema" | ||
"github.com/google/uuid" | ||
"github.com/rs/zerolog" | ||
"golang.org/x/sync/errgroup" | ||
) | ||
|
||
const DefaultWorkerCount = 1000 | ||
|
||
// WorkUnit is an atomic unit of work that the scheduler syncs. | ||
// | ||
// It is one table resolver (same as all other scheduler strategies). | ||
// | ||
// But if it is a non-top-level table, it is bound to a single parent resource. | ||
type WorkUnit struct { | ||
Table *schema.Table | ||
Client schema.ClientMeta | ||
Parent *schema.Resource | ||
} | ||
|
||
type Scheduler struct { | ||
workerCount int | ||
logger zerolog.Logger | ||
caser *caser.Caser | ||
deterministicCQID bool | ||
metrics *metrics.Metrics | ||
invocationID string | ||
seed int64 | ||
} | ||
|
||
type Option func(*Scheduler) | ||
|
||
func WithWorkerCount(workerCount int) Option { | ||
return func(d *Scheduler) { | ||
d.workerCount = workerCount | ||
} | ||
} | ||
|
||
func WithCaser(c *caser.Caser) Option { | ||
return func(d *Scheduler) { | ||
d.caser = c | ||
} | ||
} | ||
|
||
func WithDeterministicCQID(deterministicCQID bool) Option { | ||
return func(d *Scheduler) { | ||
d.deterministicCQID = deterministicCQID | ||
} | ||
} | ||
|
||
func WithInvocationID(invocationID string) Option { | ||
return func(d *Scheduler) { | ||
d.invocationID = invocationID | ||
} | ||
} | ||
|
||
func NewRandomQueueScheduler(logger zerolog.Logger, m *metrics.Metrics, seed int64, opts ...Option) *Scheduler { | ||
scheduler := &Scheduler{ | ||
logger: logger, | ||
metrics: m, | ||
workerCount: DefaultWorkerCount, | ||
caser: caser.New(), | ||
invocationID: uuid.New().String(), | ||
seed: seed, | ||
} | ||
|
||
for _, opt := range opts { | ||
opt(scheduler) | ||
} | ||
|
||
return scheduler | ||
} | ||
|
||
func (d *Scheduler) Sync(ctx context.Context, tableClients []WorkUnit, resolvedResources chan<- *schema.Resource) { | ||
if len(tableClients) == 0 { | ||
return | ||
} | ||
queue := NewConcurrentRandomQueue[WorkUnit](d.seed, len(tableClients)) | ||
for _, tc := range tableClients { | ||
queue.Push(tc) | ||
} | ||
|
||
jobs := make(chan *WorkUnit) | ||
activeWorkSignal := newActiveWorkSignal() | ||
|
||
// Worker pool | ||
workerPool, _ := errgroup.WithContext(ctx) | ||
for w := 0; w < d.workerCount; w++ { | ||
workerPool.Go(func() error { | ||
newWorker( | ||
jobs, | ||
queue, | ||
resolvedResources, | ||
d.logger, | ||
d.caser, | ||
d.invocationID, | ||
d.deterministicCQID, | ||
d.metrics, | ||
).work(ctx, activeWorkSignal) | ||
return nil | ||
}) | ||
} | ||
|
||
// Work distribution | ||
go func() { | ||
defer close(jobs) | ||
for { | ||
select { | ||
case <-ctx.Done(): | ||
return | ||
default: | ||
item := queue.Pop() | ||
|
||
// There is work to do | ||
if item != nil { | ||
jobs <- item | ||
continue | ||
} | ||
|
||
// Queue is empty and no active work, done! | ||
if activeWorkSignal.IsIdle() { | ||
return | ||
} | ||
|
||
// Queue is empty and there is active work, wait for changes | ||
activeWorkSignal.Wait() | ||
} | ||
} | ||
}() | ||
|
||
_ = workerPool.Wait() | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice 🚀 Much better than what I did before 🙈