This repository has been archived by the owner on Jun 6, 2023. It is now read-only.
/
top.go
334 lines (293 loc) · 10.6 KB
/
top.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
package nv16
import (
"context"
"sync"
"sync/atomic"
"time"
"github.com/multiformats/go-multibase"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/rt"
builtin7 "github.com/filecoin-project/specs-actors/v7/actors/builtin"
states7 "github.com/filecoin-project/specs-actors/v7/actors/states"
"github.com/filecoin-project/specs-actors/v8/actors/builtin/exported"
manifest8 "github.com/filecoin-project/specs-actors/v8/actors/builtin/manifest"
states8 "github.com/filecoin-project/specs-actors/v8/actors/states"
adt8 "github.com/filecoin-project/specs-actors/v8/actors/util/adt"
"github.com/ipfs/go-cid"
cbor "github.com/ipfs/go-ipld-cbor"
"golang.org/x/sync/errgroup"
"golang.org/x/xerrors"
)
// Config parameterizes a state tree migration
type Config struct {
// Number of migration worker goroutines to run.
// More workers enables higher CPU utilization doing migration computations (including state encoding)
MaxWorkers uint
// Capacity of the queue of jobs available to workers (zero for unbuffered).
// A queue length of hundreds to thousands improves throughput at the cost of memory.
JobQueueSize uint
// Capacity of the queue receiving migration results from workers, for persisting (zero for unbuffered).
// A queue length of tens to hundreds improves throughput at the cost of memory.
ResultQueueSize uint
// Time between progress logs to emit.
// Zero (the default) results in no progress logs.
ProgressLogPeriod time.Duration
}
type Logger interface {
// This is the same logging interface provided by the Runtime
Log(level rt.LogLevel, msg string, args ...interface{})
}
// Migrates from v15 to v16
//
// This migration only updates the actor code CIDs in the state tree.
// MigrationCache stores and loads cached data. Its implementation must be threadsafe
type MigrationCache interface {
Write(key string, newCid cid.Cid) error
Read(key string) (bool, cid.Cid, error)
Load(key string, loadFunc func() (cid.Cid, error)) (cid.Cid, error)
}
func ActorHeadKey(addr address.Address, head cid.Cid) string {
headKey, err := head.StringOfBase(multibase.Base32)
if err != nil {
panic(err)
}
return addr.String() + "-head-" + headKey
}
// Migrates the filecoin state tree starting from the global state tree and upgrading all actor state.
// The store must support concurrent writes (even if the configured worker count is 1).
func MigrateStateTree(ctx context.Context, store cbor.IpldStore, actorsManifest cid.Cid, actorsRootIn cid.Cid, priorEpoch abi.ChainEpoch, cfg Config, log Logger, cache MigrationCache) (cid.Cid, error) {
if cfg.MaxWorkers <= 0 {
return cid.Undef, xerrors.Errorf("invalid migration config with %d workers", cfg.MaxWorkers)
}
adtStore := adt8.WrapStore(ctx, store)
// load manifest
var manifest manifest8.Manifest
if err := adtStore.Get(ctx, actorsManifest, &manifest); err != nil {
return cid.Undef, xerrors.Errorf("error reading actor manifest: %w", err)
}
if err := manifest.Load(ctx, adtStore); err != nil {
return cid.Undef, xerrors.Errorf("error loading actor manifest: %w", err)
}
// Maps prior version code CIDs to migration functions.
migrations := make(map[cid.Cid]actorMigration)
// Set of prior version code CIDs for actors to defer during iteration, for explicit migration afterwards.
var deferredCodeIDs = map[cid.Cid]struct{}{
// None
}
// simple code migrations
var simpleMigrations = map[string]cid.Cid{
"init": builtin7.InitActorCodeID,
"cron": builtin7.CronActorCodeID,
"account": builtin7.AccountActorCodeID,
"storagepower": builtin7.StoragePowerActorCodeID,
"storageminer": builtin7.StorageMinerActorCodeID,
"paymentchannel": builtin7.PaymentChannelActorCodeID,
"multisig": builtin7.MultisigActorCodeID,
"reward": builtin7.RewardActorCodeID,
"verifiedregistry": builtin7.VerifiedRegistryActorCodeID,
}
for name, code7Cid := range simpleMigrations { //nolint:nomaprange
code8Cid, ok := manifest.Get(name)
if !ok {
return cid.Undef, xerrors.Errorf("code cid for %s actor not found in manifest", name)
}
migrations[code7Cid] = codeMigrator{code8Cid}
}
// migrations that migrate both code and state
system8Cid, ok := manifest.Get("system")
if !ok {
return cid.Undef, xerrors.Errorf("code cid for system actor not found in manifet")
}
migrations[builtin7.SystemActorCodeID] = systemActorMigrator{system8Cid, manifest.Data}
market8Cid, ok := manifest.Get("storagemarket")
if !ok {
return cid.Undef, xerrors.Errorf("code cid for market actor not found in manifest")
}
migrations[builtin7.StorageMarketActorCodeID] = marketMigrator{market8Cid}
if len(migrations)+len(deferredCodeIDs) != len(exported.BuiltinActors()) {
return cid.Undef, xerrors.Errorf("incomplete migration specification with %d code CIDs", len(migrations))
}
startTime := time.Now()
// Load input and output state trees
actorsIn, err := states7.LoadTree(adtStore, actorsRootIn)
if err != nil {
return cid.Undef, err
}
actorsOut, err := states8.NewTree(adtStore)
if err != nil {
return cid.Undef, err
}
// Setup synchronization
grp, ctx := errgroup.WithContext(ctx)
// Input and output queues for workers.
jobCh := make(chan *migrationJob, cfg.JobQueueSize)
jobResultCh := make(chan *migrationJobResult, cfg.ResultQueueSize)
// Atomically-modified counters for logging progress
var jobCount uint32
var doneCount uint32
// Iterate all actors in old state root to create migration jobs for each non-deferred actor.
grp.Go(func() error {
defer close(jobCh)
log.Log(rt.INFO, "Creating migration jobs for tree %s", actorsRootIn)
if err = actorsIn.ForEach(func(addr address.Address, actorIn *states7.Actor) error {
if _, ok := deferredCodeIDs[actorIn.Code]; ok {
return nil
}
migration, ok := migrations[actorIn.Code]
if !ok {
return xerrors.Errorf("actor with code %s has no registered migration function", actorIn.Code)
}
nextInput := &migrationJob{
Address: addr,
Actor: *actorIn, // Must take a copy, the pointer is not stable.
cache: cache,
actorMigration: migration,
}
select {
case jobCh <- nextInput:
case <-ctx.Done():
return ctx.Err()
}
atomic.AddUint32(&jobCount, 1)
return nil
}); err != nil {
return err
}
log.Log(rt.INFO, "Done creating %d migration jobs for tree %s after %v", jobCount, actorsRootIn, time.Since(startTime))
return nil
})
// Worker threads run jobs.
var workerWg sync.WaitGroup
for i := uint(0); i < cfg.MaxWorkers; i++ {
workerWg.Add(1)
workerId := i
grp.Go(func() error {
defer workerWg.Done()
for job := range jobCh {
result, err := job.run(ctx, store, priorEpoch)
if err != nil {
return err
}
select {
case jobResultCh <- result:
case <-ctx.Done():
return ctx.Err()
}
atomic.AddUint32(&doneCount, 1)
}
log.Log(rt.INFO, "Worker %d done", workerId)
return nil
})
}
log.Log(rt.INFO, "Started %d workers", cfg.MaxWorkers)
// Monitor the job queue. This non-critical goroutine is outside the errgroup and exits when
// workersFinished is closed, or the context done.
workersFinished := make(chan struct{}) // Closed when waitgroup is emptied.
if cfg.ProgressLogPeriod > 0 {
go func() {
defer log.Log(rt.DEBUG, "Job queue monitor done")
for {
select {
case <-time.After(cfg.ProgressLogPeriod):
jobsNow := jobCount // Snapshot values to avoid incorrect-looking arithmetic if they change.
doneNow := doneCount
pendingNow := jobsNow - doneNow
elapsed := time.Since(startTime)
rate := float64(doneNow) / elapsed.Seconds()
log.Log(rt.INFO, "%d jobs created, %d done, %d pending after %v (%.0f/s)",
jobsNow, doneNow, pendingNow, elapsed, rate)
case <-workersFinished:
return
case <-ctx.Done():
return
}
}
}()
}
// Close result channel when workers are done sending to it.
grp.Go(func() error {
workerWg.Wait()
close(jobResultCh)
close(workersFinished)
log.Log(rt.INFO, "All workers done after %v", time.Since(startTime))
return nil
})
// Insert migrated records in output state tree and accumulators.
grp.Go(func() error {
log.Log(rt.INFO, "Result writer started")
resultCount := 0
for result := range jobResultCh {
if err := actorsOut.SetActor(result.Address, &result.Actor); err != nil {
return err
}
resultCount++
}
log.Log(rt.INFO, "Result writer wrote %d results to state tree after %v", resultCount, time.Since(startTime))
return nil
})
if err := grp.Wait(); err != nil {
return cid.Undef, err
}
elapsed := time.Since(startTime)
rate := float64(doneCount) / elapsed.Seconds()
log.Log(rt.INFO, "All %d done after %v (%.0f/s). Flushing state tree root.", doneCount, elapsed, rate)
return actorsOut.Flush()
}
type actorMigrationInput struct {
address address.Address // actor's address
head cid.Cid
priorEpoch abi.ChainEpoch // epoch of last state transition prior to migration
cache MigrationCache // cache of existing cid -> cid migrations for this actor
}
type actorMigrationResult struct {
newCodeCID cid.Cid
newHead cid.Cid
}
type actorMigration interface {
// Loads an actor's state from an input store and writes new state to an output store.
// Returns the new state head CID.
migrateState(ctx context.Context, store cbor.IpldStore, input actorMigrationInput) (result *actorMigrationResult, err error)
}
type migrationJob struct {
address.Address
states7.Actor
actorMigration
cache MigrationCache
}
type migrationJobResult struct {
address.Address
states8.Actor
}
func (job *migrationJob) run(ctx context.Context, store cbor.IpldStore, priorEpoch abi.ChainEpoch) (*migrationJobResult, error) {
result, err := job.migrateState(ctx, store, actorMigrationInput{
address: job.Address,
head: job.Actor.Head,
priorEpoch: priorEpoch,
cache: job.cache,
})
if err != nil {
return nil, xerrors.Errorf("state migration failed for %s actor, addr %s: %w",
builtin7.ActorNameByCode(job.Actor.Code), job.Address, err)
}
// Set up new actor record with the migrated state.
return &migrationJobResult{
job.Address, // Unchanged
states7.Actor{
Code: result.newCodeCID,
Head: result.newHead,
CallSeqNum: job.Actor.CallSeqNum, // Unchanged
Balance: job.Actor.Balance, // Unchanged
},
}, nil
}
// Migrator which preserves the head CID and provides a fixed result code CID.
type codeMigrator struct {
OutCodeCID cid.Cid
}
func (n codeMigrator) migrateState(_ context.Context, _ cbor.IpldStore, in actorMigrationInput) (*actorMigrationResult, error) {
return &actorMigrationResult{
newCodeCID: n.OutCodeCID,
newHead: in.head,
}, nil
}