-
Notifications
You must be signed in to change notification settings - Fork 175
/
account_based_migration.go
384 lines (334 loc) · 9.53 KB
/
account_based_migration.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
382
383
384
package migrations
import (
"container/heap"
"context"
"fmt"
"io"
"sync"
"time"
"github.com/rs/zerolog"
"github.com/onflow/cadence/runtime/common"
"github.com/onflow/flow-go/cmd/util/ledger/util"
"github.com/onflow/flow-go/ledger"
moduleUtil "github.com/onflow/flow-go/module/util"
)
// logTopNDurations is the number of longest migrations to log at the end of the migration
const logTopNDurations = 20
// AccountBasedMigration is an interface for migrations that migrate account by account
// concurrently getting all the payloads for each account at a time.
type AccountBasedMigration interface {
InitMigration(
log zerolog.Logger,
allPayloads []*ledger.Payload,
nWorkers int,
) error
MigrateAccount(
ctx context.Context,
address common.Address,
payloads []*ledger.Payload,
) ([]*ledger.Payload, error)
io.Closer
}
// CreateAccountBasedMigration creates a migration function that migrates the payloads
// account by account using the given migrations
// accounts are processed concurrently using the given number of workers
// but each account is processed sequentially by the given migrations in order.
// The migrations InitMigration function is called once before the migration starts
// And the Close function is called once after the migration finishes if the migration
// is a finisher.
func CreateAccountBasedMigration(
log zerolog.Logger,
nWorker int,
migrations []AccountBasedMigration,
) func(payloads []*ledger.Payload) ([]*ledger.Payload, error) {
return func(payloads []*ledger.Payload) ([]*ledger.Payload, error) {
return MigrateByAccount(
log,
nWorker,
payloads,
migrations,
)
}
}
// MigrateByAccount takes migrations and all the Payloads,
// and returns the migrated Payloads.
func MigrateByAccount(
log zerolog.Logger,
nWorker int,
allPayloads []*ledger.Payload,
migrations []AccountBasedMigration,
) (
[]*ledger.Payload,
error,
) {
if len(allPayloads) == 0 {
return allPayloads, nil
}
for i, migrator := range migrations {
if err := migrator.InitMigration(
log.With().
Int("migration_index", i).
Logger(),
allPayloads,
nWorker,
); err != nil {
return nil, fmt.Errorf("could not init migration: %w", err)
}
}
log.Info().
Int("inner_migrations", len(migrations)).
Int("nWorker", nWorker).
Msgf("created account migrations")
defer func() {
for i, migrator := range migrations {
log.Info().
Int("migration_index", i).
Type("migration", migrator).
Msg("closing migration")
if err := migrator.Close(); err != nil {
log.Error().Err(err).Msg("error closing migration")
}
}
}()
// group the Payloads by account
accountGroups := util.GroupPayloadsByAccount(log, allPayloads, nWorker)
// migrate the Payloads under accounts
migrated, err := MigrateGroupConcurrently(log, migrations, accountGroups, nWorker)
if err != nil {
return nil, fmt.Errorf("could not migrate accounts: %w", err)
}
log.Info().
Int("account_count", accountGroups.Len()).
Int("payload_count", len(allPayloads)).
Msgf("finished migrating Payloads")
return migrated, nil
}
// MigrateGroupConcurrently migrate the Payloads in the given account groups.
// It uses nWorker to process the Payloads concurrently. The Payloads in each account
// are processed sequentially by the given migrations in order.
func MigrateGroupConcurrently(
log zerolog.Logger,
migrations []AccountBasedMigration,
accountGroups *util.PayloadAccountGrouping,
nWorker int,
) ([]*ledger.Payload, error) {
ctx := context.Background()
ctx, cancel := context.WithCancelCause(ctx)
defer cancel(nil)
jobs := make(chan jobMigrateAccountGroup, accountGroups.Len())
wg := sync.WaitGroup{}
wg.Add(nWorker)
resultCh := make(chan *migrationResult, accountGroups.Len())
for i := 0; i < nWorker; i++ {
go func() {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
case job, ok := <-jobs:
if !ok {
return
}
start := time.Now()
// This is not an account, but service level keys.
if util.IsServiceLevelAddress(job.Address) {
resultCh <- &migrationResult{
migrationDuration: migrationDuration{
Address: job.Address,
Duration: time.Since(start),
PayloadCount: len(job.Payloads),
},
Migrated: job.Payloads,
}
continue
}
if _, ok := knownProblematicAccounts[job.Address]; ok {
log.Info().
Hex("address", job.Address[:]).
Int("payload_count", len(job.Payloads)).
Msg("skipping problematic account")
resultCh <- &migrationResult{
migrationDuration: migrationDuration{
Address: job.Address,
Duration: time.Since(start),
PayloadCount: len(job.Payloads),
},
Migrated: job.Payloads,
}
continue
}
var err error
accountMigrated := job.Payloads
for m, migrator := range migrations {
select {
case <-ctx.Done():
return
default:
}
accountMigrated, err = migrator.MigrateAccount(ctx, job.Address, accountMigrated)
if err != nil {
log.Error().
Err(err).
Int("migration_index", m).
Type("migration", migrator).
Hex("address", job.Address[:]).
Msg("could not migrate account")
cancel(fmt.Errorf("could not migrate account: %w", err))
return
}
}
resultCh <- &migrationResult{
migrationDuration: migrationDuration{
Address: job.Address,
Duration: time.Since(start),
PayloadCount: len(job.Payloads),
},
Migrated: accountMigrated,
}
}
}
}()
}
go func() {
defer close(jobs)
for {
g, err := accountGroups.Next()
if err != nil {
cancel(fmt.Errorf("could not get next account group: %w", err))
return
}
if g == nil {
break
}
job := jobMigrateAccountGroup{
Address: g.Address,
Payloads: g.Payloads,
}
select {
case <-ctx.Done():
return
case jobs <- job:
}
}
}()
// read job results
logAccount := moduleUtil.LogProgress(
log,
moduleUtil.DefaultLogProgressConfig(
"processing account group",
accountGroups.Len(),
),
)
migrated := make([]*ledger.Payload, 0, accountGroups.AllPayloadsCount())
durations := newMigrationDurations(logTopNDurations)
contextDone := false
for i := 0; i < accountGroups.Len(); i++ {
select {
case <-ctx.Done():
contextDone = true
break
case result := <-resultCh:
durations.Add(result)
accountMigrated := result.Migrated
migrated = append(migrated, accountMigrated...)
logAccount(1)
}
if contextDone {
break
}
}
// make sure to exit all workers before returning from this function
// so that the migrator can be closed properly
log.Info().Msg("waiting for migration workers to finish")
wg.Wait()
log.Info().
Array("top_longest_migrations", durations.Array()).
Msgf("Top longest migrations")
if ctx.Err() != nil {
return nil, fmt.Errorf("fail to migrate payload: %w", ctx.Err())
}
return migrated, nil
}
var knownProblematicAccounts = map[common.Address]string{
// Testnet accounts with broken contracts
mustHexToAddress("434a1f199a7ae3ba"): "Broken contract FanTopPermission",
mustHexToAddress("454c9991c2b8d947"): "Broken contract Test",
mustHexToAddress("48602d8056ff9d93"): "Broken contract FanTopPermission",
mustHexToAddress("5d63c34d7f05e5a4"): "Broken contract FanTopPermission",
mustHexToAddress("5e3448b3cffb97f2"): "Broken contract FanTopPermission",
mustHexToAddress("7d8c7e050c694eaa"): "Broken contract Test",
mustHexToAddress("ba53f16ede01972d"): "Broken contract FanTopPermission",
mustHexToAddress("c843c1f5a4805c3a"): "Broken contract FanTopPermission",
mustHexToAddress("48d3be92e6e4a973"): "Broken contract FanTopPermission",
// Mainnet account
}
func mustHexToAddress(hex string) common.Address {
address, err := common.HexToAddress(hex)
if err != nil {
panic(err)
}
return address
}
type jobMigrateAccountGroup struct {
Address common.Address
Payloads []*ledger.Payload
}
type migrationResult struct {
migrationDuration
Migrated []*ledger.Payload
}
type migrationDuration struct {
Address common.Address
Duration time.Duration
PayloadCount int
}
// migrationDurations implements heap methods for the timer results
type migrationDurations struct {
v []migrationDuration
KeepTopN int
}
// newMigrationDurations creates a new migrationDurations which are used to track the
// accounts that took the longest time to migrate.
func newMigrationDurations(keepTopN int) *migrationDurations {
return &migrationDurations{
v: make([]migrationDuration, 0, keepTopN),
KeepTopN: keepTopN,
}
}
func (h *migrationDurations) Len() int { return len(h.v) }
func (h *migrationDurations) Less(i, j int) bool {
return h.v[i].Duration < h.v[j].Duration
}
func (h *migrationDurations) Swap(i, j int) {
h.v[i], h.v[j] = h.v[j], h.v[i]
}
func (h *migrationDurations) Push(x interface{}) {
h.v = append(h.v, x.(migrationDuration))
}
func (h *migrationDurations) Pop() interface{} {
old := h.v
n := len(old)
x := old[n-1]
h.v = old[0 : n-1]
return x
}
func (h *migrationDurations) Array() zerolog.LogArrayMarshaler {
array := zerolog.Arr()
for _, result := range h.v {
array = array.Str(fmt.Sprintf("%s [payloads: %d]: %s",
result.Address.Hex(),
result.PayloadCount,
result.Duration.String(),
))
}
return array
}
func (h *migrationDurations) Add(result *migrationResult) {
if h.Len() < h.KeepTopN || result.Duration > h.v[0].Duration {
if h.Len() == h.KeepTopN {
heap.Pop(h) // remove the element with the smallest duration
}
heap.Push(h, result.migrationDuration)
}
}