/
manage_subs.go
341 lines (291 loc) · 9.46 KB
/
manage_subs.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
329
330
331
332
333
334
335
336
337
338
339
340
341
package eventstojobs
import (
"context"
"fmt"
"io"
"strings"
"sync"
"time"
log "github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
"github.com/armadaproject/armada/internal/jobservice/events"
"github.com/armadaproject/armada/internal/jobservice/repository"
"github.com/armadaproject/armada/pkg/api"
)
type JobSetSubscription struct {
repository.JobSetKey
fromMessageId string
sqlJobService repository.SQLJobService
eventReader events.JobEventReader
ctx context.Context
cancel context.CancelFunc
subTimeout time.Duration
subDoneChan chan<- *repository.JobSetKey
}
type JobSetSubscriptionExecutor struct {
ctx context.Context
sqlJobService repository.SQLJobService
eventReader events.JobEventReader
subscriptions map[repository.JobSetKey]*JobSetSubscription
mutex sync.Mutex
newSubChan <-chan *repository.SubscribedTuple
subDoneChan chan *repository.JobSetKey
subTimeout time.Duration
}
func NewJobSetSubscriptionExecutor(ctx context.Context,
eventReader events.JobEventReader,
sqlJobService repository.SQLJobService,
newSubChan <-chan *repository.SubscribedTuple,
subTimeout time.Duration,
) *JobSetSubscriptionExecutor {
return &JobSetSubscriptionExecutor{
ctx: ctx,
eventReader: eventReader,
sqlJobService: sqlJobService,
subscriptions: make(map[repository.JobSetKey]*JobSetSubscription),
newSubChan: newSubChan,
subDoneChan: make(chan *repository.JobSetKey, 1000),
subTimeout: subTimeout,
}
}
func (jse *JobSetSubscriptionExecutor) Manage() {
go jse.ScanForMissingSubscriptions()
// Main {un}subscribe loop.
for {
select {
case <-jse.ctx.Done():
log.Debug("Context is done.")
return
case newSubInfo := <-jse.newSubChan:
jse.addSubscription(newSubInfo)
err := jse.launchSubscriber(&newSubInfo.JobSetKey)
if err != nil {
log.WithError(err).Error("JobSet subscribe error")
}
case subDoneKey := <-jse.subDoneChan:
log.Infof("Removing subscription on %s/%s", subDoneKey.Queue, subDoneKey.JobSetId)
err := jse.removeSubscription(subDoneKey)
if err != nil {
log.WithError(err).Error("JobSet unsubscribe error")
}
}
}
}
// Looks for subscriptions that show as active in the DB but are not active
// in this executor.
func (jse *JobSetSubscriptionExecutor) ScanForMissingSubscriptions() {
nextScan := time.After(1 * time.Nanosecond)
for {
select {
case <-jse.ctx.Done():
return
case <-nextScan:
scanStart := time.Now()
subscriptions, err := jse.sqlJobService.GetSubscribedJobSets(jse.ctx)
if err != nil {
log.WithError(err).Error("error getting subscribed job sets")
nextScan = time.After(60 * time.Second)
continue
}
for _, sub := range subscriptions {
// Adding an already existing subscription is a no-op.
jse.addSubscription(&sub)
}
scanEnd := time.Now()
duration := scanEnd.Sub(scanStart)
log.Infof("Scan for missing subs took %s", duration.String())
log.Infof("There are %d active jobset subscriptions", jse.NumActiveSubscriptions())
nextScan = time.After(60 * time.Second)
}
}
}
func (jse *JobSetSubscriptionExecutor) addSubscription(sub *repository.SubscribedTuple) {
jse.mutex.Lock()
defer jse.mutex.Unlock()
_, ok := jse.subscriptions[sub.JobSetKey]
if ok {
// TODO: What to do if subscription already exists locally?
// Restart it? Do nothing?
} else { // sub doesn't already exist.
jse.subscriptions[sub.JobSetKey] = NewJobSetSubscription(
jse.ctx,
jse.eventReader,
sub,
jse.subTimeout,
jse.subDoneChan,
jse.sqlJobService)
err := jse.sqlJobService.SubscribeJobSet(jse.ctx, sub.Queue, sub.JobSetId, sub.FromMessageId)
if err != nil {
log.Errorf("Could not add subscription on %s/%s to DB: %s", sub.Queue, sub.JobSetId, err.Error())
}
}
}
func (jse *JobSetSubscriptionExecutor) launchSubscriber(key *repository.JobSetKey) error {
jse.mutex.Lock()
sub, ok := jse.subscriptions[*key]
jse.mutex.Unlock()
if ok {
go sub.Subscribe() //nolint:errcheck
return nil
}
return fmt.Errorf("No subscription with specified key %s/%s exists!", sub.Queue, sub.JobSetId)
}
func (jse *JobSetSubscriptionExecutor) removeSubscription(key *repository.JobSetKey) error {
jse.mutex.Lock()
defer jse.mutex.Unlock()
sub, ok := jse.subscriptions[*key]
if ok {
sub.cancel()
delete(jse.subscriptions, *key)
} else {
log.Errorf("No subscription with specified key %s/%s exists!", key.Queue, key.JobSetId)
}
_, err := jse.sqlJobService.UnsubscribeJobSet(jse.ctx, key.Queue, key.JobSetId)
return err
}
func (jse *JobSetSubscriptionExecutor) HasSubscription(key *repository.JobSetKey) bool {
jse.mutex.Lock()
defer jse.mutex.Unlock()
_, ok := jse.subscriptions[*key]
return ok
}
func (jse *JobSetSubscriptionExecutor) NumActiveSubscriptions() int {
jse.mutex.Lock()
defer jse.mutex.Unlock()
return len(jse.subscriptions)
}
func NewJobSetSubscription(ctx context.Context,
eventReader events.JobEventReader,
subInfo *repository.SubscribedTuple,
subTimeout time.Duration,
subDoneChan chan<- *repository.JobSetKey,
sqlJobService repository.SQLJobService,
) *JobSetSubscription {
newCtx, cancel := context.WithCancel(ctx)
return &JobSetSubscription{
ctx: newCtx,
cancel: cancel,
eventReader: eventReader,
JobSetKey: subInfo.JobSetKey,
fromMessageId: subInfo.FromMessageId,
subTimeout: subTimeout,
subDoneChan: subDoneChan,
sqlJobService: sqlJobService,
}
}
func (js *JobSetSubscription) Subscribe() error {
requestFields := log.Fields{
"job_set_id": js.JobSetId,
"queue": js.Queue,
"from_message_id": js.fromMessageId,
}
defer func() {
js.subDoneChan <- &repository.JobSetKey{
Queue: js.Queue,
JobSetId: js.JobSetId,
}
log.WithFields(requestFields).Debugf("Sent message to subDoneChan")
}()
log.WithFields(requestFields).Debugf("Calling GetJobEventMessage")
stream, err := js.eventReader.GetJobEventMessage(js.ctx, &api.JobSetRequest{
Id: js.JobSetId,
Queue: js.Queue,
Watch: true,
FromMessageId: js.fromMessageId,
})
if err != nil {
log.WithFields(requestFields).WithError(err).Error("error from GetJobEventMessage")
return err
}
log.WithFields(requestFields).Debug("Got stream")
g, _ := errgroup.WithContext(js.ctx)
// Subscription status check ticker.
timeout := time.NewTicker(js.subTimeout)
g.Go(func() error {
for {
select {
case <-js.ctx.Done():
return nil
case <-timeout.C:
log.WithFields(requestFields).Debug("JobSetSubscription.Subscribe checking subscription status")
// Stream is created with *our* context, therefore if we cancel, stream.Recv() should bail out too.
unsub, err := js.sqlJobService.CheckToUnSubscribe(js.ctx, js.Queue, js.JobSetId, js.subTimeout)
if err != nil {
log.WithFields(requestFields).WithError(err).Error("IsJobSetSubscribed error")
}
// We should unsubscribe
if unsub {
log.WithFields(requestFields).Info("subscription done")
js.cancel()
return nil
}
}
}
})
// Nanosecond, zero wait essentially.
g.Go(func() error {
nextRecv := time.After(1 * time.Nanosecond)
defer func() {
js.cancel()
log.WithFields(requestFields).Debugf("Called cancel")
}()
// this loop will run until the context is canceled
for {
select {
case <-js.ctx.Done():
log.WithFields(requestFields).Debug("context is done")
return nil
case <-nextRecv:
msg, err := stream.Recv()
if err != nil {
if strings.Contains(err.Error(), io.EOF.Error()) {
log.WithFields(requestFields).Info("Reached stream end for JobSetSubscription")
return nil
} else if strings.Contains(err.Error(), "context canceled") {
// The select case will handle context being done/canceled.
continue
}
log.WithFields(requestFields).WithError(err).Error("could not obtain job set event message, retrying")
settingSubscribeErr := js.sqlJobService.SetSubscriptionError(
js.ctx, js.Queue, js.JobSetId, err.Error(), js.fromMessageId)
if settingSubscribeErr != nil {
log.WithFields(requestFields).WithError(settingSubscribeErr).Error("could not set error field in job set table")
}
nextRecv = time.After(5 * time.Second)
continue
}
errClear := js.sqlJobService.AddMessageIdAndClearSubscriptionError(
js.ctx, js.Queue, js.JobSetId, js.fromMessageId)
if errClear != nil {
log.WithFields(requestFields).WithError(errClear).Error("could not clear subscription error from job set table")
}
currentJobId := api.JobIdFromApiEvent(msg.Message)
jobStatus := EventsToJobResponse(*msg.Message)
if jobStatus != nil {
log.WithFields(requestFields).WithFields(log.Fields{
"job_id": currentJobId,
"job_status": jobStatus.GetState().String(),
}).Debug("Got event")
jobStatus := repository.NewJobStatus(js.Queue, js.JobSetId, currentJobId, *jobStatus)
err := js.sqlJobService.UpdateJobServiceDb(js.ctx, jobStatus)
if err != nil {
log.WithFields(requestFields).WithError(err).Error("could not update job status, retrying")
nextRecv = time.After(5 * time.Second)
continue
}
} else {
log.WithFields(requestFields).WithFields(log.Fields{
"job_id": currentJobId,
"message": msg.Message,
}).Debug("Got non-status event")
}
// advance the message id for next loop
js.fromMessageId = msg.GetId()
requestFields["from_message_id"] = js.fromMessageId
// Nanosecond, essentially go again now.
nextRecv = time.After(1 * time.Nanosecond)
}
}
})
return g.Wait()
}