-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
Copy pathmigrator_v180.go
381 lines (320 loc) · 9.74 KB
/
migrator_v180.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
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
// 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 migration
import (
"encoding/base64"
"encoding/json"
"fmt"
"strconv"
"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/logger"
"github.com/goharbor/harbor/src/jobservice/period"
"github.com/gomodule/redigo/redis"
"github.com/pkg/errors"
)
// PolicyMigrator migrate the cron job policy to new schema
type PolicyMigrator struct {
// namespace of rdb
namespace string
// Pool for connecting to redis
pool *redis.Pool
}
// PolicyMigratorFactory is a factory func to create PolicyMigrator
func PolicyMigratorFactory(pool *redis.Pool, namespace string) (RDBMigrator, error) {
if pool == nil {
return nil, errors.New("PolicyMigratorFactory: missing pool")
}
if utils.IsEmptyStr(namespace) {
return nil, errors.New("PolicyMigratorFactory: missing namespace")
}
return &PolicyMigrator{
namespace: namespace,
pool: pool,
}, nil
}
// Metadata returns the base information of this migrator
func (pm *PolicyMigrator) Metadata() *MigratorMeta {
return &MigratorMeta{
FromVersion: "<1.8.0",
ToVersion: "1.8.1",
ObjectRef: "{namespace}:period:policies",
}
}
// Migrate data
func (pm *PolicyMigrator) Migrate() error {
conn := pm.pool.Get()
defer func() {
if err := conn.Close(); err != nil {
logger.Errorf("close redis connection error: %s", err)
}
}()
allJobIDs, err := getAllJobStatsIDs(conn, pm.namespace)
if err != nil {
return errors.Wrap(err, "get job stats list error")
}
args := []interface{}{
"id_placeholder",
"id",
"kind",
"status",
"status_hook", // valid for 1.6 and 1.7,
"multiple_executions", // valid for 1.7
"numeric_policy_id", // valid for 1.8
}
count := 0
for _, fullID := range allJobIDs {
args[0] = fullID
values, err := redis.Values(conn.Do("HMGET", args...))
if err != nil {
logger.Errorf("Get stats fields of job %s failed with error: %s", fullID, err)
continue
}
pID := toString(values[0])
kind := toString(values[1])
if !utils.IsEmptyStr(pID) && job.KindPeriodic == kind {
logger.Debugf("Periodic job found: %s", pID)
// Data requires migration
// Missing 'numeric_policy_id' which is introduced in 1.8
if values[5] == nil {
logger.Infof("Migrate periodic job stats data is started: %s", pID)
numbericPolicyID, err := getScoreByID(pID, conn, pm.namespace)
if err != nil {
logger.Errorf("Get numberic ID of periodic job policy failed with error: %s", err)
continue
}
// Transaction
err = conn.Send("MULTI")
setArgs := []interface{}{
fullID,
"status",
job.ScheduledStatus.String(), // make sure the status of periodic job is "Scheduled"
"numeric_policy_id",
numbericPolicyID,
}
// If status hook existing
hookURL := toString(values[3])
if !utils.IsEmptyStr(hookURL) {
setArgs = append(setArgs, "web_hook_url", hookURL)
}
// Set fields
err = conn.Send("HMSET", setArgs...)
// Remove useless fields
rmArgs := []interface{}{
fullID,
"status_hook",
"multiple_executions",
}
err = conn.Send("HDEL", rmArgs...)
// Update periodic policy model
// conn is working, we need new conn
// this inner connection will be closed by the calling method
innerConn := pm.pool.Get()
policy, er := getPeriodicPolicy(numbericPolicyID, innerConn, pm.namespace)
if er == nil {
policy.ID = pID
if !utils.IsEmptyStr(hookURL) {
// Copy web hook URL
policy.WebHookURL = fmt.Sprintf("%s", hookURL)
}
if rawJSON, er := policy.Serialize(); er == nil {
// Remove the old one first
err = conn.Send("ZREMRANGEBYSCORE", rds.KeyPeriodicPolicy(pm.namespace), numbericPolicyID, numbericPolicyID)
// Save back to the rdb
err = conn.Send("ZADD", rds.KeyPeriodicPolicy(pm.namespace), numbericPolicyID, rawJSON)
} else {
logger.Errorf("Serialize policy %s failed with error: %s", pID, er)
}
} else {
logger.Errorf("Get periodic policy %s failed with error: %s", pID, er)
}
// Check error before executing
if err != nil {
logger.Errorf("Build redis transaction failed with error: %s", err)
continue
}
// Exec
if _, err := conn.Do("EXEC"); err != nil {
logger.Errorf("Migrate periodic job %s failed with error: %s", pID, err)
continue
}
count++
logger.Infof("Migrate periodic job stats data is completed: %s", pID)
}
}
}
logger.Infof("Migrate %d periodic policies", count)
delScoreZset(conn, pm.namespace)
return clearDuplicatedPolicies(conn, pm.namespace)
}
// getAllJobStatsIDs get all the IDs of the existing jobs
func getAllJobStatsIDs(conn redis.Conn, ns string) ([]string, error) {
pattern := rds.KeyJobStats(ns, "*")
args := []interface{}{
0,
"MATCH",
pattern,
"COUNT",
100,
}
allFullIDs := make([]interface{}, 0)
for {
// Use SCAN to iterate the IDs
values, err := redis.Values(conn.Do("SCAN", args...))
if err != nil {
return nil, err
}
// In case something wrong happened
if len(values) != 2 {
return nil, errors.Errorf("Invalid result returned for the SCAN command: %#v", values)
}
if fullIDs, ok := values[1].([]interface{}); ok {
allFullIDs = append(allFullIDs, fullIDs...)
}
// Check the next cursor
cur := toInt(values[0])
if cur == -1 {
// No valid next cursor got
return nil, errors.Errorf("Failed to get the next SCAN cursor: %#v", values[0])
}
if cur != 0 {
args[0] = cur
} else {
// end
break
}
}
IDs := make([]string, 0)
for _, fullIDValue := range allFullIDs {
if fullID, ok := fullIDValue.([]byte); ok {
IDs = append(IDs, string(fullID))
} else {
logger.Debugf("Invalid job stats key: %#v", fullIDValue)
}
}
return IDs, nil
}
// Get the score with the provided ID
func getScoreByID(id string, conn redis.Conn, ns string) (int64, error) {
scoreKey := fmt.Sprintf("%s%s:%s", rds.KeyNamespacePrefix(ns), "period", "key_score")
return redis.Int64(conn.Do("ZSCORE", scoreKey, id))
}
// Get periodic policy object by the numeric ID
func getPeriodicPolicy(numericID int64, conn redis.Conn, ns string) (*period.Policy, error) {
// close this inner connection here
defer func() {
if err := conn.Close(); err != nil {
logger.Errorf("close redis connection error: %s", err)
}
}()
bytes, err := redis.Values(conn.Do("ZRANGEBYSCORE", rds.KeyPeriodicPolicy(ns), numericID, numericID))
if err != nil {
return nil, err
}
p := &period.Policy{}
if len(bytes) > 0 {
if rawPolicy, ok := bytes[0].([]byte); ok {
if err = p.DeSerialize(rawPolicy); err == nil {
return p, nil
}
}
}
if err == nil {
err = errors.Errorf("invalid data for periodic policy %d: %#v", numericID, bytes)
}
return nil, err
}
// Clear the duplicated policy entries for the job "IMAGE_GC" and "IMAGE_SCAN_ALL"
func clearDuplicatedPolicies(conn redis.Conn, ns string) error {
hash := make(map[string]interface{})
bytes, err := redis.Values(conn.Do("ZREVRANGE", rds.KeyPeriodicPolicy(ns), 0, -1, "WITHSCORES"))
if err != nil {
return err
}
count := 0
for i, l := 0, len(bytes); i < l; i = i + 2 {
rawPolicy := bytes[i].([]byte)
p := &period.Policy{}
if err := p.DeSerialize(rawPolicy); err != nil {
logger.Errorf("DeSerialize policy: %s; error: %s\n", rawPolicy, err)
continue
}
if p.JobName == job.ImageScanAllJob ||
p.JobName == job.ImageGC ||
p.JobName == job.ReplicationScheduler {
score, _ := strconv.ParseInt(string(bytes[i+1].([]byte)), 10, 64)
key := hashKey(p)
if _, exists := hash[key]; exists {
// Already existing, remove the duplicated one
res, err := redis.Int(conn.Do("ZREMRANGEBYSCORE", rds.KeyPeriodicPolicy(ns), score, score))
if err != nil || res == 0 {
logger.Errorf("Failed to clear duplicated periodic policy: %s-%s:%v", p.JobName, p.ID, score)
} else {
logger.Infof("Remove duplicated periodic policy: %s-%s:%v", p.JobName, p.ID, score)
count++
}
} else {
hash[key] = score
}
}
}
logger.Infof("Clear %d duplicated periodic policies", count)
return nil
}
// Remove the non-used key
func delScoreZset(conn redis.Conn, ns string) {
key := fmt.Sprintf("%s%s", rds.KeyNamespacePrefix(ns), "period:key_score")
reply, err := redis.Int(conn.Do("EXISTS", key))
if err == nil && reply == 1 {
reply, err = redis.Int(conn.Do("DEL", key))
if err == nil && reply > 0 {
logger.Infof("%s removed", key)
return // success
}
}
if err != nil {
// Just logged
logger.Errorf("Remove %s failed with error: %s", key, err)
}
}
func toString(v interface{}) string {
if v == nil {
return ""
}
if bytes, ok := v.([]byte); ok {
return string(bytes)
}
return ""
}
func toInt(v interface{}) int64 {
if v == nil {
return -1
}
if bytes, ok := v.([]byte); ok {
if intV, err := strconv.ParseInt(string(bytes), 10, 64); err == nil {
return intV
}
}
return -1
}
func hashKey(p *period.Policy) string {
key := p.JobName
if p.JobParameters != nil && len(p.JobParameters) > 0 {
if bytes, err := json.Marshal(p.JobParameters); err == nil {
key = fmt.Sprintf("%s:%s", key, string(bytes))
}
}
return base64.StdEncoding.EncodeToString([]byte(key))
}