github.com/kchristidis/fabric@v1.0.4-0.20171028114726-837acd08cde1/orderer/ledger/file/factory.go (about) 1 /* 2 Copyright IBM Corp. 2017 All Rights Reserved. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package fileledger 18 19 import ( 20 "sync" 21 22 "github.com/hyperledger/fabric/common/ledger/blkstorage" 23 "github.com/hyperledger/fabric/common/ledger/blkstorage/fsblkstorage" 24 "github.com/hyperledger/fabric/orderer/ledger" 25 ) 26 27 type fileLedgerFactory struct { 28 blkstorageProvider blkstorage.BlockStoreProvider 29 ledgers map[string]ledger.ReadWriter 30 mutex sync.Mutex 31 } 32 33 // GetOrCreate gets an existing ledger (if it exists) or creates it if it does not 34 func (flf *fileLedgerFactory) GetOrCreate(chainID string) (ledger.ReadWriter, error) { 35 flf.mutex.Lock() 36 defer flf.mutex.Unlock() 37 38 key := chainID 39 // check cache 40 ledger, ok := flf.ledgers[key] 41 if ok { 42 return ledger, nil 43 } 44 // open fresh 45 blockStore, err := flf.blkstorageProvider.OpenBlockStore(key) 46 if err != nil { 47 return nil, err 48 } 49 ledger = &fileLedger{blockStore: blockStore, signal: make(chan struct{})} 50 flf.ledgers[key] = ledger 51 return ledger, nil 52 } 53 54 // ChainIDs returns the chain IDs the factory is aware of 55 func (flf *fileLedgerFactory) ChainIDs() []string { 56 chainIDs, err := flf.blkstorageProvider.List() 57 if err != nil { 58 logger.Panic(err) 59 } 60 return chainIDs 61 } 62 63 // Close releases all resources acquired by the factory 64 func (flf *fileLedgerFactory) Close() { 65 flf.blkstorageProvider.Close() 66 } 67 68 // New creates a new ledger factory 69 func New(directory string) ledger.Factory { 70 return &fileLedgerFactory{ 71 blkstorageProvider: fsblkstorage.NewProvider( 72 fsblkstorage.NewConf(directory, -1), 73 &blkstorage.IndexConfig{ 74 AttrsToIndex: []blkstorage.IndexableAttr{blkstorage.IndexableAttrBlockNum}}, 75 ), 76 ledgers: make(map[string]ledger.ReadWriter), 77 } 78 }