github.com/kchristidis/fabric@v1.0.4-0.20171028114726-837acd08cde1/bccsp/factory/factory.go (about) 1 /* 2 Copyright IBM Corp. 2016 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 package factory 17 18 import ( 19 "fmt" 20 "sync" 21 22 "github.com/hyperledger/fabric/bccsp" 23 "github.com/hyperledger/fabric/common/flogging" 24 ) 25 26 var ( 27 // Default BCCSP 28 defaultBCCSP bccsp.BCCSP 29 30 // when InitFactories has not been called yet (should only happen 31 // in test cases), use this BCCSP temporarily 32 bootBCCSP bccsp.BCCSP 33 34 // BCCSP Factories 35 bccspMap map[string]bccsp.BCCSP 36 37 // factories' Sync on Initialization 38 factoriesInitOnce sync.Once 39 bootBCCSPInitOnce sync.Once 40 41 // Factories' Initialization Error 42 factoriesInitError error 43 44 logger = flogging.MustGetLogger("bccsp") 45 ) 46 47 // BCCSPFactory is used to get instances of the BCCSP interface. 48 // A Factory has name used to address it. 49 type BCCSPFactory interface { 50 51 // Name returns the name of this factory 52 Name() string 53 54 // Get returns an instance of BCCSP using opts. 55 Get(opts *FactoryOpts) (bccsp.BCCSP, error) 56 } 57 58 // GetDefault returns a non-ephemeral (long-term) BCCSP 59 func GetDefault() bccsp.BCCSP { 60 if defaultBCCSP == nil { 61 logger.Warning("Before using BCCSP, please call InitFactories(). Falling back to bootBCCSP.") 62 bootBCCSPInitOnce.Do(func() { 63 var err error 64 f := &SWFactory{} 65 bootBCCSP, err = f.Get(GetDefaultOpts()) 66 if err != nil { 67 panic("BCCSP Internal error, failed initialization with GetDefaultOpts!") 68 } 69 }) 70 return bootBCCSP 71 } 72 return defaultBCCSP 73 } 74 75 // GetBCCSP returns a BCCSP created according to the options passed in input. 76 func GetBCCSP(name string) (bccsp.BCCSP, error) { 77 csp, ok := bccspMap[name] 78 if !ok { 79 return nil, fmt.Errorf("Could not find BCCSP, no '%s' provider", name) 80 } 81 return csp, nil 82 } 83 84 func initBCCSP(f BCCSPFactory, config *FactoryOpts) error { 85 csp, err := f.Get(config) 86 if err != nil { 87 return fmt.Errorf("Could not initialize BCCSP %s [%s]", f.Name(), err) 88 } 89 90 logger.Debugf("Initialize BCCSP [%s]", f.Name()) 91 bccspMap[f.Name()] = csp 92 return nil 93 }