forked from rpcpool/yellowstone-faithful
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd-car-split.go
419 lines (358 loc) · 11 KB
/
cmd-car-split.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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
package main
import (
"bufio"
"bytes"
"context"
"encoding/csv"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strconv"
commcid "github.com/filecoin-project/go-fil-commcid"
commp "github.com/filecoin-project/go-fil-commp-hashhash"
"github.com/filecoin-project/go-leb128"
"github.com/ipfs/go-cid"
"github.com/ipld/go-car"
carv2 "github.com/ipld/go-car/v2"
"github.com/ipld/go-ipld-prime/codec/dagcbor"
"github.com/ipld/go-ipld-prime/datamodel"
"github.com/ipld/go-ipld-prime/fluent/qp"
cidlink "github.com/ipld/go-ipld-prime/linking/cid"
"github.com/ipld/go-ipld-prime/schema"
"github.com/multiformats/go-multicodec"
"github.com/rpcpool/yellowstone-faithful/accum"
"github.com/rpcpool/yellowstone-faithful/carreader"
"github.com/rpcpool/yellowstone-faithful/ipld/ipldbindcode"
"github.com/rpcpool/yellowstone-faithful/iplddecoders"
"github.com/urfave/cli/v2"
"k8s.io/klog/v2"
)
var CBOR_SHA256_DUMMY_CID = cid.MustParse("bafyreics5uul5lbtxslcigtoa5fkba7qgwu7cyb7ih7z6fzsh4lgfgraau")
type subsetInfo struct {
fileName string
firstSlot int
lastSlot int
blockLinks []datamodel.Link
}
type carFile struct {
name string
commP cid.Cid
payloadCid cid.Cid
paddedSize uint64
fileSize int64
}
func newCmd_SplitCar() *cli.Command {
return &cli.Command{
Name: "split-car",
Description: "Splits an epoch car file into smaller chunks. Each chunk corresponds to a subset.",
ArgsUsage: "<epoch-car-path>",
Flags: []cli.Flag{
&cli.Int64Flag{
Name: "size",
Aliases: []string{"s"},
Value: 31 * 1024 * 1024 * 1024, // 31 GiB
Usage: "Target size in bytes to chunk CARs to.",
Required: false,
},
&cli.IntFlag{
Name: "epoch",
Aliases: []string{"e"},
Usage: "Epoch number",
Required: true,
},
&cli.StringFlag{
Name: "metadata",
Aliases: []string{"m"},
Value: "metadata.csv",
Required: false,
Usage: "Filename for metadata. Defaults to metadata.csv",
},
&cli.StringFlag{
Name: "output-dir",
Aliases: []string{"o"},
Usage: "Output directory",
Required: false,
Value: ".",
},
},
Action: func(c *cli.Context) error {
carPath := c.Args().First()
var file fs.File
var err error
if carPath == "-" {
file = os.Stdin
} else {
file, err = os.Open(carPath)
if err != nil {
return fmt.Errorf("failed to open CAR: %w", err)
}
defer file.Close()
}
rd, err := carreader.New(file)
if err != nil {
return fmt.Errorf("failed to open CAR: %w", err)
}
{
// print roots:
roots := rd.Header.Roots
klog.Infof("Roots: %d", len(roots))
for i, root := range roots {
if i == 0 && len(roots) == 1 {
klog.Infof("- %s (Epoch CID)", root.String())
} else {
klog.Infof("- %s", root.String())
}
}
}
epoch := c.Int("epoch")
maxFileSize := c.Int64("size")
outputDir := c.String("output-dir")
meta := c.String("metadata")
if outputDir == "" {
outputDir = "."
}
cp := new(commp.Calc)
var (
currentFileSize int64
currentFileNum int
currentFile *os.File
bufferedWriter *bufio.Writer
currentSubsetInfo subsetInfo
subsetLinks []datamodel.Link
writer io.Writer
carFiles []carFile
)
createNewFile := func() error {
if currentFile != nil {
sl, err := writeSubsetNode(currentSubsetInfo, writer)
if err != nil {
return fmt.Errorf("failed to write subset node: %w", err)
}
subsetLinks = append(subsetLinks, sl)
rawCommP, ps, err := cp.Digest()
if err != nil {
return fmt.Errorf("failed to calculate commp digest: %w", err)
}
commCid, err := commcid.DataCommitmentV1ToCID(rawCommP)
if err != nil {
return fmt.Errorf("failed to calculate commitment to cid: %w", err)
}
cf := carFile{name: fmt.Sprintf("epoch-%d-%d.car", epoch, currentFileNum), commP: commCid, payloadCid: sl.(cidlink.Link).Cid, paddedSize: ps, fileSize: currentFileSize}
carFiles = append(carFiles, cf)
err = closeFile(bufferedWriter, currentFile)
if err != nil {
return fmt.Errorf("failed to close file: %w", err)
}
err = carv2.ReplaceRootsInFile(cf.name, []cid.Cid{cf.payloadCid})
if err != nil {
return fmt.Errorf("failed to replace root: %w", err)
}
cp.Reset()
}
currentFileNum++
filename := filepath.Join(outputDir, fmt.Sprintf("epoch-%d-%d.car", epoch, currentFileNum))
currentFile, err = os.Create(filename)
if err != nil {
return fmt.Errorf("failed to create file %s: %w", filename, err)
}
bufferedWriter = bufio.NewWriter(currentFile)
writer = io.MultiWriter(bufferedWriter, cp)
// Write the header
hdr := car.CarHeader{
Roots: []cid.Cid{CBOR_SHA256_DUMMY_CID}, // placeholder
Version: 1,
}
if err := car.WriteHeader(&hdr, writer); err != nil {
return fmt.Errorf("failed to write header: %w", err)
}
// Set the currentFileSize to the size of the header
currentFileSize = int64(len(nulRootCarHeader))
currentSubsetInfo = subsetInfo{fileName: filename, firstSlot: -1, lastSlot: -1}
return nil
}
writeObject := func(data []byte) error {
_, err := writer.Write(data)
if err != nil {
return fmt.Errorf("failed to write object to car file: %s, error: %w", currentFile.Name(), err)
}
currentFileSize += int64(len(data))
return nil
}
writeBlockDag := func(blockDag []accum.ObjectWithMetadata) error {
for _, owm := range blockDag {
rs, err := owm.RawSection()
if err != nil {
return fmt.Errorf("failed to get raw section: %w", err)
}
err = writeObject(rs)
if err != nil {
return fmt.Errorf("failed to write object: %w", err)
}
}
return nil
}
accum := accum.NewObjectAccumulator(
rd,
iplddecoders.KindBlock,
func(owm1 *accum.ObjectWithMetadata, owm2 []accum.ObjectWithMetadata) error {
if owm1 == nil {
return nil
}
owms := append(owm2, *owm1)
dagSize := 0
for _, owm := range owms {
dagSize += owm.RawSectionSize()
}
if currentFile == nil || currentFileSize+int64(dagSize) > maxFileSize {
err := createNewFile()
if err != nil {
return fmt.Errorf("failed to create a new file: %w", err)
}
}
// owm1 is necessarily a Block
block, err := iplddecoders.DecodeBlock(owm1.ObjectData)
if err != nil {
return fmt.Errorf("failed to decode block: %w", err)
}
if currentSubsetInfo.firstSlot == -1 || block.Slot < currentSubsetInfo.firstSlot {
currentSubsetInfo.firstSlot = block.Slot
}
if block.Slot > currentSubsetInfo.lastSlot {
currentSubsetInfo.lastSlot = block.Slot
}
currentSubsetInfo.blockLinks = append(currentSubsetInfo.blockLinks, cidlink.Link{Cid: owm1.Cid})
err = writeBlockDag(owms)
if err != nil {
return fmt.Errorf("failed to write block dag to file: %w", err)
}
return nil
},
iplddecoders.KindEpoch,
iplddecoders.KindSubset,
)
if err := accum.Run((context.Background())); err != nil {
return fmt.Errorf("failed to run accumulator while accumulating objects: %w", err)
}
sl, err := writeSubsetNode(currentSubsetInfo, writer)
if err != nil {
return fmt.Errorf("failed to write subset node: %w", err)
}
subsetLinks = append(subsetLinks, sl)
epochNode, err := qp.BuildMap(ipldbindcode.Prototypes.Epoch, -1, func(ma datamodel.MapAssembler) {
qp.MapEntry(ma, "kind", qp.Int(int64(iplddecoders.KindEpoch)))
qp.MapEntry(ma, "epoch", qp.Int(int64(epoch)))
qp.MapEntry(ma, "subsets",
qp.List(-1, func(la datamodel.ListAssembler) {
for _, sl := range subsetLinks {
qp.ListEntry(la, qp.Link(sl))
}
}),
)
})
if err != nil {
return fmt.Errorf("failed to construct epochNode: %w", err)
}
_, err = writeNode(epochNode, writer)
if err != nil {
return fmt.Errorf("failed to write epochNode: %w", err)
}
rawCommP, ps, err := cp.Digest()
if err != nil {
return fmt.Errorf("failed to calculate commp digest: %w", err)
}
commCid, err := commcid.DataCommitmentV1ToCID(rawCommP)
if err != nil {
return fmt.Errorf("failed to calculate commitment to cid: %w", err)
}
cf := carFile{name: fmt.Sprintf("epoch-%d-%d.car", epoch, currentFileNum), commP: commCid, payloadCid: sl.(cidlink.Link).Cid, paddedSize: ps, fileSize: currentFileSize}
carFiles = append(carFiles, cf)
err = closeFile(bufferedWriter, currentFile)
if err != nil {
return fmt.Errorf("failed to close file: %w", err)
}
err = carv2.ReplaceRootsInFile(cf.name, []cid.Cid{cf.payloadCid})
if err != nil {
return fmt.Errorf("failed to replace root: %w", err)
}
f, err := os.Create(meta)
defer f.Close()
if err != nil {
return err
}
w := csv.NewWriter(f)
err = w.Write([]string{"car file", "piece cid", "payload cid", "padded piece size", "file size"})
if err != nil {
return err
}
defer w.Flush()
for _, c := range carFiles {
err = w.Write([]string{
c.name,
c.commP.String(),
c.payloadCid.String(),
strconv.FormatUint(c.paddedSize, 10),
strconv.FormatInt(c.fileSize, 10),
})
}
return nil
},
}
}
func writeSubsetNode(currentSubsetInfo subsetInfo, writer io.Writer) (datamodel.Link, error) {
subsetNode, err := qp.BuildMap(ipldbindcode.Prototypes.Subset, -1, func(ma datamodel.MapAssembler) {
qp.MapEntry(ma, "kind", qp.Int(int64(iplddecoders.KindSubset)))
qp.MapEntry(ma, "first", qp.Int(int64(currentSubsetInfo.firstSlot)))
qp.MapEntry(ma, "last", qp.Int(int64(currentSubsetInfo.lastSlot)))
qp.MapEntry(ma, "blocks",
qp.List(-1, func(la datamodel.ListAssembler) {
for _, bl := range currentSubsetInfo.blockLinks {
qp.ListEntry(la, qp.Link(bl))
}
}))
})
if err != nil {
return nil, fmt.Errorf("failed to write a subsetNode: %w", err)
}
cid, err := writeNode(subsetNode, writer)
if err != nil {
return nil, fmt.Errorf("failed to write a subsetNode: %w", err)
}
return cidlink.Link{Cid: cid}, nil
}
func closeFile(bufferedWriter *bufio.Writer, currentFile *os.File) error {
err := bufferedWriter.Flush()
if err != nil {
return fmt.Errorf("failed to flush buffer: %w", err)
}
err = currentFile.Close()
if err != nil {
return fmt.Errorf("failed to close file: %w", err)
}
return nil
}
func writeNode(node datamodel.Node, w io.Writer) (cid.Cid, error) {
node = node.(schema.TypedNode).Representation()
var buf bytes.Buffer
err := dagcbor.Encode(node, &buf)
if err != nil {
return cid.Cid{}, err
}
data := buf.Bytes()
bd := cid.V1Builder{MhLength: -1, MhType: uint64(multicodec.Sha2_256), Codec: uint64(multicodec.DagCbor)}
cd, err := bd.Sum(data)
if err != nil {
return cid.Cid{}, err
}
c := cd.Bytes()
sizeVi := leb128.FromUInt64(uint64(len(c)) + uint64(len(data)))
if _, err := w.Write(sizeVi); err == nil {
if _, err := w.Write(c); err == nil {
if _, err := w.Write(data); err != nil {
return cid.Cid{}, err
}
}
}
return cd, nil
}