Skip to content

Commit

Permalink
Merge pull request #19 from nacos-group/develop
Browse files Browse the repository at this point in the history
0.1.0
  • Loading branch information
lzp0412 authored Jul 17, 2019
2 parents 22f4c0b + f7978cb commit 650d958
Show file tree
Hide file tree
Showing 246 changed files with 30,612 additions and 106 deletions.
1 change: 0 additions & 1 deletion .gitignore

This file was deleted.

60 changes: 59 additions & 1 deletion Gopkg.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions Gopkg.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@
branch = "master"
name = "github.com/toolkits/concurrent"

[[constraint]]
name = "github.com/aliyun/alibaba-cloud-sdk-go"
revision = "e6958b522d6f315a3585561bca1f87f6a41fd0c3"

[prune]
go-tests = true
unused-packages = true
7 changes: 2 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@

# nacos-sdk-go

## nacos-go
go语言版本的nacos client,支持服务发现和配置管理

### 客户端配置
Expand Down Expand Up @@ -225,5 +223,4 @@ configClient.ListenConfig(vo.ConfigParam{
},
})

```

```
8 changes: 6 additions & 2 deletions clients/client_factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,12 @@ func setConfig(properties map[string]interface{}) (iClient nacos_client.INacosCl
}
}
} else {
err = errors.New("server configs not found in properties")
return
clientConfig, _ := client.GetClientConfig()
if len(clientConfig.Endpoint) <= 0 {
err = errors.New("server configs not found in properties")
return
}
client.SetServerConfig([]constant.ServerConfig{})
}

