github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/core/access_contoller/crypto/hsm/plugin.go (about) 1 /* 2 Copyright (C) BABEC. All rights reserved. 3 Copyright (C) THL A29 Limited, a Tencent company. All rights reserved. 4 5 SPDX-License-Identifier: Apache-2.0 6 */ 7 8 package hsm 9 10 import ( 11 "log" 12 "os" 13 "plugin" 14 "sync" 15 16 "github.com/pkg/errors" 17 ) 18 19 var once sync.Once 20 var adapter IHSMAdapter 21 22 func GetHSMAdapter(pluginPath string) IHSMAdapter { 23 once.Do(func() { 24 var err error 25 if adapter, err = Load(pluginPath); err != nil { 26 log.Println("load hsm adapter plugin failed, use default dummyAdapter") 27 adapter = dummyAdapter{} 28 } 29 }) 30 return adapter 31 } 32 33 func Load(pluginPath string) (IHSMAdapter, error) { 34 if len(pluginPath) == 0 { 35 pluginPathEnv := os.Getenv("HSM_ADAPTER_LIB") 36 log.Printf("invalid pluginPath params[%s], use HSM_ADAPTER_LIB[%s] from env", pluginPath, pluginPathEnv) 37 pluginPath = pluginPathEnv 38 } 39 p, err := plugin.Open(pluginPath) 40 if err != nil { 41 return nil, errors.WithMessagef(err, "failed to open plugin lib = %s", pluginPath) 42 } 43 s, err := p.Lookup("Adapter") 44 if err != nil { 45 return nil, errors.WithMessagef(err, "failed to lookup hsm Adapter") 46 } 47 48 adapter, ok := s.(IHSMAdapter) 49 if !ok { 50 return nil, errors.New("Adapter obj not implement IHSMAdapter interface") 51 } 52 53 return adapter, nil 54 }