github.com/lingyao2333/mo-zero@v1.4.1/core/discov/internal/accountmanager.go (about)

     1  package internal
     2  
     3  import (
     4  	"crypto/tls"
     5  	"crypto/x509"
     6  	"os"
     7  	"sync"
     8  )
     9  
    10  var (
    11  	accounts   = make(map[string]Account)
    12  	tlsConfigs = make(map[string]*tls.Config)
    13  	lock       sync.RWMutex
    14  )
    15  
    16  // Account holds the username/password for an etcd cluster.
    17  type Account struct {
    18  	User string
    19  	Pass string
    20  }
    21  
    22  // AddAccount adds the username/password for the given etcd cluster.
    23  func AddAccount(endpoints []string, user, pass string) {
    24  	lock.Lock()
    25  	defer lock.Unlock()
    26  
    27  	accounts[getClusterKey(endpoints)] = Account{
    28  		User: user,
    29  		Pass: pass,
    30  	}
    31  }
    32  
    33  // AddTLS adds the tls cert files for the given etcd cluster.
    34  func AddTLS(endpoints []string, certFile, certKeyFile, caFile string, insecureSkipVerify bool) error {
    35  	cert, err := tls.LoadX509KeyPair(certFile, certKeyFile)
    36  	if err != nil {
    37  		return err
    38  	}
    39  
    40  	caData, err := os.ReadFile(caFile)
    41  	if err != nil {
    42  		return err
    43  	}
    44  
    45  	pool := x509.NewCertPool()
    46  	pool.AppendCertsFromPEM(caData)
    47  
    48  	lock.Lock()
    49  	defer lock.Unlock()
    50  	tlsConfigs[getClusterKey(endpoints)] = &tls.Config{
    51  		Certificates:       []tls.Certificate{cert},
    52  		RootCAs:            pool,
    53  		InsecureSkipVerify: insecureSkipVerify,
    54  	}
    55  
    56  	return nil
    57  }
    58  
    59  // GetAccount gets the username/password for the given etcd cluster.
    60  func GetAccount(endpoints []string) (Account, bool) {
    61  	lock.RLock()
    62  	defer lock.RUnlock()
    63  
    64  	account, ok := accounts[getClusterKey(endpoints)]
    65  	return account, ok
    66  }
    67  
    68  // GetTLS gets the tls config for the given etcd cluster.
    69  func GetTLS(endpoints []string) (*tls.Config, bool) {
    70  	lock.RLock()
    71  	defer lock.RUnlock()
    72  
    73  	cfg, ok := tlsConfigs[getClusterKey(endpoints)]
    74  	return cfg, ok
    75  }