-
Notifications
You must be signed in to change notification settings - Fork 0
/
basic_scheduler.go
293 lines (247 loc) · 7.59 KB
/
basic_scheduler.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
// Copyright Project Harbor Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package period
import (
"encoding/json"
"time"
"context"
"github.com/gocraft/work"
"github.com/goharbor/harbor/src/jobservice/common/rds"
"github.com/goharbor/harbor/src/jobservice/common/utils"
"github.com/goharbor/harbor/src/jobservice/job"
"github.com/goharbor/harbor/src/jobservice/lcm"
"github.com/goharbor/harbor/src/jobservice/logger"
"github.com/gomodule/redigo/redis"
"github.com/pkg/errors"
)
// basicScheduler manages the periodic scheduling policies.
type basicScheduler struct {
context context.Context
pool *redis.Pool
namespace string
enqueuer *enqueuer
client *work.Client
ctl lcm.Controller
}
// NewScheduler is constructor of basicScheduler
func NewScheduler(ctx context.Context, namespace string, pool *redis.Pool, ctl lcm.Controller) Scheduler {
return &basicScheduler{
context: ctx,
pool: pool,
namespace: namespace,
enqueuer: newEnqueuer(ctx, namespace, pool, ctl),
client: work.NewClient(namespace, pool),
ctl: ctl,
}
}
// Start the periodic scheduling process
// Blocking call here
func (bs *basicScheduler) Start() error {
defer func() {
logger.Info("Basic scheduler is stopped")
}()
// Try best to do
go bs.clearDirtyJobs()
logger.Info("Basic scheduler is started")
// start enqueuer
return bs.enqueuer.start()
}
// Stop the periodic scheduling process
func (bs *basicScheduler) Stop() error {
// stop everything
bs.enqueuer.stopChan <- true
return nil
}
// Schedule is implementation of the same method in period.Interface
func (bs *basicScheduler) Schedule(p *Policy) (int64, error) {
if p == nil {
return -1, errors.New("bad policy object: nil")
}
if err := p.Validate(); err != nil {
return -1, err
}
conn := bs.pool.Get()
defer func() {
_ = conn.Close()
}()
// Do the 1st round of enqueuing
bs.enqueuer.scheduleNextJobs(p, conn)
// Serialize data
rawJSON, err := p.Serialize()
if err != nil {
return -1, err
}
// Prepare publish message
m := &message{
Event: changeEventSchedule,
Data: p,
}
msgJSON, err := json.Marshal(m)
if err != nil {
return -1, err
}
pid := time.Now().Unix()
// Save to redis db and publish notification via redis transaction
err = conn.Send("MULTI")
err = conn.Send("ZADD", rds.KeyPeriodicPolicy(bs.namespace), pid, rawJSON)
err = conn.Send("PUBLISH", rds.KeyPeriodicNotification(bs.namespace), msgJSON)
if _, err := conn.Do("EXEC"); err != nil {
return -1, err
}
return pid, nil
}
// UnSchedule is implementation of the same method in period.Interface
func (bs *basicScheduler) UnSchedule(policyID string) error {
if utils.IsEmptyStr(policyID) {
return errors.New("bad periodic job ID: nil")
}
tracker, err := bs.ctl.Track(policyID)
if err != nil {
return err
}
// If errors occurred when getting the numeric ID of periodic job,
// may be because the specified job is not a valid periodic job.
numericID, err := tracker.NumericID()
if err != nil {
return err
}
conn := bs.pool.Get()
defer func() {
_ = conn.Close()
}()
// Get the un-scheduling policy object
bytes, err := redis.Values(conn.Do("ZRANGEBYSCORE", rds.KeyPeriodicPolicy(bs.namespace), numericID, numericID))
if err != nil {
return err
}
p := &Policy{}
if len(bytes) > 0 {
if rawPolicy, ok := bytes[0].([]byte); ok {
if err := p.DeSerialize(rawPolicy); err != nil {
return err
}
}
}
if utils.IsEmptyStr(p.ID) {
// Deserialize failed
return errors.Errorf("no valid periodic job policy found: %s:%d", policyID, numericID)
}
notification := &message{
Event: changeEventUnSchedule,
Data: p,
}
msgJSON, err := json.Marshal(notification)
if err != nil {
return err
}
// REM from redis db with transaction way
err = conn.Send("MULTI")
err = conn.Send("ZREMRANGEBYSCORE", rds.KeyPeriodicPolicy(bs.namespace), numericID, numericID) // Accurately remove the item with the specified score
err = conn.Send("PUBLISH", rds.KeyPeriodicNotification(bs.namespace), msgJSON)
if err != nil {
return err
}
_, err = conn.Do("EXEC")
if err != nil {
return err
}
// Expire periodic job stats
if err := tracker.Expire(); err != nil {
logger.Error(err)
}
// Switch the job stats to stopped
// Should not block the next clear action
err = tracker.Stop()
// Get downstream executions of the periodic job
// And clear these executions
// This is a try best action, its failure will not cause the unschedule action failed.
// Failure errors will be only logged here
eKey := rds.KeyUpstreamJobAndExecutions(bs.namespace, policyID)
if eIDs, err := getPeriodicExecutions(conn, eKey); err != nil {
logger.Errorf("Get executions for periodic job %s error: %s", policyID, err)
} else {
if len(eIDs) == 0 {
logger.Debugf("no stopped executions: %s", policyID)
}
for _, eID := range eIDs {
eTracker, err := bs.ctl.Track(eID)
if err != nil {
logger.Errorf("Track execution %s error: %s", eID, err)
continue
}
e := eTracker.Job()
// Only need to care the pending and running ones
// Do clear
if job.ScheduledStatus == job.Status(e.Info.Status) {
// Please pay attention here, the job ID used in the scheduled jon queue is
// the ID of the periodic job (policy).
if err := bs.client.DeleteScheduledJob(e.Info.RunAt, policyID); err != nil {
logger.Errorf("Delete scheduled job %s error: %s", eID, err)
}
}
// Mark job status to stopped to block execution.
// The executions here should not be in the final states,
// double confirmation: only stop the stopped ones.
if job.RunningStatus.Compare(job.Status(e.Info.Status)) >= 0 {
if err := eTracker.Stop(); err != nil {
logger.Errorf("Stop execution %s error: %s", eID, err)
}
}
}
}
return err
}
// Clear all the dirty jobs
// A scheduled job will be marked as dirty job only if the enqueued timestamp has expired a horizon.
// This is a try best action
func (bs *basicScheduler) clearDirtyJobs() {
conn := bs.pool.Get()
defer func() {
_ = conn.Close()
}()
nowEpoch := time.Now().Unix()
scope := nowEpoch - int64(enqueuerHorizon/time.Minute)*60
jobScores, err := rds.GetZsetByScore(conn, rds.RedisKeyScheduled(bs.namespace), []int64{0, scope})
if err != nil {
logger.Errorf("Get dirty jobs error: %s", err)
return
}
for _, jobScore := range jobScores {
j, err := utils.DeSerializeJob(jobScore.JobBytes)
if err != nil {
logger.Errorf("Deserialize dirty job error: %s", err)
continue
}
if err = bs.client.DeleteScheduledJob(jobScore.Score, j.ID); err != nil {
logger.Errorf("Remove dirty scheduled job error: %s", err)
} else {
logger.Debugf("Remove dirty scheduled job: %s run at %#v", j.ID, time.Unix(jobScore.Score, 0).String())
}
}
}
// Get relevant executions for the periodic job
func getPeriodicExecutions(conn redis.Conn, key string) ([]string, error) {
args := []interface{}{key, 0, "+inf"}
list, err := redis.Values(conn.Do("ZRANGEBYSCORE", args...))
if err != nil {
return nil, err
}
results := make([]string, 0)
for _, item := range list {
if eID, ok := item.([]byte); ok {
results = append(results, string(eID))
}
}
return results, nil
}