-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathSchedulePool.go
More file actions
460 lines (399 loc) · 12.5 KB
/
SchedulePool.go
File metadata and controls
460 lines (399 loc) · 12.5 KB
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
package schedules
import (
"strconv"
"sync"
"time"
"github.com/semaphoreui/semaphore/pkg/common_errors"
"github.com/semaphoreui/semaphore/services/server"
"github.com/semaphoreui/semaphore/util"
"github.com/robfig/cron/v3"
"github.com/semaphoreui/semaphore/db"
"github.com/semaphoreui/semaphore/db_lib"
"github.com/semaphoreui/semaphore/services/tasks"
log "github.com/sirupsen/logrus"
)
type ScheduleRunner struct {
projectID int
scheduleID int
pool *SchedulePool
encryptionService server.AccessKeyEncryptionService
keyInstaller db_lib.AccessKeyInstaller
}
type oneTimeSchedule struct {
runAt time.Time
ran bool
}
func (s *oneTimeSchedule) Next(t time.Time) time.Time {
if s.ran {
return time.Time{}
}
if !t.Before(s.runAt) {
s.ran = true
return time.Time{}
}
return s.runAt
}
func CreateScheduleRunner(
projectID int,
scheduleID int,
pool *SchedulePool,
encryptionService server.AccessKeyEncryptionService,
keyInstaller db_lib.AccessKeyInstaller,
) ScheduleRunner {
return ScheduleRunner{
projectID: projectID,
scheduleID: scheduleID,
pool: pool,
encryptionService: encryptionService,
keyInstaller: keyInstaller,
}
}
func (r ScheduleRunner) tryUpdateScheduleCommitHash(schedule db.Schedule) (updated bool, err error) {
repo, err := r.pool.store.GetRepository(schedule.ProjectID, *schedule.RepositoryID)
if err != nil {
return
}
err = r.pool.encryptionService.DeserializeSecret(&repo.SSHKey)
if err != nil {
return
}
remoteHash, err := db_lib.GitRepository{
Logger: nil,
TemplateID: schedule.TemplateID,
Repository: repo,
Client: db_lib.CreateDefaultGitClient(r.keyInstaller),
}.GetLastRemoteCommitHash()
if err != nil {
return
}
if schedule.LastCommitHash != nil && remoteHash == *schedule.LastCommitHash {
return
}
err = r.pool.store.SetScheduleCommitHash(schedule.ProjectID, schedule.ID, remoteHash)
if err != nil {
return
}
updated = true
return
}
func (r ScheduleRunner) Run() {
if !r.pool.store.PermanentConnection() {
r.pool.store.Connect("schedule " + strconv.Itoa(r.scheduleID))
defer r.pool.store.Close("schedule " + strconv.Itoa(r.scheduleID))
}
schedule, err := r.pool.store.GetSchedule(r.projectID, r.scheduleID)
if err != nil {
log.WithError(err).WithFields(log.Fields{
"context": common_errors.GetErrorContext(),
"project_id": r.projectID,
"schedule_id": r.scheduleID,
}).Error("failed to get schedule")
return
}
scheduleType := schedule.Type
if scheduleType == "" {
scheduleType = db.ScheduleTypeCron
}
if schedule.RepositoryID != nil {
var updated bool
updated, err = r.tryUpdateScheduleCommitHash(schedule)
if err != nil {
log.WithError(err).WithFields(log.Fields{
"context": common_errors.GetErrorContext(),
"project_id": r.projectID,
"schedule_id": r.scheduleID,
}).Error("failed to update schedule commit hash")
return
}
if !updated {
return
}
}
tpl, err := r.pool.store.GetTemplate(schedule.ProjectID, schedule.TemplateID)
if err != nil {
log.WithError(err).WithFields(log.Fields{
"context": common_errors.GetErrorContext(),
"project_id": schedule.ProjectID,
"schedule_id": schedule.ID,
"template_id": schedule.TemplateID,
}).Error("failed to get template")
return
}
// In HA mode, ensure only one node fires this schedule occurrence.
if r.pool.dedup != nil && !r.pool.dedup.TryLockExecution(r.scheduleID) {
log.WithFields(log.Fields{
"project_id": r.projectID,
"schedule_id": r.scheduleID,
}).Debug("schedule already executed by another node")
// For one-time schedules the winning node deactivates/deletes
// the schedule in the DB after execution. Refresh so this
// node's cron picks up that change and drops the stale entry.
if scheduleType == db.ScheduleTypeRunAt {
r.pool.Refresh()
}
return
}
task := schedule.TaskParams.CreateTask(schedule.TemplateID)
task.ScheduleID = &schedule.ID
_, err = r.pool.taskPool.AddTask(
task,
nil,
"",
schedule.ProjectID,
tpl.App.NeedTaskAlias(),
)
if err != nil {
log.WithError(err).WithFields(log.Fields{
"context": common_errors.GetErrorContext(),
"project_id": schedule.ProjectID,
"schedule_id": schedule.ID,
"template_id": schedule.TemplateID,
}).Error("failed to add task")
}
// For "RunAt" schedules, the schedule should only trigger once at the specified time and be deactivated afterwards.
// Calling Refresh here ensures that after the job has fired, the pool reloads the active schedules
// from the database (where this run-at schedule may now be disabled) so it is not executed again.
if scheduleType == db.ScheduleTypeRunAt {
r.pool.Refresh()
}
}
// ScheduleDeduplicator prevents the same schedule from being executed on
// multiple nodes simultaneously in an HA cluster. When configured, each
// ScheduleRunner calls TryLockExecution before creating a task.
//
// The deduplication lock is intended to cover a *single execution attempt*
// of a schedule occurrence: a node should acquire the lock immediately
// before creating a task and release it once the attempt has either
// completed or failed. Implementations are free to choose the underlying
// mechanism (in‑memory, database, distributed store, etc.), but they should
// be robust to node failures and process restarts (for example by using
// leases with automatic expiry).
//
// Callers MUST treat the lock as advisory and best‑effort: if the
// implementation becomes unavailable or releases the lock early, at‑most‑once
// execution across the cluster is not guaranteed.
type ScheduleDeduplicator interface {
// TryLockExecution attempts to acquire an execution lock for the given
// schedule occurrence.
//
// Lock duration:
// - The lock is expected to remain held for the duration of the current
// schedule execution attempt (from just before task creation until
// the attempt finishes or fails).
// - Implementations will typically release the lock explicitly when the
// attempt ends and/or rely on a lease with automatic expiry to avoid
// permanent deadlocks.
//
// Timeouts and crash behavior:
// - If the node that acquired the lock crashes or loses connectivity,
// the behavior is implementation‑specific. Recommended practice is to
// use a finite TTL/lease so that the lock eventually expires and
// future executions can proceed.
//
// Idempotency:
// - TryLockExecution may be called multiple times for the same
// scheduleID (for example, after retries or rescheduling). The
// implementation SHOULD behave idempotently such that, for a single
// schedule occurrence, at most one call across the cluster returns
// true.
//
// Returns true if this node successfully acquired the lock and should
// execute the schedule, and false otherwise.
TryLockExecution(scheduleID int) bool
}
type SchedulePool struct {
cron *cron.Cron
locker sync.Locker
dedup ScheduleDeduplicator
store db.Store
taskPool *tasks.TaskPool
encryptionService server.AccessKeyEncryptionService
keyInstaller db_lib.AccessKeyInstaller
}
// SetDeduplicator configures a distributed schedule deduplicator for HA mode.
// When set, only one node in the cluster fires each schedule occurrence.
func (p *SchedulePool) SetDeduplicator(d ScheduleDeduplicator) {
p.dedup = d
}
func (p *SchedulePool) init() {
loc, err := time.LoadLocation(util.Config.Schedule.Timezone)
if err != nil {
panic(err)
}
p.cron = cron.New(cron.WithLocation(loc))
p.locker = &sync.Mutex{}
}
func (p *SchedulePool) Refresh() {
schedules, err := p.store.GetSchedules()
if err != nil {
log.WithError(err).WithFields(log.Fields{
"context": common_errors.GetErrorContext(),
}).Error("failed to get schedules")
return
}
p.locker.Lock()
defer p.locker.Unlock()
p.clear()
now := time.Now().In(p.cron.Location())
for _, schedule := range schedules {
scheduleType := schedule.Type
if scheduleType == "" {
scheduleType = db.ScheduleTypeCron
}
if schedule.RepositoryID == nil && !schedule.Active {
continue
}
runner := CreateScheduleRunner(
schedule.ProjectID,
schedule.ID,
p,
p.encryptionService,
p.keyInstaller,
)
switch scheduleType {
case db.ScheduleTypeRunAt:
if schedule.RunAt == nil {
log.WithFields(log.Fields{
"project_id": schedule.ProjectID,
"schedule_id": schedule.ID,
}).Warn("run_at schedule has no run_at value")
continue
}
runAt := schedule.RunAt.In(p.cron.Location())
if !runAt.After(now) {
if schedule.DeleteAfterRun {
err = p.store.DeleteSchedule(schedule.ProjectID, schedule.ID)
if err != nil {
log.WithError(err).WithFields(log.Fields{
"context": common_errors.GetErrorContext(),
"project_id": schedule.ProjectID,
"schedule_id": schedule.ID,
}).Warn("failed to delete past run_at schedule")
}
} else if schedule.Active {
err = p.store.SetScheduleActive(schedule.ProjectID, schedule.ID, false)
if err != nil {
log.WithError(err).WithFields(log.Fields{
"context": common_errors.GetErrorContext(),
"project_id": schedule.ProjectID,
"schedule_id": schedule.ID,
}).Warn("failed to deactivate past run_at schedule")
}
}
continue
}
_, err = p.addOneTimeRunner(runner, runAt)
case db.ScheduleTypeCron:
if schedule.CronFormat == "" {
continue
}
_, err = p.addRunner(runner, schedule.CronFormat)
default:
log.WithFields(log.Fields{
"project_id": schedule.ProjectID,
"schedule_id": schedule.ID,
"type": schedule.Type,
}).Warn("schedule has unsupported type")
continue
}
if err != nil {
log.WithError(err).WithFields(log.Fields{
"context": common_errors.GetErrorContext(),
"project_id": schedule.ProjectID,
"schedule_id": schedule.ID,
}).Errorf("failed to add schedule")
}
}
}
func (p *SchedulePool) addRunner(runner ScheduleRunner, cronFormat string) (int, error) {
schedule, err := ParseCronAndSemantics(cronFormat)
if err != nil {
return 0, err
}
id := p.cron.Schedule(schedule, runner)
return int(id), nil
}
func (p *SchedulePool) addOneTimeRunner(runner ScheduleRunner, runAt time.Time) (int, error) {
id := p.cron.Schedule(&oneTimeSchedule{runAt: runAt}, runner)
return int(id), nil
}
func (p *SchedulePool) Run() {
p.cron.Run()
}
func (p *SchedulePool) clear() {
runners := p.cron.Entries()
for _, r := range runners {
p.cron.Remove(r.ID)
}
}
func (p *SchedulePool) Destroy() {
p.locker.Lock()
defer p.locker.Unlock()
p.cron.Stop()
p.clear()
p.cron = nil
}
func CreateSchedulePool(
store db.Store,
taskPool *tasks.TaskPool,
keyInstaller db_lib.AccessKeyInstaller,
encryptionService server.AccessKeyEncryptionService,
) SchedulePool {
pool := SchedulePool{
store: store,
taskPool: taskPool,
keyInstaller: keyInstaller,
encryptionService: encryptionService,
}
pool.init()
pool.Refresh()
return pool
}
func ValidateCronFormat(cronFormat string) error {
_, err := cron.ParseStandard(cronFormat)
return err
}
// andSchedule wraps a cron.SpecSchedule so that day-of-month and day-of-week
// are combined with AND instead of the POSIX OR that robfig/cron implements.
// For example "0 6 25-31 * 6" fires only on Saturdays within the 25-31 range
// (the last Saturday of each month), not on every Saturday OR every 25th-31st.
//
// When either field is * (starBit set), robfig/cron already uses AND, so the
// wrapper delegates directly.
type andSchedule struct {
spec *cron.SpecSchedule
}
const cronStarBit = 1 << 63
func (s *andSchedule) Next(t time.Time) time.Time {
if s.spec.Dom&cronStarBit != 0 || s.spec.Dow&cronStarBit != 0 {
return s.spec.Next(t)
}
limit := t.AddDate(4, 0, 0)
candidate := t
for candidate.Before(limit) {
next := s.spec.Next(candidate)
if next.IsZero() || next.After(limit) {
break
}
domMatch := s.spec.Dom&(1<<uint(next.Day())) != 0
dowMatch := s.spec.Dow&(1<<uint(next.Weekday())) != 0
if domMatch && dowMatch {
return next
}
candidate = next
}
return time.Time{}
}
// ParseCronAndSemantics parses a standard 5-field cron expression and returns
// a Schedule that uses AND semantics for day-of-month + day-of-week.
func ParseCronAndSemantics(cronFormat string) (cron.Schedule, error) {
schedule, err := cron.ParseStandard(cronFormat)
if err != nil {
return nil, err
}
spec, ok := schedule.(*cron.SpecSchedule)
if !ok {
return schedule, nil
}
return &andSchedule{spec: spec}, nil
}