iClient = &client
Expand Down
89 changes: 71 additions & 18 deletions clients/config_client/config_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import (
"github.com/nacos-group/nacos-sdk-go/common/util"
"github.com/nacos-group/nacos-sdk-go/utils"
"github.com/nacos-group/nacos-sdk-go/vo"

"github.com/aliyun/alibaba-cloud-sdk-go/services/kms"
"io/ioutil"
"log"
"net/http"
Expand All @@ -23,6 +25,7 @@ import (

type ConfigClient struct {
nacos_client.INacosClient
kmsClient *kms.Client
localConfigs []vo.ConfigParam
mutex sync.Mutex
configProxy ConfigProxy
Expand Down Expand Up @@ -50,6 +53,14 @@ func NewConfigClient(nc nacos_client.INacosClient) (ConfigClient, error) {
}
config.configCacheDir = clientConfig.CacheDir + string(os.PathSeparator) + "config"
config.configProxy, err = NewConfigProxy(serverConfig, clientConfig, httpAgent)
if clientConfig.OpenKMS {
kmsClient, err := kms.NewClientWithAccessKey(clientConfig.RegionId, clientConfig.AccessKey, clientConfig.SecretKey)
if err != nil {
return config, err
}
config.kmsClient = kmsClient
}

return config, err
}

Expand All @@ -75,29 +86,65 @@ func (client *ConfigClient) sync() (clientConfig constant.ClientConfig,
}

func (client *ConfigClient) GetConfig(param vo.ConfigParam) (content string, err error) {
content, err = client.getConfigInner(param)

if err != nil {
return "", err
}

return client.decrypt(param.DataId, content)
}

func (client *ConfigClient) decrypt(dataId, content string) (string, error) {
if strings.HasPrefix(dataId, "cipher-") && client.kmsClient != nil {
request := kms.CreateDecryptRequest()
request.Method = "POST"
request.Scheme = "https"
request.AcceptFormat = "json"
request.CiphertextBlob = content
response, err := client.kmsClient.Decrypt(request)
if err != nil {
return "", errors.New("ksm decrypt failed")
}
content = response.Plaintext
}

return content, nil
}

func (client *ConfigClient) getConfigInner(param vo.ConfigParam) (content string, err error) {
if len(param.DataId) <= 0 {
err = errors.New("[client.GetConfig] param.dataId can not be empty")
}
if len(param.Group) <= 0 {
err = errors.New("[client.GetConfig] param.group can not be empty")
}

clientConfig, _ := client.GetClientConfig()
cacheKey := utils.GetConfigCacheKey(param.DataId, param.Group, clientConfig.NamespaceId)
content, err = client.configProxy.GetConfigProxy(param, clientConfig.NamespaceId)
content, err = client.configProxy.GetConfigProxy(param, clientConfig.NamespaceId, clientConfig.AccessKey, clientConfig.SecretKey)

if err != nil {
log.Printf("[ERROR] get config from server error:%s ", err.Error())
if _, ok := err.(*nacos_error.NacosError); ok {
nacosErr := err.(*nacos_error.NacosError)
if nacosErr.ErrorCode() == "404" {
cache.WriteConfigToFile(cacheKey, client.configCacheDir, "")
return "", errors.New("config not found")
}
if nacosErr.ErrorCode() == "403" {
return "", errors.New("get config forbidden")
}
}
content, err = cache.ReadConfigFromFile(cacheKey, client.configCacheDir)
if err != nil {
log.Printf("[ERROR] get config from cache error:%s ", err.Error())
return "", errors.New("read config from both server and cache fail")
}
return content, nil

} else {
cache.WriteConfigToFile(cacheKey, client.configCacheDir, content)
return content, nil
}

return content, nil
}

func (client *ConfigClient) PublishConfig(param vo.ConfigParam) (published bool,
Expand All @@ -112,7 +159,7 @@ func (client *ConfigClient) PublishConfig(param vo.ConfigParam) (published bool,
err = errors.New("[client.PublishConfig] param.content can not be empty")
}
clientConfig, _ := client.GetClientConfig()
return client.configProxy.PublishConfigProxy(param, clientConfig.NamespaceId)
return client.configProxy.PublishConfigProxy(param, clientConfig.NamespaceId, clientConfig.AccessKey, clientConfig.SecretKey)
}

func (client *ConfigClient) DeleteConfig(param vo.ConfigParam) (deleted bool,
Expand All @@ -125,7 +172,7 @@ func (client *ConfigClient) DeleteConfig(param vo.ConfigParam) (deleted bool,
}

clientConfig, _ := client.GetClientConfig()
return client.configProxy.DeleteConfigProxy(param, clientConfig.NamespaceId)
return client.configProxy.DeleteConfigProxy(param, clientConfig.NamespaceId, clientConfig.AccessKey, clientConfig.SecretKey)
}

func (client *ConfigClient) AddConfigToListen(params []vo.ConfigParam) (err error) {
Expand Down Expand Up @@ -196,15 +243,21 @@ func (client *ConfigClient) listenConfigTask(clientConfig constant.ClientConfig,
if len(param.Content) > 0 {
md5 = util.Md5(param.Content)
}
listeningConfigs += param.DataId + constant.SPLIT_CONFIG_INNER + param.Group + constant.SPLIT_CONFIG_INNER +
md5 + constant.SPLIT_CONFIG_INNER + tenant + constant.SPLIT_CONFIG
client.mutex.Unlock()
if len(tenant) > 0 {
listeningConfigs += param.DataId + constant.SPLIT_CONFIG_INNER + param.Group + constant.SPLIT_CONFIG_INNER +
md5 + constant.SPLIT_CONFIG_INNER + tenant + constant.SPLIT_CONFIG
} else {
listeningConfigs += param.DataId + constant.SPLIT_CONFIG_INNER + param.Group + constant.SPLIT_CONFIG_INNER +
md5 + constant.SPLIT_CONFIG
}

client.mutex.Unlock()
// http 请求
params := make(map[string]string)
params[constant.KEY_LISTEN_CONFIGS] = listeningConfigs
var changed string
for _, serverConfig := range serverConfigs {

for _, serverConfig := range client.configProxy.GetServerList() {
path := client.buildBasePath(serverConfig) + "/listener"
changedTmp, err := listen(agent, path, clientConfig.TimeoutMs, clientConfig.ListenInterval, params)
if err == nil {
Expand Down Expand Up @@ -247,9 +300,7 @@ func listen(agent http_agent.IHttpAgent, path string,
if response.StatusCode == 200 {
changed = string(bytes)
} else {
err = &nacos_error.NacosError{
ErrMsg: "[" + strconv.Itoa(response.StatusCode) + "]" + string(bytes),
}
err = nacos_error.NewNacosError(strconv.Itoa(response.StatusCode), string(bytes), nil)
}
}
}
Expand All @@ -263,7 +314,7 @@ func (client *ConfigClient) updateLocalConfig(changed string, param vo.ConfigPar
for _, config := range changedConfigs {
attrs := strings.Split(config, "%02")
if len(attrs) == 2 {
content, err := client.GetConfig(vo.ConfigParam{
content, err := client.getConfigInner(vo.ConfigParam{
DataId: attrs[0],
Group: attrs[1],
})
Expand All @@ -277,11 +328,12 @@ func (client *ConfigClient) updateLocalConfig(changed string, param vo.ConfigPar
})

// call listener:
param.OnChange("", attrs[1], attrs[0], content)
decrept, _ := client.decrypt(attrs[0], content)
param.OnChange("", attrs[1], attrs[0], decrept)

}
} else if len(attrs) == 3 {
content, err := client.GetConfig(vo.ConfigParam{
content, err := client.getConfigInner(vo.ConfigParam{
DataId: attrs[0],
Group: attrs[1],
})
Expand All @@ -295,7 +347,8 @@ func (client *ConfigClient) updateLocalConfig(changed string, param vo.ConfigPar
})

// call listener:
param.OnChange(attrs[2], attrs[1], attrs[0], content)
decrept, _ := client.decrypt(attrs[0], content)
param.OnChange(attrs[2], attrs[1], attrs[0], decrept)
}
}
}
Expand Down
39 changes: 37 additions & 2 deletions clients/config_client/config_client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ func Test_GetConfig(t *testing.T) {
assert.Equal(t, "hello world!222222", content)
}

func Test_GetConfigWithErrorResponse(t *testing.T) {
func Test_GetConfigWithErrorResponse_401(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
mockHttpAgent := mock.NewMockIHttpAgent(controller)
Expand All @@ -145,8 +145,43 @@ func Test_GetConfigWithErrorResponse(t *testing.T) {
gomock.Eq(clientConfigTest.TimeoutMs),
gomock.Eq(configParamMapTest),
).Times(3).Return(http_agent.FakeHttpResponse(401, "no auth"), nil)
_, err := client.GetConfig(configParamTest)
result, err := client.GetConfig(configParamTest)
assert.Nil(t, err)
fmt.Printf("result:%s \n", result)
}

func Test_GetConfigWithErrorResponse_404(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
mockHttpAgent := mock.NewMockIHttpAgent(controller)
client := cretateConfigClientHttpTest(mockHttpAgent)
mockHttpAgent.EXPECT().Request(gomock.Eq(http.MethodGet),
gomock.Eq("http://console.nacos.io:80/nacos/v1/cs/configs"),
gomock.AssignableToTypeOf(http.Header{}),
gomock.Eq(clientConfigTest.TimeoutMs),
gomock.Eq(configParamMapTest),
).Times(3).Return(http_agent.FakeHttpResponse(404, ""), nil)
reslut, err := client.GetConfig(configParamTest)
assert.NotNil(t, err)
assert.Equal(t, "", reslut)
fmt.Println(err.Error())
}

func Test_GetConfigWithErrorResponse_403(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
mockHttpAgent := mock.NewMockIHttpAgent(controller)
client := cretateConfigClientHttpTest(mockHttpAgent)
mockHttpAgent.EXPECT().Request(gomock.Eq(http.MethodGet),
gomock.Eq("http://console.nacos.io:80/nacos/v1/cs/configs"),
gomock.AssignableToTypeOf(http.Header{}),
gomock.Eq(clientConfigTest.TimeoutMs),
gomock.Eq(configParamMapTest),
).Times(3).Return(http_agent.FakeHttpResponse(403, ""), nil)
reslut, err := client.GetConfig(configParamTest)
assert.NotNil(t, err)
assert.Equal(t, "", reslut)
fmt.Println(err.Error())
}

func Test_GetConfigWithCache(t *testing.T) {
Expand Down
Loading

0 comments on commit 650d958

Please sign in to comment.