Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 20 additions & 12 deletions clients/config_client/config_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,11 @@ func (client *ConfigClient) getConfigInner(param vo.ConfigParam) (content string
response, err := client.configProxy.queryConfig(param.DataId, param.Group, clientConfig.NamespaceId,
clientConfig.TimeoutMs, false, client)
if err != nil {
if _, ok := err.(*nacos_error.NacosError); ok {
nacosErr := err.(*nacos_error.NacosError)
return "", errors.New(nacosErr.Error())
}

logger.Errorf("get config from server error:%v, dataId=%s, group=%s, namespaceId=%s", err,
param.DataId, param.Group, clientConfig.NamespaceId)

Expand Down Expand Up @@ -250,10 +255,14 @@ func (client *ConfigClient) PublishConfig(param vo.ConfigParam) (published bool,
request.AdditionMap["encryptedDataKey"] = param.EncryptedDataKey
rpcClient := client.configProxy.getRpcClient(client)
response, err := client.configProxy.requestProxy(rpcClient, request, constant.DEFAULT_TIMEOUT_MILLS)
if response != nil {
return response.IsSuccess(), err
if err != nil {
return false, err
}
return false, err
if !response.IsSuccess() {
logger.Errorf("[client.PublishConfig] failed ,dataId="+param.DataId+",group="+param.Group+",tenant="+clientConfig.NamespaceId+",msg:%s", response.GetMessage())
return false, errors.New(response.GetMessage())
}
return true, nil
}

func (client *ConfigClient) DeleteConfig(param vo.ConfigParam) (deleted bool, err error) {
Expand All @@ -270,10 +279,14 @@ func (client *ConfigClient) DeleteConfig(param vo.ConfigParam) (deleted bool, er
request := rpc_request.NewConfigRemoveRequest(param.Group, param.DataId, clientConfig.NamespaceId)
rpcClient := client.configProxy.getRpcClient(client)
response, err := client.configProxy.requestProxy(rpcClient, request, constant.DEFAULT_TIMEOUT_MILLS)
if response != nil {
return response.IsSuccess(), err
if err != nil {
return false, err
}
return false, err
if !response.IsSuccess() {
logger.Errorf("[client.DeleteConfig] failed ,dataId="+param.DataId+",group="+param.Group+",tenant="+clientConfig.NamespaceId+",msg:%s", response.GetMessage())
return false, errors.New(response.GetMessage())
}
return true, nil
}

// Cancel Listen Config
Expand Down Expand Up @@ -363,12 +376,7 @@ func (client *ConfigClient) searchConfigInner(param vo.SearchConfigParam) (*mode
logger.Errorf("search config from server error:%+v ", err)
if _, ok := err.(*nacos_error.NacosError); ok {
nacosErr := err.(*nacos_error.NacosError)
if nacosErr.ErrorCode() == "404" {
return nil, errors.New("config not found")
}
if nacosErr.ErrorCode() == "403" {
return nil, errors.New("get config forbidden")
}
return nil, errors.New(nacosErr.Error())
}
return nil, err
}
Expand Down
23 changes: 11 additions & 12 deletions clients/config_client/config_proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package config_client
import (
"context"
"encoding/json"
"github.com/nacos-group/nacos-sdk-go/v2/common/nacos_error"
"net/http"
"strconv"
"time"
Expand Down Expand Up @@ -128,26 +129,24 @@ func (cp *ConfigProxy) queryConfig(dataId, group, tenant string, timeout uint64,
response.ContentType = "text"
}
return response, nil
}

if response.GetErrorCode() == 300 {
} else if response.GetErrorCode() == rpc_response.CONFIG_NOT_FOUND {
cache.WriteConfigToFile(cacheKey, cp.clientConfig.CacheDir, "")
//todo LocalConfigInfoProcessor.saveEncryptDataKeySnapshot
return response, nil
}

if response.GetErrorCode() == 400 {
logger.Errorf(
"[config_rpc_client] [sub-server-error] data can not found , dataId=" + dataId + ",group=" + group + ",tenant=" + tenant)
return nil, nacos_error.NewNacosError(strconv.Itoa(nacos_error.NOT_FOUND), "[config_rpc_client] [sub-server-error] data can not found , dataId="+dataId+
",group="+group+",tenant="+tenant, nil)
} else if response.GetErrorCode() == rpc_response.CONFIG_QUERY_CONFLICT {
logger.Errorf(
"[config_rpc_client] [sub-server-error] get server config being modified concurrently, dataId=%s, group=%s, "+
"tenant=%s", dataId, group, tenant)
return nil, errors.New("data being modified, dataId=" + dataId + ",group=" + group + ",tenant=" + tenant)
}

if response.GetErrorCode() > 0 {
return nil, nacos_error.NewNacosError(strconv.Itoa(nacos_error.CONFLICT), "data being modified, dataId="+dataId+",group="+group+",tenant="+tenant, nil)
} else {
logger.Errorf("[config_rpc_client] [sub-server-error] dataId=%s, group=%s, tenant=%s, code=%+v", dataId, group,
tenant, response)
return nil, nacos_error.NewNacosError(strconv.Itoa(response.GetErrorCode()),
"http error, code="+strconv.Itoa(response.GetErrorCode())+",msg="+response.GetMessage()+",dataId="+dataId+",group="+group+",tenant="+tenant, nil)
}
return response, nil
}

func appName(client *ConfigClient) string {
Expand Down
14 changes: 12 additions & 2 deletions clients/naming_client/naming_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,9 @@ func (sc *NamingClient) RegisterInstance(param vo.RegisterInstanceParam) (bool,
Weight: param.Weight,
Ephemeral: param.Ephemeral,
}
if pass, err := util.CheckInstanceIsLegal(instance); !pass {
return false, err
}
return sc.serviceProxy.RegisterInstance(param.ServiceName, param.GroupName, instance)
}

Expand All @@ -130,7 +133,7 @@ func (sc *NamingClient) BatchRegisterInstance(param vo.BatchRegisterInstancePara
if !param.Ephemeral {
return false, errors.Errorf("Batch registration does not allow persistent instance registration! instance:%+v", param)
}
modelInstances = append(modelInstances, model.Instance{
instance := model.Instance{
Ip: param.Ip,
Port: param.Port,
Metadata: param.Metadata,
Expand All @@ -139,7 +142,11 @@ func (sc *NamingClient) BatchRegisterInstance(param vo.BatchRegisterInstancePara
Enable: param.Enable,
Weight: param.Weight,
Ephemeral: param.Ephemeral,
})
}
if pass, err := util.CheckInstanceIsLegal(instance); !pass {
return false, err
}
modelInstances = append(modelInstances, instance)
}

return sc.serviceProxy.BatchRegisterInstance(param.ServiceName, param.GroupName, modelInstances)
Expand Down Expand Up @@ -180,6 +187,9 @@ func (sc *NamingClient) UpdateInstance(param vo.UpdateInstanceParam) (bool, erro
Weight: param.Weight,
Ephemeral: param.Ephemeral,
}
if pass, err := util.CheckInstanceIsLegal(instance); !pass {
return false, err
}

return sc.serviceProxy.RegisterInstance(param.ServiceName, param.GroupName, instance)

Expand Down
11 changes: 10 additions & 1 deletion clients/naming_client/naming_grpc/naming_grpc_proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ package naming_grpc

import (
"context"
"github.com/nacos-group/nacos-sdk-go/v2/common/nacos_error"
"strconv"
"time"

"github.com/nacos-group/nacos-sdk-go/v2/clients/naming_client/naming_cache"
Expand Down Expand Up @@ -86,6 +88,13 @@ func (proxy *NamingGrpcProxy) requestToServer(request rpc_request.IRequest) (rpc
proxy.nacosServer.InjectSign(request, request.GetHeaders(), proxy.clientConfig)
proxy.nacosServer.InjectSecurityInfo(request.GetHeaders())
response, err := proxy.rpcClient.GetRpcClient().Request(request, int64(proxy.clientConfig.TimeoutMs))
if err != nil {
return nil, err
}
if response.GetResultCode() != 200 {
logger.Errorf("Request nacos server failed:code=" + strconv.Itoa(response.GetErrorCode()) + ",msg=" + response.GetMessage())
return nil, nacos_error.NewNacosError(strconv.Itoa(response.GetErrorCode()), response.GetMessage(), nil)
}
monitor.GetConfigRequestMonitor(constant.GRPC, request.GetRequestType(), rpc_response.GetGrpcResponseStatusCode(response)).Observe(float64(time.Now().Nanosecond() - start.Nanosecond()))
return response, err
}
Expand Down Expand Up @@ -122,10 +131,10 @@ func (proxy *NamingGrpcProxy) DeregisterInstance(serviceName string, groupName s
proxy.clientConfig.NamespaceId, serviceName, instance.Ip, instance.Port, instance.ClusterName)
instanceRequest := rpc_request.NewInstanceRequest(proxy.clientConfig.NamespaceId, serviceName, groupName, "deregisterInstance", instance)
response, err := proxy.requestToServer(instanceRequest)
proxy.eventListener.RemoveInstanceForRedo(serviceName, groupName, instance)
if err != nil {
return false, err
}
proxy.eventListener.RemoveInstanceForRedo(serviceName, groupName, instance)
return response.IsSuccess(), err
}

Expand Down
167 changes: 87 additions & 80 deletions common/constant/const.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,84 +19,91 @@ package constant
import "time"

const (
KEY_USERNAME = "username"
KEY_PASSWORD = "password"
KEY_ENDPOINT = "endpoint"
KEY_NAME_SPACE = "namespace"
KEY_ACCESS_KEY = "accessKey"
KEY_SECRET_KEY = "secretKey"
KEY_SERVER_ADDR = "serverAddr"
KEY_CONTEXT_PATH = "contextPath"
KEY_ENCODE = "encode"
KEY_DATA_ID = "dataId"
KEY_GROUP = "group"
KEY_TENANT = "tenant"
KEY_DESC = "desc"
KEY_APP_NAME = "appName"
KEY_CONTENT = "content"
KEY_TIMEOUT_MS = "timeoutMs"
KEY_LISTEN_INTERVAL = "listenInterval"
KEY_SERVER_CONFIGS = "serverConfigs"
KEY_CLIENT_CONFIG = "clientConfig"
KEY_TOKEN = "token"
KEY_ACCESS_TOKEN = "accessToken"
KEY_TOKEN_TTL = "tokenTtl"
KEY_GLOBAL_ADMIN = "globalAdmin"
KEY_TOKEN_REFRESH_WINDOW = "tokenRefreshWindow"
WEB_CONTEXT = "/nacos"
CONFIG_BASE_PATH = "/v1/cs"
CONFIG_PATH = CONFIG_BASE_PATH + "/configs"
CONFIG_AGG_PATH = "/datum.do"
CONFIG_LISTEN_PATH = CONFIG_BASE_PATH + "/configs/listener"
SERVICE_BASE_PATH = "/v1/ns"
SERVICE_PATH = SERVICE_BASE_PATH + "/instance"
SERVICE_INFO_PATH = SERVICE_BASE_PATH + "/service"
SERVICE_SUBSCRIBE_PATH = SERVICE_PATH + "/list"
NAMESPACE_PATH = "/v1/console/namespaces"
SPLIT_CONFIG = string(rune(1))
SPLIT_CONFIG_INNER = string(rune(2))
KEY_LISTEN_CONFIGS = "Listening-Configs"
KEY_SERVICE_NAME = "serviceName"
KEY_IP = "ip"
KEY_PORT = "port"
KEY_WEIGHT = "weight"
KEY_ENABLE = "enable"
KEY_HEALTHY = "healthy"
KEY_METADATA = "metadata"
KEY_CLUSTER_NAME = "clusterName"
KEY_CLUSTER = "cluster"
KEY_BEAT = "beat"
KEY_DOM = "dom"
DEFAULT_CONTEXT_PATH = "/nacos"
CLIENT_VERSION = "Nacos-Go-Client:v2.2.2"
REQUEST_DOMAIN_RETRY_TIME = 3
SERVICE_INFO_SPLITER = "@@"
CONFIG_INFO_SPLITER = "@@"
DEFAULT_NAMESPACE_ID = "public"
DEFAULT_GROUP = "DEFAULT_GROUP"
NAMING_INSTANCE_ID_SPLITTER = "#"
DefaultClientErrorCode = "SDK.NacosError"
DEFAULT_SERVER_SCHEME = "http"
HTTPS_SERVER_SCHEME = "https"
LABEL_SOURCE = "source"
LABEL_SOURCE_SDK = "sdk"
LABEL_MODULE = "module"
LABEL_MODULE_CONFIG = "config"
LABEL_MODULE_NAMING = "naming"
RESPONSE_CODE_SUCCESS = 200
UN_REGISTER = 301
KEEP_ALIVE_TIME = 5
DEFAULT_TIMEOUT_MILLS = 3000
ALL_SYNC_INTERNAL = 5 * time.Minute
CLIENT_APPNAME_HEADER = "Client-AppName"
APPNAME_HEADER = "AppName"
CLIENT_REQUEST_TS_HEADER = "Client-RequestTS"
CLIENT_REQUEST_TOKEN_HEADER = "Client-RequestToken"
EX_CONFIG_INFO = "exConfigInfo"
CHARSET_KEY = "charset"
LOG_FILE_NAME = "nacos-sdk.log"
HTTPS_SERVER_PORT = 443
GRPC = "grpc"
FAILOVER_FILE_SUFFIX = "_failover"
RpcPortOffset = 1000
KEY_USERNAME = "username"
KEY_PASSWORD = "password"
KEY_ENDPOINT = "endpoint"
KEY_NAME_SPACE = "namespace"
KEY_ACCESS_KEY = "accessKey"
KEY_SECRET_KEY = "secretKey"
KEY_SERVER_ADDR = "serverAddr"
KEY_CONTEXT_PATH = "contextPath"
KEY_ENCODE = "encode"
KEY_DATA_ID = "dataId"
KEY_GROUP = "group"
KEY_TENANT = "tenant"
KEY_DESC = "desc"
KEY_APP_NAME = "appName"
KEY_CONTENT = "content"
KEY_TIMEOUT_MS = "timeoutMs"
KEY_LISTEN_INTERVAL = "listenInterval"
KEY_SERVER_CONFIGS = "serverConfigs"
KEY_CLIENT_CONFIG = "clientConfig"
KEY_TOKEN = "token"
KEY_ACCESS_TOKEN = "accessToken"
KEY_TOKEN_TTL = "tokenTtl"
KEY_GLOBAL_ADMIN = "globalAdmin"
KEY_TOKEN_REFRESH_WINDOW = "tokenRefreshWindow"
WEB_CONTEXT = "/nacos"
CONFIG_BASE_PATH = "/v1/cs"
CONFIG_PATH = CONFIG_BASE_PATH + "/configs"
CONFIG_AGG_PATH = "/datum.do"
CONFIG_LISTEN_PATH = CONFIG_BASE_PATH + "/configs/listener"
SERVICE_BASE_PATH = "/v1/ns"
SERVICE_PATH = SERVICE_BASE_PATH + "/instance"
SERVICE_INFO_PATH = SERVICE_BASE_PATH + "/service"
SERVICE_SUBSCRIBE_PATH = SERVICE_PATH + "/list"
NAMESPACE_PATH = "/v1/console/namespaces"
SPLIT_CONFIG = string(rune(1))
SPLIT_CONFIG_INNER = string(rune(2))
KEY_LISTEN_CONFIGS = "Listening-Configs"
KEY_SERVICE_NAME = "serviceName"
KEY_IP = "ip"
KEY_PORT = "port"
KEY_WEIGHT = "weight"
KEY_ENABLE = "enable"
KEY_HEALTHY = "healthy"
KEY_METADATA = "metadata"
KEY_CLUSTER_NAME = "clusterName"
KEY_CLUSTER = "cluster"
KEY_BEAT = "beat"
KEY_DOM = "dom"
DEFAULT_CONTEXT_PATH = "/nacos"
CLIENT_VERSION = "Nacos-Go-Client:v2.2.2"
REQUEST_DOMAIN_RETRY_TIME = 3
SERVICE_INFO_SPLITER = "@@"
CONFIG_INFO_SPLITER = "@@"
DEFAULT_NAMESPACE_ID = "public"
DEFAULT_GROUP = "DEFAULT_GROUP"
NAMING_INSTANCE_ID_SPLITTER = "#"
DefaultClientErrorCode = "SDK.NacosError"
DEFAULT_SERVER_SCHEME = "http"
HTTPS_SERVER_SCHEME = "https"
LABEL_SOURCE = "source"
LABEL_SOURCE_SDK = "sdk"
LABEL_MODULE = "module"
LABEL_MODULE_CONFIG = "config"
LABEL_MODULE_NAMING = "naming"
RESPONSE_CODE_SUCCESS = 200
UN_REGISTER = 301
KEEP_ALIVE_TIME = 5
DEFAULT_TIMEOUT_MILLS = 3000
ALL_SYNC_INTERNAL = 5 * time.Minute
CLIENT_APPNAME_HEADER = "Client-AppName"
APPNAME_HEADER = "AppName"
CLIENT_REQUEST_TS_HEADER = "Client-RequestTS"
CLIENT_REQUEST_TOKEN_HEADER = "Client-RequestToken"
EX_CONFIG_INFO = "exConfigInfo"
CHARSET_KEY = "charset"
LOG_FILE_NAME = "nacos-sdk.log"
HTTPS_SERVER_PORT = 443
GRPC = "grpc"
FAILOVER_FILE_SUFFIX = "_failover"
RpcPortOffset = 1000
KEY_PRESERVED_HEART_BEAT_TIMEOUT = "preserved.heart.beat.timeout"
KEY_PRESERVED_IP_DELETE_TIMEOUT = "preserved.ip.delete.timeout"
KEY_PRESERVED_HEART_BEAT_INTERVAL = "preserved.heart.beat.interval"
DEFAULT_HEART_BEAT_TIMEOUT = 15000
DEFAULT_IP_DELETE_TIMEOUT = 30000
DEFAULT_HEART_BEAT_INTERVAL = 5000
CLUSTER_NAME_PATTERN_STRING = "^[0-9a-zA-Z-]+$"
)
29 changes: 29 additions & 0 deletions common/nacos_error/nacos_error.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,35 @@ import (
"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
)

const (
/*
* client error code.
* -400 -503 throw exception to user.
*/
CLIENT_INVALID_PARAM = -400 //invalid param(参数错误)
CLIENT_DISCONNECT = -401 //client disconnect.
CLIENT_OVER_THRESHOLD = -503 //over client threshold(超过client端的限流阈值).
RESOURCE_NOT_FOUND = -404
CLIENT_ERROR = -500 //client error(client异常,返回给服务端).

/*
* server error code.
* 400 403 throw exception to user
* 500 502 503 change ip and retry
*/
INVALID_PARAM = 400 //invalid param(参数错误).
NO_RIGHT = 403 //no right(鉴权失败).
NOT_FOUND = 404 //not found.
CONFLICT = 409 //conflict(写并发冲突).
SERVER_ERROR = 500 //server error(server异常,如超时).
BAD_GATEWAY = 502 //bad gateway(路由异常,如nginx后面的Server挂掉).
OVER_THRESHOLD = 503 //over threshold(超过server端的限流阈值).
INVALID_SERVER_STATUS = 300 //Server is not started.
UN_REGISTER = 301 //Connection is not registered.
NO_HANDLER = 302 //No Handler Found.

)

type NacosError struct {
errorCode string
errMsg string
Expand Down
Loading