-
Notifications
You must be signed in to change notification settings - Fork 228
/
dump.go
315 lines (271 loc) · 8.37 KB
/
dump.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
package client
import (
"bufio"
"compress/zlib"
"context"
"fmt"
"io"
"math"
"os"
"path/filepath"
"runtime"
"sync"
"time"
"github.com/alitto/pond"
"github.com/cosmos/iavl"
"github.com/golang/snappy"
"github.com/spf13/cast"
"github.com/spf13/cobra"
dbm "github.com/tendermint/tm-db"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/server"
"github.com/crypto-org-chain/cronos/versiondb/tsrocksdb"
)
const DefaultChunkSize = 1000000
func DumpChangeSetCmd(opts Options) *cobra.Command {
cmd := &cobra.Command{
Use: "dump outDir",
Short: "Extract changesets from iavl versions, and save to plain file format",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
ctx := server.GetServerContextFromCmd(cmd)
if err := ctx.Viper.BindPFlags(cmd.Flags()); err != nil {
return err
}
db, err := opts.OpenReadOnlyDB(ctx.Viper.GetString(flags.FlagHome), server.GetAppDBBackend(ctx.Viper))
if err != nil {
return err
}
cacheSize := cast.ToInt(ctx.Viper.Get(server.FlagIAVLCacheSize))
startVersion, err := cmd.Flags().GetInt64(flagStartVersion)
if err != nil {
return err
}
endVersion, err := cmd.Flags().GetInt64(flagEndVersion)
if err != nil {
return err
}
concurrency, err := cmd.Flags().GetInt(flagConcurrency)
if err != nil {
return err
}
chunkSize, err := cmd.Flags().GetInt(flagChunkSize)
if err != nil {
return err
}
zlibLevel, err := cmd.Flags().GetInt(flagZlibLevel)
if err != nil {
return err
}
stores, err := GetStoresOrDefault(cmd, opts.DefaultStores)
if err != nil {
return err
}
outDir := args[0]
if err := os.MkdirAll(outDir, os.ModePerm); err != nil {
return err
}
if endVersion == 0 {
// use the latest version of the first store for all stores
prefix := []byte(fmt.Sprintf(tsrocksdb.StorePrefixTpl, stores[0]))
tree, err := iavl.NewMutableTree(dbm.NewPrefixDB(db, prefix), 0, true)
if err != nil {
return err
}
latestVersion, err := tree.LazyLoadVersion(0)
if err != nil {
return err
}
endVersion = latestVersion + 1
fmt.Println("end version not specified, default to latest version + 1,", endVersion)
}
// create fixed size task pool with big enough buffer.
pool := pond.New(concurrency, 1024)
defer pool.StopAndWait()
// we handle multiple stores sequentially, because different stores don't share much in db, handle concurrently reduces cache efficiency.
for _, store := range stores {
fmt.Println("begin store", store, time.Now().Format(time.RFC3339))
// find the first version in the db, reading raw db because no public api for it.
prefix := []byte(fmt.Sprintf(tsrocksdb.StorePrefixTpl, store))
storeStartVersion, err := getNextVersion(dbm.NewPrefixDB(db, prefix), 0)
if err != nil {
return err
}
if storeStartVersion == 0 {
// store not exists
fmt.Println("skip empty store")
continue
}
if startVersion > storeStartVersion {
storeStartVersion = startVersion
}
// share the iavl tree between tasks to reuse the node cache
iavlTreePool := sync.Pool{
New: func() any {
// use separate prefixdb and iavl tree in each task to maximize concurrency performance
return iavl.NewImmutableTree(dbm.NewPrefixDB(db, prefix), cacheSize, true)
},
}
// first split work load into chunks
var chunks []chunk
for i := storeStartVersion; i < endVersion; i += int64(chunkSize) {
end := i + int64(chunkSize)
if end > endVersion {
end = endVersion
}
var taskFiles []string
group, _ := pool.GroupContext(context.Background())
// then split each chunk according to number of workers, the results will be concatenated into a single chunk file
for _, workRange := range splitWorkLoad(concurrency, Range{Start: i, End: end}) {
// https://github.com/golang/go/wiki/CommonMistakes#using-goroutines-on-loop-iterator-variables
workRange := workRange
taskFile := filepath.Join(outDir, fmt.Sprintf("tmp-%s-%d.snappy", store, workRange.Start))
group.Submit(func() error {
tree := iavlTreePool.Get().(*iavl.ImmutableTree)
defer iavlTreePool.Put(tree)
return dumpRangeBlocks(taskFile, tree, workRange)
})
taskFiles = append(taskFiles, taskFile)
}
chunks = append(chunks, chunk{
store: store, beginVersion: i, taskFiles: taskFiles, taskGroup: group,
})
}
// for each chunk, wait for related tasks to finish, and concatenate the result files in order
for _, chunk := range chunks {
if err := chunk.collect(outDir, zlibLevel); err != nil {
return err
}
}
}
return nil
},
}
cmd.Flags().Int64(flagStartVersion, 0, "The start version")
cmd.Flags().Int64(flagEndVersion, 0, "The end version, exclusive, default to latestVersion+1")
cmd.Flags().Int(flagConcurrency, runtime.NumCPU(), "Number concurrent goroutines to parallelize the work")
cmd.Flags().Int(server.FlagIAVLCacheSize, 781250, "size of the iavl tree cache")
cmd.Flags().Int(flagChunkSize, DefaultChunkSize, "size of the block chunk")
cmd.Flags().Int(flagZlibLevel, 6, "level of zlib compression, 0: plain data, 1: fast, 9: best, default: 6, if not 0 the output file name will have .zz extension")
cmd.Flags().String(flagStores, "", "list of store names, default to the current store list in application")
return cmd
}
type Range struct {
Start, End int64
}
func splitWorkLoad(workers int, full Range) []Range {
var chunks []Range
chunkSize := (full.End - full.Start + int64(workers) - 1) / int64(workers)
for i := full.Start; i < full.End; i += chunkSize {
end := i + chunkSize
if end > full.End {
end = full.End
}
chunks = append(chunks, Range{Start: i, End: end})
}
return chunks
}
func dumpRangeBlocks(outputFile string, tree *iavl.ImmutableTree, blockRange Range) (returnErr error) {
fp, err := createFile(outputFile)
if err != nil {
return err
}
defer func() {
if err := fp.Close(); returnErr == nil {
returnErr = err
}
}()
writer := snappy.NewBufferedWriter(fp)
if err := tree.TraverseStateChanges(blockRange.Start, blockRange.End, func(version int64, changeSet *iavl.ChangeSet) error {
return WriteChangeSet(writer, version, *changeSet)
}); err != nil {
return err
}
return writer.Flush()
}
type chunk struct {
store string
beginVersion int64
taskFiles []string
taskGroup *pond.TaskGroupWithContext
}
// collect wait for the tasks to complete and concatenate the files into a single output file.
func (c *chunk) collect(outDir string, zlibLevel int) (returnErr error) {
storeDir := filepath.Join(outDir, c.store)
if err := os.MkdirAll(storeDir, os.ModePerm); err != nil {
return err
}
output := filepath.Join(storeDir, fmt.Sprintf("block-%d", c.beginVersion))
if zlibLevel > 0 {
output += ZlibFileSuffix
}
if err := c.taskGroup.Wait(); err != nil {
return err
}
fp, err := createFile(output)
if err != nil {
return err
}
defer func() {
if err := fp.Close(); returnErr == nil {
returnErr = err
}
}()
bufWriter := bufio.NewWriter(fp)
writer := io.Writer(bufWriter)
var zwriter *zlib.Writer
if zlibLevel > 0 {
var err error
zwriter, err = zlib.NewWriterLevel(bufWriter, zlibLevel)
if err != nil {
return err
}
writer = zwriter
}
for _, taskFile := range c.taskFiles {
if err := copyTmpFile(writer, taskFile); err != nil {
return err
}
if err := os.Remove(taskFile); err != nil {
return err
}
}
if zwriter != nil {
if err := zwriter.Close(); err != nil {
return err
}
}
return bufWriter.Flush()
}
// copyTmpFile append the snappy compressed temporary file to writer
func copyTmpFile(writer io.Writer, tmpFile string) error {
fp, err := os.Open(tmpFile)
if err != nil {
return err
}
defer fp.Close()
_, err = io.Copy(writer, snappy.NewReader(fp))
return err
}
func createFile(name string) (*os.File, error) {
return os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
}
func getNextVersion(db dbm.DB, version int64) (int64, error) {
itr, err := db.Iterator(
rootKeyFormat.Key(uint64(version+1)),
rootKeyFormat.Key(uint64(math.MaxInt64)),
)
if err != nil {
return 0, err
}
defer itr.Close()
var nversion int64
for ; itr.Valid(); itr.Next() {
rootKeyFormat.Scan(itr.Key(), &nversion)
return nversion, nil
}
if err := itr.Error(); err != nil {
return 0, err
}
return 0, nil
}