blockfile_mgr.go 11.2 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
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
/*
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}
		err = mgr.saveCurrentInfo(cpInfo)
		if err != nil {
			panic(fmt.Sprintf("Could not save next block file info to db: %s", err))
		}
	}
	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
	bcInfo := &protos.BlockchainInfo{Height: 0, CurrentBlockHash: nil, PreviousBlockHash: nil}
	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 {
	dbInst := db.CreateDB(&db.Conf{DBPath: conf.dbPath, CFNames: []string{blockIndexCF}})
	dbInst.Open()
	return dbInst
}

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() {
	nextFileInfo := &checkpointInfo{latestFileChunkSuffixNum: mgr.cpInfo.latestFileChunkSuffixNum + 1, latestFileChunksize: 0}
	nextFileWriter, err := newBlockfileWriter(deriveBlockfilePath(mgr.rootDir, nextFileInfo.latestFileChunkSuffixNum))
	if err != nil {
		panic(fmt.Sprintf("Could not open writer to next file: %s", err))
	}
	mgr.currentFileWriter.close()
	err = mgr.saveCurrentInfo(nextFileInfo)
	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()
	if err != nil {
		return fmt.Errorf("Error while serializing block: %s", err)
	}
	currentOffset := mgr.cpInfo.latestFileChunksize
	length := len(blockBytes)
	encodedLen := proto.EncodeVarint(uint64(length))
	totalLen := length + len(encodedLen)
	if currentOffset+totalLen > mgr.conf.maxBlockfileSize {
		mgr.moveToNextFile()
		currentOffset = 0
	}
	err = mgr.currentFileWriter.append(encodedLen)
	if err != nil {
		err1 := mgr.currentFileWriter.truncateFile(mgr.cpInfo.latestFileChunksize)
		if err1 != nil {
			panic(fmt.Sprintf("Could not truncate current file to known size after an error while appending a block: %s", err))
		}
		return fmt.Errorf("Error while appending block to file: %s", err)
	}

	err = mgr.currentFileWriter.append(blockBytes)
	if err != nil {
		err1 := mgr.currentFileWriter.truncateFile(mgr.cpInfo.latestFileChunksize)
		if err1 != nil {
			panic(fmt.Sprintf("Could not truncate current file to known size after an error while appending a block: %s", err))
		}
		return fmt.Errorf("Error while appending block to file: %s", err)
	}

	mgr.cpInfo.latestFileChunksize += totalLen
	mgr.cpInfo.lastBlockNumber++
	err = mgr.saveCurrentInfo(mgr.cpInfo)
	if err != nil {
		mgr.cpInfo.latestFileChunksize -= totalLen
		err1 := mgr.currentFileWriter.truncateFile(mgr.cpInfo.latestFileChunksize)
		if err1 != nil {
			panic(fmt.Sprintf("Could not truncate current file to known size after an error while appending a block: %s", err))
		}
		return fmt.Errorf("Error while saving current file info to db: %s", err)
	}
	blockFLP := &fileLocPointer{fileSuffixNum: mgr.cpInfo.latestFileChunkSuffixNum}
	blockFLP.offset = currentOffset
	mgr.index.indexBlock(mgr.cpInfo.lastBlockNumber, blockHash, blockFLP, length, len(encodedLen), txOffsets)
	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()
	newBCInfo := &protos.BlockchainInfo{Height: currentBCInfo.Height + 1, CurrentBlockHash: latestBlockHash, PreviousBlockHash: latestBlock.PreviousBlockHash}
	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) {
	b, err := mgr.db.Get(mgr.defaultCF, blkMgrInfoKey)
	if err != nil {
		return nil, err
	}
	if b == nil {
		return nil, err
	}
	i := &checkpointInfo{}
	if err = i.unmarshal(b); err != nil {
		return nil, err
	}
	return i, nil
}

func (mgr *blockfileMgr) saveCurrentInfo(i *checkpointInfo) error {
	b, err := i.marshal()
	if err != nil {
		return err
	}
	err = mgr.db.Put(mgr.defaultCF, blkMgrInfoKey, b)
	if err != nil {
		return err
	}
	return nil
}

// blkMgrInfo
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
}