blockfile_mgr.go 13.3 KB
Newer Older
manish's avatar
manish committed
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
/*
Copyright IBM Corp. 2016 All Rights Reserved.

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 fsblkstorage

import (
	"fmt"
	"sync/atomic"

	"github.com/golang/protobuf/proto"
	"github.com/hyperledger/fabric/core/ledgernext/util"
	"github.com/hyperledger/fabric/core/ledgernext/util/db"
	"github.com/hyperledger/fabric/protos"
	"github.com/op/go-logging"
	"github.com/tecbot/gorocksdb"
)

var logger = logging.MustGetLogger("kvledger")

const (
	blockIndexCF    = "blockIndexCF"
	blockfilePrefix = "blockfile_"
)

var (
	blkMgrInfoKey = []byte("blkMgrInfo")
)

type blockfileMgr struct {
	rootDir           string
	conf              *Conf
	db                *db.DB
	defaultCF         *gorocksdb.ColumnFamilyHandle
	index             *blockIndex
	cpInfo            *checkpointInfo
	currentFileWriter *blockfileWriter
	bcInfo            atomic.Value
}

func newBlockfileMgr(conf *Conf) *blockfileMgr {
	rootDir := conf.blockfilesDir
	_, err := util.CreateDirIfMissing(rootDir)
	if err != nil {
		panic(fmt.Sprintf("Error: %s", err))
	}
	db := initDB(conf)
	mgr := &blockfileMgr{rootDir: rootDir, conf: conf, db: db, defaultCF: db.GetDefaultCFHandle()}
	cpInfo, err := mgr.loadCurrentInfo()
	if err != nil {
		panic(fmt.Sprintf("Could not get block file info for current block file from db: %s", err))
	}
	if cpInfo == nil {
		cpInfo = &checkpointInfo{latestFileChunkSuffixNum: 0, latestFileChunksize: 0}
manish's avatar
manish committed
67
		err = mgr.saveCurrentInfo(cpInfo, true)
manish's avatar
manish committed
68
69
70
71
		if err != nil {
			panic(fmt.Sprintf("Could not save next block file info to db: %s", err))
		}
	}
manish's avatar
manish committed
72
	updateCPInfo(conf, cpInfo)
manish's avatar
manish committed
73
74
75
76
77
78
79
80
81
82
83
84
85
	currentFileWriter, err := newBlockfileWriter(deriveBlockfilePath(rootDir, cpInfo.latestFileChunkSuffixNum))
	if err != nil {
		panic(fmt.Sprintf("Could not open writer to current file: %s", err))
	}
	err = currentFileWriter.truncateFile(cpInfo.latestFileChunksize)
	if err != nil {
		panic(fmt.Sprintf("Could not truncate current file to known size in db: %s", err))
	}

	mgr.index = newBlockIndex(db)
	mgr.cpInfo = cpInfo
	mgr.currentFileWriter = currentFileWriter
	// init BlockchainInfo
manish's avatar
manish committed
86
87
88
89
90
	bcInfo := &protos.BlockchainInfo{
		Height:            0,
		CurrentBlockHash:  nil,
		PreviousBlockHash: nil}

manish's avatar
manish committed
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
	if cpInfo.lastBlockNumber > 0 {
		lastBlock, err := mgr.retrieveSerBlockByNumber(cpInfo.lastBlockNumber)
		if err != nil {
			panic(fmt.Sprintf("Could not retrieve last block form file: %s", err))
		}
		lastBlockHash := lastBlock.ComputeHash()
		previousBlockHash, err := lastBlock.GetPreviousBlockHash()
		if err != nil {
			panic(fmt.Sprintf("Error in decoding block: %s", err))
		}
		bcInfo = &protos.BlockchainInfo{
			Height:            cpInfo.lastBlockNumber,
			CurrentBlockHash:  lastBlockHash,
			PreviousBlockHash: previousBlockHash}
	}
	mgr.bcInfo.Store(bcInfo)
	return mgr
}

func initDB(conf *Conf) *db.DB {
manish's avatar
manish committed
111
112
113
114
115
	dbInst := db.CreateDB(&db.Conf{
		DBPath:     conf.dbPath,
		CFNames:    []string{blockIndexCF},
		DisableWAL: true})

manish's avatar
manish committed
116
117
118
119
	dbInst.Open()
	return dbInst
}

manish's avatar
manish committed
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
func updateCPInfo(conf *Conf, cpInfo *checkpointInfo) {
	logger.Debugf("Starting checkpoint=%s", cpInfo)
	rootDir := conf.blockfilesDir
	filePath := deriveBlockfilePath(rootDir, cpInfo.latestFileChunkSuffixNum)
	exists, size, err := util.FileExists(filePath)
	if err != nil {
		panic(fmt.Sprintf("Error in checking whether file [%s] exists: %s", filePath, err))
	}
	logger.Debugf("status of file [%s]: exists=[%t], size=[%d]", filePath, exists, size)
	if !exists || int(size) == cpInfo.latestFileChunksize {
		// check point info is in sync with the file on disk
		return
	}
	endOffsetLastBlock, numBlocks, err := scanForLastCompleteBlock(filePath, int64(cpInfo.latestFileChunksize))
	if err != nil {
		panic(fmt.Sprintf("Could not open current file for detecting last block in the file: %s", err))
	}
	cpInfo.lastBlockNumber += uint64(numBlocks)
	cpInfo.latestFileChunksize = int(endOffsetLastBlock)
	logger.Debugf("Checkpoint after updates by scanning the last file segment:%s", cpInfo)
}

manish's avatar
manish committed
142
143
144
145
146
147
148
149
150
151
152
153
154
155
func deriveBlockfilePath(rootDir string, suffixNum int) string {
	return rootDir + "/" + blockfilePrefix + fmt.Sprintf("%06d", suffixNum)
}

func (mgr *blockfileMgr) open() error {
	return mgr.currentFileWriter.open()
}

func (mgr *blockfileMgr) close() {
	mgr.currentFileWriter.close()
	mgr.db.Close()
}

func (mgr *blockfileMgr) moveToNextFile() {
manish's avatar
manish committed
156
157
158
159
160
161
162
	nextFileInfo := &checkpointInfo{
		latestFileChunkSuffixNum: mgr.cpInfo.latestFileChunkSuffixNum + 1,
		latestFileChunksize:      0}

	nextFileWriter, err := newBlockfileWriter(
		deriveBlockfilePath(mgr.rootDir, nextFileInfo.latestFileChunkSuffixNum))

manish's avatar
manish committed
163
164
165
166
	if err != nil {
		panic(fmt.Sprintf("Could not open writer to next file: %s", err))
	}
	mgr.currentFileWriter.close()
manish's avatar
manish committed
167
	err = mgr.saveCurrentInfo(nextFileInfo, true)
manish's avatar
manish committed
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
	if err != nil {
		panic(fmt.Sprintf("Could not save next block file info to db: %s", err))
	}
	mgr.cpInfo = nextFileInfo
	mgr.currentFileWriter = nextFileWriter
}

func (mgr *blockfileMgr) addBlock(block *protos.Block2) error {
	serBlock, err := protos.ConstructSerBlock2(block)
	if err != nil {
		return fmt.Errorf("Error while serializing block: %s", err)
	}
	blockBytes := serBlock.GetBytes()
	blockHash := serBlock.ComputeHash()
	txOffsets, err := serBlock.GetTxOffsets()
manish's avatar
manish committed
183
	currentOffset := mgr.cpInfo.latestFileChunksize
manish's avatar
manish committed
184
185
186
	if err != nil {
		return fmt.Errorf("Error while serializing block: %s", err)
	}
manish's avatar
manish committed
187
188
189
190
191
	blockBytesLen := len(blockBytes)
	blockBytesEncodedLen := proto.EncodeVarint(uint64(blockBytesLen))
	totalBytesToAppend := blockBytesLen + len(blockBytesEncodedLen)

	if currentOffset+totalBytesToAppend > mgr.conf.maxBlockfileSize {
manish's avatar
manish committed
192
193
194
		mgr.moveToNextFile()
		currentOffset = 0
	}
manish's avatar
manish committed
195
196
197
	err = mgr.currentFileWriter.append(blockBytesEncodedLen, false)
	if err == nil {
		err = mgr.currentFileWriter.append(blockBytes, true)
manish's avatar
manish committed
198
199
	}
	if err != nil {
manish's avatar
manish committed
200
201
202
		truncateErr := mgr.currentFileWriter.truncateFile(mgr.cpInfo.latestFileChunksize)
		if truncateErr != nil {
			panic(fmt.Sprintf("Could not truncate current file to known size after an error during block append: %s", err))
manish's avatar
manish committed
203
204
205
206
		}
		return fmt.Errorf("Error while appending block to file: %s", err)
	}

manish's avatar
manish committed
207
	mgr.cpInfo.latestFileChunksize += totalBytesToAppend
manish's avatar
manish committed
208
	mgr.cpInfo.lastBlockNumber++
manish's avatar
manish committed
209
	err = mgr.saveCurrentInfo(mgr.cpInfo, false)
manish's avatar
manish committed
210
	if err != nil {
manish's avatar
manish committed
211
212
213
214
		mgr.cpInfo.latestFileChunksize -= totalBytesToAppend
		truncateErr := mgr.currentFileWriter.truncateFile(mgr.cpInfo.latestFileChunksize)
		if truncateErr != nil {
			panic(fmt.Sprintf("Error in truncating current file to known size after an error in saving checkpoint info: %s", err))
manish's avatar
manish committed
215
216
217
218
219
		}
		return fmt.Errorf("Error while saving current file info to db: %s", err)
	}
	blockFLP := &fileLocPointer{fileSuffixNum: mgr.cpInfo.latestFileChunkSuffixNum}
	blockFLP.offset = currentOffset
manish's avatar
manish committed
220
	mgr.index.indexBlock(mgr.cpInfo.lastBlockNumber, blockHash, blockFLP, blockBytesLen, len(blockBytesEncodedLen), txOffsets)
manish's avatar
manish committed
221
222
223
224
225
226
227
228
229
230
	mgr.updateBlockchainInfo(blockHash, block)
	return nil
}

func (mgr *blockfileMgr) getBlockchainInfo() *protos.BlockchainInfo {
	return mgr.bcInfo.Load().(*protos.BlockchainInfo)
}

func (mgr *blockfileMgr) updateBlockchainInfo(latestBlockHash []byte, latestBlock *protos.Block2) {
	currentBCInfo := mgr.getBlockchainInfo()
manish's avatar
manish committed
231
232
233
234
235
	newBCInfo := &protos.BlockchainInfo{
		Height:            currentBCInfo.Height + 1,
		CurrentBlockHash:  latestBlockHash,
		PreviousBlockHash: latestBlock.PreviousBlockHash}

manish's avatar
manish committed
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
	mgr.bcInfo.Store(newBCInfo)
}

func (mgr *blockfileMgr) retrieveBlockByHash(blockHash []byte) (*protos.Block2, error) {
	logger.Debugf("retrieveBlockByHash() - blockHash = [%#v]", blockHash)
	loc, err := mgr.index.getBlockLocByHash(blockHash)
	if err != nil {
		return nil, err
	}
	return mgr.fetchBlock(loc)
}

func (mgr *blockfileMgr) retrieveBlockByNumber(blockNum uint64) (*protos.Block2, error) {
	logger.Debugf("retrieveBlockByNumber() - blockNum = [%d]", blockNum)
	loc, err := mgr.index.getBlockLocByBlockNum(blockNum)
	if err != nil {
		return nil, err
	}
	return mgr.fetchBlock(loc)
}

func (mgr *blockfileMgr) retrieveSerBlockByNumber(blockNum uint64) (*protos.SerBlock2, error) {
	logger.Debugf("retrieveSerBlockByNumber() - blockNum = [%d]", blockNum)
	loc, err := mgr.index.getBlockLocByBlockNum(blockNum)
	if err != nil {
		return nil, err
	}
	return mgr.fetchSerBlock(loc)
}

func (mgr *blockfileMgr) retrieveBlocks(startNum uint64, endNum uint64) (*BlocksItr, error) {
	var lp *fileLocPointer
	var err error
	if lp, err = mgr.index.getBlockLocByBlockNum(startNum); err != nil {
		return nil, err
	}
	filePath := deriveBlockfilePath(mgr.rootDir, lp.fileSuffixNum)

	var stream *blockStream
	if stream, err = newBlockStream(filePath, int64(lp.offset)); err != nil {
		return nil, err
	}
	return newBlockItr(stream, int(endNum-startNum)+1), nil
}

func (mgr *blockfileMgr) retrieveTransactionByID(txID string) (*protos.Transaction2, error) {
	logger.Debugf("retrieveTransactionByID() - txId = [%s]", txID)
	loc, err := mgr.index.getTxLoc(txID)
	if err != nil {
		return nil, err
	}
	return mgr.fetchTransaction(loc)
}

func (mgr *blockfileMgr) fetchBlock(lp *fileLocPointer) (*protos.Block2, error) {
	serBlock, err := mgr.fetchSerBlock(lp)
	if err != nil {
		return nil, err
	}
	block, err := serBlock.ToBlock2()
	if err != nil {
		return nil, err
	}
	return block, nil
}

func (mgr *blockfileMgr) fetchSerBlock(lp *fileLocPointer) (*protos.SerBlock2, error) {
	blockBytes, err := mgr.fetchBlockBytes(lp)
	if err != nil {
		return nil, err
	}
	return protos.NewSerBlock2(blockBytes), nil
}

func (mgr *blockfileMgr) fetchTransaction(lp *fileLocPointer) (*protos.Transaction2, error) {
	txBytes, err := mgr.fetchRawBytes(lp)
	if err != nil {
		return nil, err
	}
	tx := &protos.Transaction2{}
	err = proto.Unmarshal(txBytes, tx)
	if err != nil {
		return nil, err
	}
	return tx, nil
}

func (mgr *blockfileMgr) fetchBlockBytes(lp *fileLocPointer) ([]byte, error) {
	filePath := deriveBlockfilePath(mgr.rootDir, lp.fileSuffixNum)
	stream, err := newBlockStream(filePath, int64(lp.offset))
	if err != nil {
		return nil, err
	}
	defer stream.close()
	b, err := stream.nextBlockBytes()
	if err != nil {
		return nil, err
	}
	return b, nil
}

func (mgr *blockfileMgr) fetchRawBytes(lp *fileLocPointer) ([]byte, error) {
	filePath := deriveBlockfilePath(mgr.rootDir, lp.fileSuffixNum)
	reader, err := newBlockfileReader(filePath)
	if err != nil {
		return nil, err
	}
	defer reader.close()
	b, err := reader.read(lp.offset, lp.bytesLength)
	if err != nil {
		return nil, err
	}
	return b, nil
}

func (mgr *blockfileMgr) loadCurrentInfo() (*checkpointInfo, error) {
manish's avatar
manish committed
352
353
354
	var b []byte
	var err error
	if b, err = mgr.db.Get(mgr.defaultCF, blkMgrInfoKey); b == nil || err != nil {
manish's avatar
manish committed
355
356
357
358
359
360
		return nil, err
	}
	i := &checkpointInfo{}
	if err = i.unmarshal(b); err != nil {
		return nil, err
	}
manish's avatar
manish committed
361
	logger.Debugf("loaded checkpointInfo:%s", i)
manish's avatar
manish committed
362
363
364
	return i, nil
}

manish's avatar
manish committed
365
func (mgr *blockfileMgr) saveCurrentInfo(i *checkpointInfo, flush bool) error {
manish's avatar
manish committed
366
367
368
369
	b, err := i.marshal()
	if err != nil {
		return err
	}
manish's avatar
manish committed
370
	if err = mgr.db.Put(mgr.defaultCF, blkMgrInfoKey, b); err != nil {
manish's avatar
manish committed
371
372
		return err
	}
manish's avatar
manish committed
373
374
375
376
377
378
	if flush {
		if err = mgr.db.Flush(true); err != nil {
			return err
		}
		logger.Debugf("saved checkpointInfo:%s", i)
	}
manish's avatar
manish committed
379
380
381
	return nil
}

manish's avatar
manish committed
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
func scanForLastCompleteBlock(filePath string, startingOffset int64) (int64, int, error) {
	logger.Debugf("scanForLastCompleteBlock(): filePath=[%s], startingOffset=[%d]", filePath, startingOffset)
	numBlocks := 0
	blockStream, err := newBlockStream(filePath, startingOffset)
	if err != nil {
		return 0, 0, err
	}
	defer blockStream.close()
	for {
		blockBytes, err := blockStream.nextBlockBytes()
		if blockBytes == nil || err != nil {
			logger.Debugf(`scanForLastCompleteBlock(): error=[%s].
			This may happen if a crash has happened during block appending.
			Returning current offset as a last complete block's end offset`, err)
			break
		}
		numBlocks++
	}
	logger.Debugf("scanForLastCompleteBlock(): last complete block ends at offset=[%d]", blockStream.currentFileOffset)
	return blockStream.currentFileOffset, numBlocks, err
}

// checkpointInfo
manish's avatar
manish committed
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
type checkpointInfo struct {
	latestFileChunkSuffixNum int
	latestFileChunksize      int
	lastBlockNumber          uint64
}

func (i *checkpointInfo) marshal() ([]byte, error) {
	buffer := proto.NewBuffer([]byte{})
	var err error
	if err = buffer.EncodeVarint(uint64(i.latestFileChunkSuffixNum)); err != nil {
		return nil, err
	}
	if err = buffer.EncodeVarint(uint64(i.latestFileChunksize)); err != nil {
		return nil, err
	}
	if err = buffer.EncodeVarint(i.lastBlockNumber); err != nil {
		return nil, err
	}
	return buffer.Bytes(), nil
}

func (i *checkpointInfo) unmarshal(b []byte) error {
	buffer := proto.NewBuffer(b)
	var val uint64
	var err error

	if val, err = buffer.DecodeVarint(); err != nil {
		return err
	}
	i.latestFileChunkSuffixNum = int(val)

	if val, err = buffer.DecodeVarint(); err != nil {
		return err
	}
	i.latestFileChunksize = int(val)

	if val, err = buffer.DecodeVarint(); err != nil {
		return err
	}
	i.lastBlockNumber = val

	return nil
}
manish's avatar
manish committed
448
449
450
451
452

func (i *checkpointInfo) String() string {
	return fmt.Sprintf("latestFileChunkSuffixNum=[%d], latestFileChunksize=[%d], lastBlockNumber=[%d]",
		i.latestFileChunkSuffixNum, i.latestFileChunksize, i.lastBlockNumber)
}