-
Notifications
You must be signed in to change notification settings - Fork 0
/
balancer.go
218 lines (179 loc) · 4.57 KB
/
balancer.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
package go_balancer
import "sync"
type runnable interface {
// Run() is the function that will be executed by the load balancer.
Run()
}
// one item in the queue
type queueItem[T runnable] struct {
lck *sync.Mutex
id int
item T
isRunning bool
}
type loadBalancer[T runnable] struct {
// Makes sure that the job ID is unique
ids int
// Lock for accessing ids variable
idlck *sync.Mutex
// Queue of jobs
l []*queueItem[T]
// Lock for accessing queue l
// qlck should only be acquired by functions implemented for queue
qlck *sync.Mutex
// Maximal number of jobs to execute at the same time
executeNjobs int
// Total number of jobs running now
totalRunningJobs int
// Lock for accessing totalRunningJobs varialbe
statslck *sync.Mutex
// WaitGroup for waiting for all jobs to finish
universalWg *sync.WaitGroup
}
// Config is a struct that holds the initial configurations for the load balancer.
type Config[T any] struct {
// Execute is a function that gets executed on the queue.
// Execute func(v *T) error
// Load Balancer will Execute at max N jobs at the same time.
MaxJobsToExecuteAtSameTime int
}
// NewGoBalancer() returns a new load balancer instance.
func NewGoBalancer[T runnable](c Config[T]) *loadBalancer[T] {
if c.MaxJobsToExecuteAtSameTime <= 0 {
c.MaxJobsToExecuteAtSameTime = 1
}
return &loadBalancer[T]{
executeNjobs: c.MaxJobsToExecuteAtSameTime,
ids: 0,
idlck: &sync.Mutex{},
l: []*queueItem[T]{},
qlck: &sync.Mutex{},
statslck: &sync.Mutex{},
universalWg: &sync.WaitGroup{},
}
}
// AddJob() adds a new job to the load balancer queue. If the number of jobs running is less than the maximum number
// of jobs to execute at the same time, the job will be executed immediately. Otherwise, the job will be added to the queue.
// And will be executed when a slot gets freed.
// The function returns the job ID.
func (lb *loadBalancer[T]) AddJob(item T) int {
jobID := lb.newJobID()
lb.addToQueue(queueItem[T]{
lck: &sync.Mutex{},
id: jobID,
item: item,
isRunning: false})
if lb.hasFreeSlot() {
// execute job
lb.execute(jobID)
}
return jobID
}
// RemoveJobByID() removes a job from the queue by its ID.
// The function returns the removed job.
func (lb *loadBalancer[T]) RemoveJobByID(ID int) *T {
return lb.removeFromQueue(ID)
}
// TotalJobs() returns the total number of jobs.
func (lb *loadBalancer[T]) TotalJobs() int {
lb.qlck.Lock()
defer lb.qlck.Unlock()
return len(lb.l)
}
// TotalJobs() returns the total number of running jobs.
func (lb *loadBalancer[T]) TotalRunningJobs() int {
lb.qlck.Lock()
defer lb.qlck.Unlock()
return len(lb.l)
}
func (lb *loadBalancer[T]) WaitForRunningJobs() {
lb.universalWg.Wait()
}
// newJobID() returns a new unique job ID.
func (lb *loadBalancer[T]) newJobID() int {
lb.idlck.Lock()
defer lb.idlck.Unlock()
lb.ids++
return lb.ids
}
func (lb *loadBalancer[T]) incTotalRunningJobs() {
lb.statslck.Lock()
lb.totalRunningJobs++
lb.statslck.Unlock()
}
func (lb *loadBalancer[T]) decTotalRunningJobs() {
lb.statslck.Lock()
lb.totalRunningJobs--
lb.statslck.Unlock()
}
func (lb *loadBalancer[T]) triggerScheduler() {
if lb.hasFreeSlot() {
id := lb.nextScheduledJobID()
// All jobs are running
if id <= 0 {
return
}
lb.execute(id)
}
}
func (lb *loadBalancer[T]) nextScheduledJobID() int {
for _, v := range lb.l {
if !v.isRunning {
return v.id
}
}
return -1
}
// execute() executes the job.
func (lb *loadBalancer[T]) execute(jobID int) {
lb.universalWg.Add(1)
defer lb.universalWg.Done()
lb.incTotalRunningJobs()
defer lb.decTotalRunningJobs()
var index int = -1
for i, v := range lb.l {
if v.id == jobID {
if v.isRunning {
return
} else {
index = i
break
}
}
}
if index == -1 {
return
}
lb.l[index].lck.Lock()
lb.l[index].isRunning = true
lb.l[index].item.Run()
// After job is done, remove it from the queue and trigger the scheduler.
lb.l[index].isRunning = false
lb.l[index].lck.Unlock()
lb.removeFromQueue(jobID)
lb.triggerScheduler()
}
func (lb *loadBalancer[T]) addToQueue(item queueItem[T]) {
lb.qlck.Lock()
lb.l = append(lb.l, &item)
lb.qlck.Unlock()
}
func (lb *loadBalancer[T]) removeFromQueue(ID int) *T {
for i, v := range lb.l {
if v.id == ID {
lb.qlck.Lock()
lb.l = append(lb.l[:i], lb.l[i+1:]...)
lb.qlck.Unlock()
return &v.item
}
}
return nil
}
func (lb *loadBalancer[T]) hasFreeSlot() bool {
lb.statslck.Lock()
defer lb.statslck.Unlock()
return lb.totalRunningJobs < lb.executeNjobs
}
func toPtr[T any](v T) *T {
return &v
}