gitee.com/lh-her-team/common@v1.5.1/crypto/hsm/plugin.go (about)

     1  package hsm
     2  
     3  import (
     4  	"log"
     5  	"os"
     6  	"plugin"
     7  	"sync"
     8  
     9  	"github.com/pkg/errors"
    10  )
    11  
    12  var once sync.Once
    13  var adapter IHSMAdapter
    14  
    15  func GetHSMAdapter(pluginPath string) IHSMAdapter {
    16  	once.Do(func() {
    17  		var err error
    18  		if adapter, err = Load(pluginPath); err != nil {
    19  			log.Println("load hsm adapter plugin failed, use default dummyAdapter")
    20  			adapter = dummyAdapter{}
    21  		}
    22  	})
    23  	return adapter
    24  }
    25  
    26  func Load(pluginPath string) (IHSMAdapter, error) {
    27  	if len(pluginPath) == 0 {
    28  		pluginPathEnv := os.Getenv("HSM_ADAPTER_LIB")
    29  		log.Printf("invalid pluginPath params[%s], use HSM_ADAPTER_LIB[%s] from env", pluginPath, pluginPathEnv)
    30  		pluginPath = pluginPathEnv
    31  	}
    32  	p, err := plugin.Open(pluginPath)
    33  	if err != nil {
    34  		return nil, errors.WithMessagef(err, "failed to open plugin lib = %s", pluginPath)
    35  	}
    36  	s, err := p.Lookup("Adapter")
    37  	if err != nil {
    38  		return nil, errors.WithMessagef(err, "failed to lookup hsm Adapter")
    39  	}
    40  	adapter, ok := s.(IHSMAdapter)
    41  	if !ok {
    42  		return nil, errors.New("Adapter obj not implement IHSMAdapter interface")
    43  	}
    44  	return adapter, nil
    45  }