github.com/myafeier/fabric@v1.0.1-0.20170722181825-3a4b1f2bce86/orderer/common/server/util.go (about) 1 /* 2 Copyright IBM Corp. 2017 All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package server 8 9 import ( 10 "io/ioutil" 11 "os" 12 "path/filepath" 13 14 "github.com/hyperledger/fabric/common/ledger/blkstorage/fsblkstorage" 15 "github.com/hyperledger/fabric/orderer/common/ledger" 16 fileledger "github.com/hyperledger/fabric/orderer/common/ledger/file" 17 jsonledger "github.com/hyperledger/fabric/orderer/common/ledger/json" 18 ramledger "github.com/hyperledger/fabric/orderer/common/ledger/ram" 19 config "github.com/hyperledger/fabric/orderer/common/localconfig" 20 ) 21 22 func createLedgerFactory(conf *config.TopLevel) (ledger.Factory, string) { 23 var lf ledger.Factory 24 var ld string 25 switch conf.General.LedgerType { 26 case "file": 27 ld = conf.FileLedger.Location 28 if ld == "" { 29 ld = createTempDir(conf.FileLedger.Prefix) 30 } 31 logger.Debug("Ledger dir:", ld) 32 lf = fileledger.New(ld) 33 // The file-based ledger stores the blocks for each channel 34 // in a fsblkstorage.ChainsDir sub-directory that we have 35 // to create separately. Otherwise the call to the ledger 36 // Factory's ChainIDs below will fail (dir won't exist). 37 createSubDir(ld, fsblkstorage.ChainsDir) 38 case "json": 39 ld = conf.FileLedger.Location 40 if ld == "" { 41 ld = createTempDir(conf.FileLedger.Prefix) 42 } 43 logger.Debug("Ledger dir:", ld) 44 lf = jsonledger.New(ld) 45 case "ram": 46 fallthrough 47 default: 48 lf = ramledger.New(int(conf.RAMLedger.HistorySize)) 49 } 50 return lf, ld 51 } 52 53 func createTempDir(dirPrefix string) string { 54 dirPath, err := ioutil.TempDir("", dirPrefix) 55 if err != nil { 56 logger.Panic("Error creating temp dir:", err) 57 } 58 return dirPath 59 } 60 61 func createSubDir(parentDirPath string, subDir string) (string, bool) { 62 var created bool 63 subDirPath := filepath.Join(parentDirPath, subDir) 64 if _, err := os.Stat(subDirPath); err != nil { 65 if os.IsNotExist(err) { 66 if err = os.Mkdir(subDirPath, 0755); err != nil { 67 logger.Panic("Error creating sub dir:", err) 68 } 69 created = true 70 } 71 } else { 72 logger.Debugf("Found %s sub-dir and using it", fsblkstorage.ChainsDir) 73 } 74 return subDirPath, created 75 }