feat: support auth account for etcd (#1174)

This commit is contained in:
Kevin Wan
2021-10-31 09:05:38 +08:00
committed by GitHub
parent c1a8ccda11
commit 59b9687f31
15 changed files with 204 additions and 29 deletions

View File

@@ -0,0 +1,31 @@
package internal
import "sync"
type Account struct {
User string
Pass string
}
var (
accounts = make(map[string]Account)
lock sync.RWMutex
)
func AddAccount(endpoints []string, user, pass string) {
lock.Lock()
defer lock.Unlock()
accounts[getClusterKey(endpoints)] = Account{
User: user,
Pass: pass,
}
}
func GetAccount(endpoints []string) (Account, bool) {
lock.RLock()
defer lock.RUnlock()
account, ok := accounts[getClusterKey(endpoints)]
return account, ok
}

View File

@@ -0,0 +1,34 @@
package internal
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/tal-tech/go-zero/core/stringx"
)
func TestAccount(t *testing.T) {
endpoints := []string{
"192.168.0.2:2379",
"192.168.0.3:2379",
"192.168.0.4:2379",
}
username := "foo" + stringx.Rand()
password := "bar"
anotherPassword := "any"
_, ok := GetAccount(endpoints)
assert.False(t, ok)
AddAccount(endpoints, username, password)
account, ok := GetAccount(endpoints)
assert.True(t, ok)
assert.Equal(t, username, account.User)
assert.Equal(t, password, account.Pass)
AddAccount(endpoints, username, anotherPassword)
account, ok = GetAccount(endpoints)
assert.True(t, ok)
assert.Equal(t, username, account.User)
assert.Equal(t, anotherPassword, account.Pass)
}

View File

@@ -302,14 +302,20 @@ func (c *cluster) watchConnState(cli EtcdClient) {
// DialClient dials an etcd cluster with given endpoints.
func DialClient(endpoints []string) (EtcdClient, error) {
return clientv3.New(clientv3.Config{
cfg := clientv3.Config{
Endpoints: endpoints,
AutoSyncInterval: autoSyncInterval,
DialTimeout: DialTimeout,
DialKeepAliveTime: dialKeepAliveTime,
DialKeepAliveTimeout: DialTimeout,
RejectOldCluster: true,
})
}
if account, ok := GetAccount(endpoints); ok {
cfg.Username = account.User
cfg.Password = account.Pass
}
return clientv3.New(cfg)
}
func getClusterKey(endpoints []string) string {

View File

@@ -33,6 +33,7 @@ func setMockClient(cli EtcdClient) func() {
}
func TestGetCluster(t *testing.T) {
AddAccount([]string{"first"}, "foo", "bar")
c1 := GetRegistry().getCluster([]string{"first"})
c2 := GetRegistry().getCluster([]string{"second"})
c3 := GetRegistry().getCluster([]string{"first"})