diff --git a/cluster/cluster_impl/base_cluster_invoker_test.go b/cluster/cluster_impl/base_cluster_invoker_test.go index 695ffcddbbce5a1c65f806b4561670d726588aaa..8121e5c0eab16b92b323fbc0e6e944231d1ed1b9 100644 --- a/cluster/cluster_impl/base_cluster_invoker_test.go +++ b/cluster/cluster_impl/base_cluster_invoker_test.go @@ -33,10 +33,15 @@ import ( "github.com/apache/dubbo-go/protocol/invocation" ) +const ( + baseClusterInvokerMethodName = "getUser" + baseClusterInvokerFormat = "dubbo://192.168.1.%v:20000/com.ikurento.user.UserProvider" +) + func TestStickyNormal(t *testing.T) { invokers := []protocol.Invoker{} for i := 0; i < 10; i++ { - url, _ := common.NewURL(fmt.Sprintf("dubbo://192.168.1.%v:20000/com.ikurento.user.UserProvider", i)) + url, _ := common.NewURL(fmt.Sprintf(baseClusterInvokerFormat, i)) url.SetParam("sticky", "true") invokers = append(invokers, NewMockInvoker(url, 1)) } @@ -45,7 +50,7 @@ func TestStickyNormal(t *testing.T) { invoked := []protocol.Invoker{} tmpRandomBalance := loadbalance.NewRandomLoadBalance() - tmpInvocation := invocation.NewRPCInvocation("getUser", nil, nil) + tmpInvocation := invocation.NewRPCInvocation(baseClusterInvokerMethodName, nil, nil) result := base.doSelect(tmpRandomBalance, tmpInvocation, invokers, invoked) result1 := base.doSelect(tmpRandomBalance, tmpInvocation, invokers, invoked) assert.Equal(t, result, result1) @@ -54,7 +59,7 @@ func TestStickyNormal(t *testing.T) { func TestStickyNormalWhenError(t *testing.T) { invokers := []protocol.Invoker{} for i := 0; i < 10; i++ { - url, _ := common.NewURL(fmt.Sprintf("dubbo://192.168.1.%v:20000/com.ikurento.user.UserProvider", i)) + url, _ := common.NewURL(fmt.Sprintf(baseClusterInvokerFormat, i)) url.SetParam("sticky", "true") invokers = append(invokers, NewMockInvoker(url, 1)) } @@ -62,8 +67,8 @@ func TestStickyNormalWhenError(t *testing.T) { base.availablecheck = true invoked := []protocol.Invoker{} - result := base.doSelect(loadbalance.NewRandomLoadBalance(), invocation.NewRPCInvocation("getUser", nil, nil), invokers, invoked) + result := base.doSelect(loadbalance.NewRandomLoadBalance(), invocation.NewRPCInvocation(baseClusterInvokerMethodName, nil, nil), invokers, invoked) invoked = append(invoked, result) - result1 := base.doSelect(loadbalance.NewRandomLoadBalance(), invocation.NewRPCInvocation("getUser", nil, nil), invokers, invoked) + result1 := base.doSelect(loadbalance.NewRandomLoadBalance(), invocation.NewRPCInvocation(baseClusterInvokerMethodName, nil, nil), invokers, invoked) assert.NotEqual(t, result, result1) } diff --git a/cluster/cluster_impl/failback_cluster_invoker.go b/cluster/cluster_impl/failback_cluster_invoker.go index 46b0ff634e56c45223a5aeb5566b9b1401518960..af17a93756a6f558c7da063eec9d8052b83cbe69 100644 --- a/cluster/cluster_impl/failback_cluster_invoker.go +++ b/cluster/cluster_impl/failback_cluster_invoker.go @@ -72,6 +72,19 @@ func newFailbackClusterInvoker(directory cluster.Directory) protocol.Invoker { return invoker } +func (invoker *failbackClusterInvoker) tryTimerTaskProc(ctx context.Context, retryTask *retryTimerTask) { + invoked := make([]protocol.Invoker, 0) + invoked = append(invoked, retryTask.lastInvoker) + + retryInvoker := invoker.doSelect(retryTask.loadbalance, retryTask.invocation, retryTask.invokers, invoked) + var result protocol.Result + result = retryInvoker.Invoke(ctx, retryTask.invocation) + if result.Error() != nil { + retryTask.lastInvoker = retryInvoker + invoker.checkRetry(retryTask, result.Error()) + } +} + func (invoker *failbackClusterInvoker) process(ctx context.Context) { invoker.ticker = time.NewTicker(time.Second * 1) for range invoker.ticker.C { @@ -91,25 +104,11 @@ func (invoker *failbackClusterInvoker) process(ctx context.Context) { } // ignore return. the get must success. - _, err = invoker.taskList.Get(1) - if err != nil { + if _, err = invoker.taskList.Get(1); err != nil { logger.Warnf("get task found err: %v\n", err) break } - - go func(retryTask *retryTimerTask) { - invoked := make([]protocol.Invoker, 0) - invoked = append(invoked, retryTask.lastInvoker) - - retryInvoker := invoker.doSelect(retryTask.loadbalance, retryTask.invocation, retryTask.invokers, invoked) - var result protocol.Result - result = retryInvoker.Invoke(ctx, retryTask.invocation) - if result.Error() != nil { - retryTask.lastInvoker = retryInvoker - invoker.checkRetry(retryTask, result.Error()) - } - }(retryTask) - + go invoker.tryTimerTaskProc(ctx, retryTask) } } } @@ -129,29 +128,26 @@ func (invoker *failbackClusterInvoker) checkRetry(retryTask *retryTimerTask, err func (invoker *failbackClusterInvoker) Invoke(ctx context.Context, invocation protocol.Invocation) protocol.Result { invokers := invoker.directory.List(invocation) - err := invoker.checkInvokers(invokers, invocation) - if err != nil { + if err := invoker.checkInvokers(invokers, invocation); err != nil { logger.Errorf("Failed to invoke the method %v in the service %v, wait for retry in background. Ignored exception: %v.\n", invocation.MethodName(), invoker.GetUrl().Service(), err) return &protocol.RPCResult{} } - url := invokers[0].GetUrl() - methodName := invocation.MethodName() + //Get the service loadbalance config + url := invokers[0].GetUrl() lb := url.GetParam(constant.LOADBALANCE_KEY, constant.DEFAULT_LOADBALANCE) - //Get the service method loadbalance config if have + methodName := invocation.MethodName() if v := url.GetMethodParam(methodName, constant.LOADBALANCE_KEY, ""); v != "" { lb = v } - loadbalance := extension.GetLoadbalance(lb) + loadBalance := extension.GetLoadbalance(lb) invoked := make([]protocol.Invoker, 0, len(invokers)) - var result protocol.Result - - ivk := invoker.doSelect(loadbalance, invocation, invokers, invoked) + ivk := invoker.doSelect(loadBalance, invocation, invokers, invoked) //DO INVOKE - result = ivk.Invoke(ctx, invocation) + result := ivk.Invoke(ctx, invocation) if result.Error() != nil { invoker.once.Do(func() { invoker.taskList = queue.New(invoker.failbackTasks) @@ -164,7 +160,7 @@ func (invoker *failbackClusterInvoker) Invoke(ctx context.Context, invocation pr return &protocol.RPCResult{} } - timerTask := newRetryTimerTask(loadbalance, invocation, invokers, ivk) + timerTask := newRetryTimerTask(loadBalance, invocation, invokers, ivk) invoker.taskList.Put(timerTask) logger.Errorf("Failback to invoke the method %v in the service %v, wait for retry in background. Ignored exception: %v.\n", @@ -172,7 +168,6 @@ func (invoker *failbackClusterInvoker) Invoke(ctx context.Context, invocation pr // ignore return &protocol.RPCResult{} } - return result } diff --git a/cluster/directory/base_directory.go b/cluster/directory/base_directory.go index 3ede3d8c0ab3691603ac69c10202155e0a331d26..8a7e0c0e8359c69faf0e504adeb1778c38a08e04 100644 --- a/cluster/directory/base_directory.go +++ b/cluster/directory/base_directory.go @@ -80,14 +80,14 @@ func (dir *BaseDirectory) SetRouters(urls []*common.URL) { return } - routers := make([]router.Router, 0, len(urls)) + routers := make([]router.PriorityRouter, 0, len(urls)) for _, url := range urls { routerKey := url.GetParam(constant.ROUTER_KEY, "") if len(routerKey) > 0 { factory := extension.GetRouterFactory(url.Protocol) - r, err := factory.NewRouter(url) + r, err := factory.NewPriorityRouter(url) if err != nil { logger.Errorf("Create router fail. router key: %s, url:%s, error: %+v", routerKey, url.Service(), err) return diff --git a/cluster/loadbalance/consistent_hash_test.go b/cluster/loadbalance/consistent_hash_test.go index a44293172c6e2c96bd098a19306f69260b713689..9f22d39dc46243dddda89151e07dbea39ab933fb 100644 --- a/cluster/loadbalance/consistent_hash_test.go +++ b/cluster/loadbalance/consistent_hash_test.go @@ -18,6 +18,7 @@ package loadbalance import ( + "fmt" "testing" ) @@ -32,6 +33,19 @@ import ( "github.com/apache/dubbo-go/protocol/invocation" ) +const ( + ip = "192.168.1.0" + port8080 = 8080 + port8082 = 8082 + + url8080Short = "dubbo://192.168.1.0:8080" + url8081Short = "dubbo://192.168.1.0:8081" + url20000 = "dubbo://192.168.1.0:20000/org.apache.demo.HelloService?methods.echo.hash.arguments=0,1" + url8080 = "dubbo://192.168.1.0:8080/org.apache.demo.HelloService?methods.echo.hash.arguments=0,1" + url8081 = "dubbo://192.168.1.0:8081/org.apache.demo.HelloService?methods.echo.hash.arguments=0,1" + url8082 = "dubbo://192.168.1.0:8082/org.apache.demo.HelloService?methods.echo.hash.arguments=0,1" +) + func TestConsistentHashSelectorSuite(t *testing.T) { suite.Run(t, new(consistentHashSelectorSuite)) } @@ -43,8 +57,7 @@ type consistentHashSelectorSuite struct { func (s *consistentHashSelectorSuite) SetupTest() { var invokers []protocol.Invoker - url, _ := common.NewURL( - "dubbo://192.168.1.0:20000/org.apache.demo.HelloService?methods.echo.hash.arguments=0,1") + url, _ := common.NewURL(url20000) invokers = append(invokers, protocol.NewBaseInvoker(url)) s.selector = newConsistentHashSelector(invokers, "echo", 999944) } @@ -55,14 +68,14 @@ func (s *consistentHashSelectorSuite) TestToKey() { } func (s *consistentHashSelectorSuite) TestSelectForKey() { - url1, _ := common.NewURL("dubbo://192.168.1.0:8080") - url2, _ := common.NewURL("dubbo://192.168.1.0:8081") + url1, _ := common.NewURL(url8080Short) + url2, _ := common.NewURL(url8081Short) s.selector.virtualInvokers = make(map[uint32]protocol.Invoker) s.selector.virtualInvokers[99874] = protocol.NewBaseInvoker(url1) s.selector.virtualInvokers[9999945] = protocol.NewBaseInvoker(url2) s.selector.keys = []uint32{99874, 9999945} result := s.selector.selectForKey(9999944) - s.Equal(result.GetUrl().String(), "dubbo://192.168.1.0:8081?") + s.Equal(result.GetUrl().String(), url8081Short+"?") } func TestConsistentHashLoadBalanceSuite(t *testing.T) { @@ -83,11 +96,11 @@ type consistentHashLoadBalanceSuite struct { func (s *consistentHashLoadBalanceSuite) SetupTest() { var err error - s.url1, err = common.NewURL("dubbo://192.168.1.0:8080/org.apache.demo.HelloService?methods.echo.hash.arguments=0,1") + s.url1, err = common.NewURL(url8080) s.NoError(err) - s.url2, err = common.NewURL("dubbo://192.168.1.0:8081/org.apache.demo.HelloService?methods.echo.hash.arguments=0,1") + s.url2, err = common.NewURL(url8081) s.NoError(err) - s.url3, err = common.NewURL("dubbo://192.168.1.0:8082/org.apache.demo.HelloService?methods.echo.hash.arguments=0,1") + s.url3, err = common.NewURL(url8082) s.NoError(err) s.invoker1 = protocol.NewBaseInvoker(s.url1) @@ -101,9 +114,9 @@ func (s *consistentHashLoadBalanceSuite) SetupTest() { func (s *consistentHashLoadBalanceSuite) TestSelect() { args := []interface{}{"name", "password", "age"} invoker := s.lb.Select(s.invokers, invocation.NewRPCInvocation("echo", args, nil)) - s.Equal(invoker.GetUrl().Location, "192.168.1.0:8080") + s.Equal(invoker.GetUrl().Location, fmt.Sprintf("%s:%d", ip, port8080)) args = []interface{}{"ok", "abc"} invoker = s.lb.Select(s.invokers, invocation.NewRPCInvocation("echo", args, nil)) - s.Equal(invoker.GetUrl().Location, "192.168.1.0:8082") + s.Equal(invoker.GetUrl().Location, fmt.Sprintf("%s:%d", ip, port8082)) } diff --git a/cluster/loadbalance/random_test.go b/cluster/loadbalance/random_test.go index 88392de52c93579dd4def3da2d60b415b601b21e..b94d7da43d5bd42e6798fca750c8616830a8df8f 100644 --- a/cluster/loadbalance/random_test.go +++ b/cluster/loadbalance/random_test.go @@ -36,18 +36,24 @@ import ( "github.com/apache/dubbo-go/protocol/invocation" ) +const ( + tmpUrl = "dubbo://192.168.1.100:20000/com.ikurento.user.UserProvider" + tmpUrlFormat = "dubbo://192.168.1.%v:20000/com.ikurento.user.UserProvider" + tmpIp = "192.168.1.100" +) + func TestRandomlbSelect(t *testing.T) { randomlb := NewRandomLoadBalance() invokers := []protocol.Invoker{} - url, _ := common.NewURL(fmt.Sprintf("dubbo://192.168.1.%v:20000/com.ikurento.user.UserProvider", 0)) + url, _ := common.NewURL(fmt.Sprintf(tmpUrlFormat, 0)) invokers = append(invokers, protocol.NewBaseInvoker(url)) i := randomlb.Select(invokers, &invocation.RPCInvocation{}) assert.True(t, i.GetUrl().URLEqual(url)) for i := 1; i < 10; i++ { - url, _ := common.NewURL(fmt.Sprintf("dubbo://192.168.1.%v:20000/com.ikurento.user.UserProvider", i)) + url, _ := common.NewURL(fmt.Sprintf(tmpUrlFormat, i)) invokers = append(invokers, protocol.NewBaseInvoker(url)) } randomlb.Select(invokers, &invocation.RPCInvocation{}) @@ -58,13 +64,13 @@ func TestRandomlbSelectWeight(t *testing.T) { invokers := []protocol.Invoker{} for i := 0; i < 10; i++ { - url, _ := common.NewURL(fmt.Sprintf("dubbo://192.168.1.%v:20000/com.ikurento.user.UserProvider", i)) + url, _ := common.NewURL(fmt.Sprintf(tmpUrlFormat, i)) invokers = append(invokers, protocol.NewBaseInvoker(url)) } urlParams := url.Values{} urlParams.Set("methods.test."+constant.WEIGHT_KEY, "10000000000000") - urll, _ := common.NewURL(fmt.Sprintf("dubbo://192.168.1.100:20000/com.ikurento.user.UserProvider"), common.WithParams(urlParams)) + urll, _ := common.NewURL(tmpUrl, common.WithParams(urlParams)) invokers = append(invokers, protocol.NewBaseInvoker(urll)) ivc := invocation.NewRPCInvocationWithOptions(invocation.WithMethodName("test")) @@ -72,7 +78,7 @@ func TestRandomlbSelectWeight(t *testing.T) { var selected float64 for i := 0; i < 10000; i++ { s := randomlb.Select(invokers, ivc) - if s.GetUrl().Ip == "192.168.1.100" { + if s.GetUrl().Ip == tmpIp { selected++ } selectedInvoker = append(selectedInvoker, s) @@ -89,13 +95,13 @@ func TestRandomlbSelectWarmup(t *testing.T) { invokers := []protocol.Invoker{} for i := 0; i < 10; i++ { - url, _ := common.NewURL(fmt.Sprintf("dubbo://192.168.1.%v:20000/com.ikurento.user.UserProvider", i)) + url, _ := common.NewURL(fmt.Sprintf(tmpUrlFormat, i)) invokers = append(invokers, protocol.NewBaseInvoker(url)) } urlParams := url.Values{} urlParams.Set(constant.REMOTE_TIMESTAMP_KEY, strconv.FormatInt(time.Now().Add(time.Minute*(-9)).Unix(), 10)) - urll, _ := common.NewURL(fmt.Sprintf("dubbo://192.168.1.100:20000/com.ikurento.user.UserProvider"), common.WithParams(urlParams)) + urll, _ := common.NewURL(tmpUrl, common.WithParams(urlParams)) invokers = append(invokers, protocol.NewBaseInvoker(urll)) ivc := invocation.NewRPCInvocationWithOptions(invocation.WithMethodName("test")) @@ -103,7 +109,7 @@ func TestRandomlbSelectWarmup(t *testing.T) { var selected float64 for i := 0; i < 10000; i++ { s := randomlb.Select(invokers, ivc) - if s.GetUrl().Ip == "192.168.1.100" { + if s.GetUrl().Ip == tmpIp { selected++ } selectedInvoker = append(selectedInvoker, s) diff --git a/cluster/router/chain/chain.go b/cluster/router/chain/chain.go index d48a837eba2080867f370b0cd90e38a0bdf5e417..97d20ac5fca0688d3f1f48c6ffc12314f5dc3904 100644 --- a/cluster/router/chain/chain.go +++ b/cluster/router/chain/chain.go @@ -40,19 +40,21 @@ type RouterChain struct { // Full list of addresses from registry, classified by method name. invokers []protocol.Invoker // Containing all routers, reconstruct every time 'route://' urls change. - routers []router.Router + routers []router.PriorityRouter // Fixed router instances: ConfigConditionRouter, TagRouter, e.g., the rule for each instance may change but the // instance will never delete or recreate. - builtinRouters []router.Router + builtinRouters []router.PriorityRouter mutex sync.RWMutex + + url common.URL } // Route Loop routers in RouterChain and call Route method to determine the target invokers list. func (c *RouterChain) Route(invoker []protocol.Invoker, url *common.URL, invocation protocol.Invocation) []protocol.Invoker { finalInvokers := invoker l := len(c.routers) - rs := make([]router.Router, l, int(math.Ceil(float64(l)*1.2))) + rs := make([]router.PriorityRouter, l, int(math.Ceil(float64(l)*1.2))) c.mutex.RLock() copy(rs, c.routers) c.mutex.RUnlock() @@ -67,8 +69,8 @@ func (c *RouterChain) Route(invoker []protocol.Invoker, url *common.URL, invocat // New a array add builtinRouters which is not sorted in RouterChain and routers // Sort the array // Replace router array in RouterChain -func (c *RouterChain) AddRouters(routers []router.Router) { - newRouters := make([]router.Router, 0, len(c.builtinRouters)+len(routers)) +func (c *RouterChain) AddRouters(routers []router.PriorityRouter) { + newRouters := make([]router.PriorityRouter, 0, len(c.builtinRouters)+len(routers)) newRouters = append(newRouters, c.builtinRouters...) newRouters = append(newRouters, routers...) sortRouter(newRouters) @@ -77,6 +79,11 @@ func (c *RouterChain) AddRouters(routers []router.Router) { c.routers = newRouters } +// URL Return URL in RouterChain +func (c *RouterChain) URL() common.URL { + return c.url +} + // NewRouterChain Use url to init router chain // Loop routerFactories and call NewRouter method func NewRouterChain(url *common.URL) (*RouterChain, error) { @@ -84,9 +91,9 @@ func NewRouterChain(url *common.URL) (*RouterChain, error) { if len(routerFactories) == 0 { return nil, perrors.Errorf("No routerFactory exits , create one please") } - routers := make([]router.Router, 0, len(routerFactories)) + routers := make([]router.PriorityRouter, 0, len(routerFactories)) for key, routerFactory := range routerFactories { - r, err := routerFactory().NewRouter(url) + r, err := routerFactory().NewPriorityRouter(url) if r == nil || err != nil { logger.Errorf("router chain build router fail! routerFactories key:%s error:%s", key, err.Error()) continue @@ -94,7 +101,7 @@ func NewRouterChain(url *common.URL) (*RouterChain, error) { routers = append(routers, r) } - newRouters := make([]router.Router, len(routers)) + newRouters := make([]router.PriorityRouter, len(routers)) copy(newRouters, routers) sortRouter(newRouters) @@ -103,17 +110,20 @@ func NewRouterChain(url *common.URL) (*RouterChain, error) { builtinRouters: routers, routers: newRouters, } + if url != nil { + chain.url = *url + } return chain, nil } // sortRouter Sort router instance by priority with stable algorithm -func sortRouter(routers []router.Router) { +func sortRouter(routers []router.PriorityRouter) { sort.Stable(byPriority(routers)) } // byPriority Sort by priority -type byPriority []router.Router +type byPriority []router.PriorityRouter func (a byPriority) Len() int { return len(a) } func (a byPriority) Swap(i, j int) { a[i], a[j] = a[j], a[i] } diff --git a/cluster/router/chain/chain_test.go b/cluster/router/chain/chain_test.go index c7a75f3d8608ecb7a95dcf33027e71b61d7f00f5..c1f723525f5307e7732f0ea1ecc27eca7ba09c8d 100644 --- a/cluster/router/chain/chain_test.go +++ b/cluster/router/chain/chain_test.go @@ -20,7 +20,6 @@ package chain import ( "encoding/base64" "fmt" - "strconv" "testing" "time" ) @@ -43,9 +42,22 @@ import ( ) const ( - path = "/dubbo/config/dubbo/test-condition.condition-router" - zkPrefix = "zookeeper://127.0.0.1:" - anyUrl = "condition://0.0.0.0/com.foo.BarService" + localIP = "127.0.0.1" + test1234IP = "1.2.3.4" + test1111IP = "1.1.1.1" + test0000IP = "0.0.0.0" + port20000 = 20000 + + path = "/dubbo/config/dubbo/test-condition.condition-router" + zkFormat = "zookeeper://%s:%d" + consumerFormat = "consumer://%s/com.foo.BarService" + dubboForamt = "dubbo://%s:%d/com.foo.BarService" + anyUrlFormat = "condition://%s/com.foo.BarService" + zk = "zookeeper" + applicationKey = "test-condition" + applicationField = "application" + forceField = "force" + forceValue = "true" ) func TestNewRouterChain(t *testing.T) { @@ -66,14 +78,14 @@ conditions: defer ts.Stop() defer z.Close() - zkUrl, _ := common.NewURL(zkPrefix + strconv.Itoa(ts.Servers[0].Port)) - configuration, err := extension.GetConfigCenterFactory("zookeeper").GetDynamicConfiguration(&zkUrl) + zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, localIP, ts.Servers[0].Port)) + configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(&zkUrl) config.GetEnvInstance().SetDynamicConfiguration(configuration) assert.Nil(t, err) assert.NotNil(t, configuration) - chain, err := NewRouterChain(getRouteUrl("test-condition")) + chain, err := NewRouterChain(getRouteUrl(applicationKey)) assert.Nil(t, err) assert.Equal(t, 1, len(chain.routers)) appRouter := chain.routers[0].(*condition.AppRouter) @@ -116,22 +128,22 @@ conditions: defer ts.Stop() defer z.Close() - zkUrl, _ := common.NewURL(zkPrefix + strconv.Itoa(ts.Servers[0].Port)) - configuration, err := extension.GetConfigCenterFactory("zookeeper").GetDynamicConfiguration(&zkUrl) + zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, localIP, ts.Servers[0].Port)) + configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(&zkUrl) config.GetEnvInstance().SetDynamicConfiguration(configuration) - chain, err := NewRouterChain(getConditionRouteUrl("test-condition")) + chain, err := NewRouterChain(getConditionRouteUrl(applicationKey)) assert.Nil(t, err) assert.Equal(t, 2, len(chain.routers)) - url := getConditionRouteUrl("test-condition") + url := getConditionRouteUrl(applicationKey) assert.NotNil(t, url) factory := extension.GetRouterFactory(url.Protocol) - r, err := factory.NewRouter(url) + r, err := factory.NewPriorityRouter(url) assert.Nil(t, err) assert.NotNil(t, r) - routers := make([]router.Router, 0) + routers := make([]router.PriorityRouter, 0) routers = append(routers, r) chain.AddRouters(routers) assert.Equal(t, 3, len(chain.routers)) @@ -142,22 +154,22 @@ func TestRouterChainRoute(t *testing.T) { defer ts.Stop() defer z.Close() - zkUrl, _ := common.NewURL(zkPrefix + strconv.Itoa(ts.Servers[0].Port)) - configuration, err := extension.GetConfigCenterFactory("zookeeper").GetDynamicConfiguration(&zkUrl) + zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, localIP, ts.Servers[0].Port)) + configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(&zkUrl) config.GetEnvInstance().SetDynamicConfiguration(configuration) - chain, err := NewRouterChain(getConditionRouteUrl("test-condition")) + chain, err := NewRouterChain(getConditionRouteUrl(applicationKey)) assert.Nil(t, err) assert.Equal(t, 1, len(chain.routers)) - url := getConditionRouteUrl("test-condition") + url := getConditionRouteUrl(applicationKey) assert.NotNil(t, url) invokers := []protocol.Invoker{} - dubboURL, _ := common.NewURL(fmt.Sprintf("dubbo://1.2.3.4:20000/com.foo.BarService")) + dubboURL, _ := common.NewURL(fmt.Sprintf(dubboForamt, test1234IP, port20000)) invokers = append(invokers, protocol.NewBaseInvoker(dubboURL)) - targetURL, _ := common.NewURL(fmt.Sprintf("consumer://1.1.1.1/com.foo.BarService")) + targetURL, _ := common.NewURL(fmt.Sprintf(consumerFormat, test1111IP)) inv := &invocation.RPCInvocation{} finalInvokers := chain.Route(invokers, &targetURL, inv) @@ -182,46 +194,46 @@ conditions: defer ts.Stop() defer z.Close() - zkUrl, _ := common.NewURL(zkPrefix + strconv.Itoa(ts.Servers[0].Port)) - configuration, err := extension.GetConfigCenterFactory("zookeeper").GetDynamicConfiguration(&zkUrl) + zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, localIP, ts.Servers[0].Port)) + configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(&zkUrl) config.GetEnvInstance().SetDynamicConfiguration(configuration) - chain, err := NewRouterChain(getConditionRouteUrl("test-condition")) + chain, err := NewRouterChain(getConditionRouteUrl(applicationKey)) assert.Nil(t, err) assert.Equal(t, 2, len(chain.routers)) invokers := []protocol.Invoker{} - dubboURL, _ := common.NewURL(fmt.Sprintf("dubbo://1.2.3.4:20000/com.foo.BarService")) + dubboURL, _ := common.NewURL(fmt.Sprintf(dubboForamt, test1234IP, port20000)) invokers = append(invokers, protocol.NewBaseInvoker(dubboURL)) - targetURL, _ := common.NewURL(fmt.Sprintf("consumer://1.1.1.1/com.foo.BarService")) + targetURL, _ := common.NewURL(fmt.Sprintf(consumerFormat, test1111IP)) inv := &invocation.RPCInvocation{} finalInvokers := chain.Route(invokers, &targetURL, inv) assert.Equal(t, 0, len(finalInvokers)) } -func TestRouterChain_Route_NoRoute(t *testing.T) { +func TestRouterChainRouteNoRoute(t *testing.T) { ts, z, _, err := zookeeper.NewMockZookeeperClient("test", 15*time.Second) defer ts.Stop() defer z.Close() - zkUrl, _ := common.NewURL(zkPrefix + strconv.Itoa(ts.Servers[0].Port)) - configuration, err := extension.GetConfigCenterFactory("zookeeper").GetDynamicConfiguration(&zkUrl) + zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, localIP, ts.Servers[0].Port)) + configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(&zkUrl) config.GetEnvInstance().SetDynamicConfiguration(configuration) - chain, err := NewRouterChain(getConditionNoRouteUrl("test-condition")) + chain, err := NewRouterChain(getConditionNoRouteUrl(applicationKey)) assert.Nil(t, err) assert.Equal(t, 1, len(chain.routers)) - url := getConditionRouteUrl("test-condition") + url := getConditionRouteUrl(applicationKey) assert.NotNil(t, url) invokers := []protocol.Invoker{} - dubboURL, _ := common.NewURL(fmt.Sprintf("dubbo://1.2.3.4:20000/com.foo.BarService")) + dubboURL, _ := common.NewURL(fmt.Sprintf(dubboForamt, test1234IP, port20000)) invokers = append(invokers, protocol.NewBaseInvoker(dubboURL)) - targetURL, _ := common.NewURL(fmt.Sprintf("consumer://1.1.1.1/com.foo.BarService")) + targetURL, _ := common.NewURL(fmt.Sprintf(consumerFormat, test1111IP)) inv := &invocation.RPCInvocation{} finalInvokers := chain.Route(invokers, &targetURL, inv) @@ -229,26 +241,26 @@ func TestRouterChain_Route_NoRoute(t *testing.T) { } func getConditionNoRouteUrl(applicationKey string) *common.URL { - url, _ := common.NewURL(anyUrl) - url.AddParam("application", applicationKey) - url.AddParam("force", "true") + url, _ := common.NewURL(fmt.Sprintf(anyUrlFormat, test0000IP)) + url.AddParam(applicationField, applicationKey) + url.AddParam(forceField, forceValue) rule := base64.URLEncoding.EncodeToString([]byte("host = 1.1.1.1 => host != 1.2.3.4")) url.AddParam(constant.RULE_KEY, rule) return &url } func getConditionRouteUrl(applicationKey string) *common.URL { - url, _ := common.NewURL(anyUrl) - url.AddParam("application", applicationKey) - url.AddParam("force", "true") + url, _ := common.NewURL(fmt.Sprintf(anyUrlFormat, test0000IP)) + url.AddParam(applicationField, applicationKey) + url.AddParam(forceField, forceValue) rule := base64.URLEncoding.EncodeToString([]byte("host = 1.1.1.1 => host = 1.2.3.4")) url.AddParam(constant.RULE_KEY, rule) return &url } func getRouteUrl(applicationKey string) *common.URL { - url, _ := common.NewURL(anyUrl) - url.AddParam("application", applicationKey) - url.AddParam("force", "true") + url, _ := common.NewURL(fmt.Sprintf(anyUrlFormat, test0000IP)) + url.AddParam(applicationField, applicationKey) + url.AddParam(forceField, forceValue) return &url } diff --git a/cluster/router/chan.go b/cluster/router/chan.go new file mode 100644 index 0000000000000000000000000000000000000000..6904e1734a7cbdaa00afa1b30797d19ca502453c --- /dev/null +++ b/cluster/router/chan.go @@ -0,0 +1,25 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package router + +// Chain +type Chain interface { + router + // AddRouters Add routers + AddRouters([]PriorityRouter) +} diff --git a/cluster/router/condition/app_router_test.go b/cluster/router/condition/app_router_test.go index f37a483e8468bc57d3ce1e73172ccf9a05bc29f0..8b38f2dd6136b4d31f46e7214c0ad1359537b198 100644 --- a/cluster/router/condition/app_router_test.go +++ b/cluster/router/condition/app_router_test.go @@ -18,7 +18,7 @@ package condition import ( - "strconv" + "fmt" "testing" "time" ) @@ -31,6 +31,7 @@ import ( import ( "github.com/apache/dubbo-go/common" "github.com/apache/dubbo-go/common/config" + "github.com/apache/dubbo-go/common/constant" "github.com/apache/dubbo-go/common/extension" "github.com/apache/dubbo-go/config_center" "github.com/apache/dubbo-go/remoting" @@ -38,7 +39,15 @@ import ( ) const ( - path = "/dubbo/config/dubbo/test-condition.condition-router" + routerPath = "/dubbo/config/dubbo/test-condition.condition-router" + routerLocalIP = "127.0.0.1" + routerZk = "zookeeper" + routerKey = "test-condition" +) + +var ( + zkFormat = "zookeeper://%s:%d" + conditionFormat = "condition://%s/com.foo.BarService" ) func TestNewAppRouter(t *testing.T) { @@ -51,22 +60,22 @@ conditions: ` ts, z, _, err := zookeeper.NewMockZookeeperClient("test", 15*time.Second) assert.NoError(t, err) - err = z.Create(path) + err = z.Create(routerPath) assert.NoError(t, err) - _, err = z.Conn.Set(path, []byte(testYML), 0) + _, err = z.Conn.Set(routerPath, []byte(testYML), 0) assert.NoError(t, err) defer ts.Stop() defer z.Close() - zkUrl, _ := common.NewURL("zookeeper://127.0.0.1:" + strconv.Itoa(ts.Servers[0].Port)) - configuration, err := extension.GetConfigCenterFactory("zookeeper").GetDynamicConfiguration(&zkUrl) + zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, routerLocalIP, ts.Servers[0].Port)) + configuration, err := extension.GetConfigCenterFactory(routerZk).GetDynamicConfiguration(&zkUrl) config.GetEnvInstance().SetDynamicConfiguration(configuration) assert.Nil(t, err) assert.NotNil(t, configuration) - appRouteURL := getAppRouteURL("test-condition") + appRouteURL := getAppRouteURL(routerKey) appRouter, err := NewAppRouter(appRouteURL) assert.Nil(t, err) assert.NotNil(t, appRouter) @@ -97,22 +106,22 @@ conditions: ` ts, z, _, err := zookeeper.NewMockZookeeperClient("test", 15*time.Second) assert.NoError(t, err) - err = z.Create(path) + err = z.Create(routerPath) assert.NoError(t, err) - _, err = z.Conn.Set(path, []byte(testYML), 0) + _, err = z.Conn.Set(routerPath, []byte(testYML), 0) assert.NoError(t, err) defer ts.Stop() defer z.Close() - zkUrl, _ := common.NewURL("zookeeper://127.0.0.1:" + strconv.Itoa(ts.Servers[0].Port)) - configuration, err := extension.GetConfigCenterFactory("zookeeper").GetDynamicConfiguration(&zkUrl) + zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, routerLocalIP, ts.Servers[0].Port)) + configuration, err := extension.GetConfigCenterFactory(routerZk).GetDynamicConfiguration(&zkUrl) config.GetEnvInstance().SetDynamicConfiguration(configuration) assert.Nil(t, err) assert.NotNil(t, configuration) - appRouteURL := getAppRouteURL("test-condition") + appRouteURL := getAppRouteURL(routerKey) appRouter, err := NewAppRouter(appRouteURL) assert.Nil(t, err) assert.NotNil(t, appRouter) @@ -134,22 +143,22 @@ conditions: ` ts, z, _, err := zookeeper.NewMockZookeeperClient("test", 15*time.Second) assert.NoError(t, err) - err = z.Create(path) + err = z.Create(routerPath) assert.NoError(t, err) - _, err = z.Conn.Set(path, []byte(testYML), 0) + _, err = z.Conn.Set(routerPath, []byte(testYML), 0) assert.NoError(t, err) defer ts.Stop() defer z.Close() - zkUrl, _ := common.NewURL("zookeeper://127.0.0.1:" + strconv.Itoa(ts.Servers[0].Port)) - configuration, err := extension.GetConfigCenterFactory("zookeeper").GetDynamicConfiguration(&zkUrl) + zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, routerLocalIP, ts.Servers[0].Port)) + configuration, err := extension.GetConfigCenterFactory(routerZk).GetDynamicConfiguration(&zkUrl) config.GetEnvInstance().SetDynamicConfiguration(configuration) assert.Nil(t, err) assert.NotNil(t, configuration) - appRouteURL := getAppRouteURL("test-condition") + appRouteURL := getAppRouteURL(routerKey) appRouter, err := NewAppRouter(appRouteURL) assert.Nil(t, err) assert.NotNil(t, appRouter) @@ -175,7 +184,7 @@ conditions: } func getAppRouteURL(applicationKey string) *common.URL { - url, _ := common.NewURL("condition://0.0.0.0/com.foo.BarService") + url, _ := common.NewURL(fmt.Sprintf(conditionFormat, constant.ANYHOST_VALUE)) url.AddParam("application", applicationKey) url.AddParam("force", "true") return &url diff --git a/cluster/router/condition/factory.go b/cluster/router/condition/factory.go index 66512a138706e9b9ab565f7537a15c37a75deefd..f8d3e130102d4311f8b1ddb1055aece8a0633296 100644 --- a/cluster/router/condition/factory.go +++ b/cluster/router/condition/factory.go @@ -32,28 +32,28 @@ func init() { // ConditionRouterFactory Condition router factory type ConditionRouterFactory struct{} -func newConditionRouterFactory() router.RouterFactory { +func newConditionRouterFactory() router.PriorityRouterFactory { return &ConditionRouterFactory{} } -// NewRouter Create ConditionRouterFactory by URL -func (c *ConditionRouterFactory) NewRouter(url *common.URL) (router.Router, error) { +// NewPriorityRouter creates ConditionRouterFactory by URL +func (c *ConditionRouterFactory) NewPriorityRouter(url *common.URL) (router.PriorityRouter, error) { return NewConditionRouter(url) } // NewRouter Create FileRouterFactory by Content -func (c *ConditionRouterFactory) NewFileRouter(content []byte) (router.Router, error) { +func (c *ConditionRouterFactory) NewFileRouter(content []byte) (router.PriorityRouter, error) { return NewFileConditionRouter(content) } // AppRouterFactory Application router factory type AppRouterFactory struct{} -func newAppRouterFactory() router.RouterFactory { +func newAppRouterFactory() router.PriorityRouterFactory { return &AppRouterFactory{} } -// NewRouter Create AppRouterFactory by URL -func (c *AppRouterFactory) NewRouter(url *common.URL) (router.Router, error) { +// NewPriorityRouter creates AppRouterFactory by URL +func (c *AppRouterFactory) NewPriorityRouter(url *common.URL) (router.PriorityRouter, error) { return NewAppRouter(url) } diff --git a/cluster/router/condition/factory_test.go b/cluster/router/condition/factory_test.go index a826cafb85ee1a30ac568db34e10dd2c9c9e87d0..0f61b39fc71af3aaeffc731974a0fa997503693e 100644 --- a/cluster/router/condition/factory_test.go +++ b/cluster/router/condition/factory_test.go @@ -33,12 +33,21 @@ import ( import ( "github.com/apache/dubbo-go/common" + "github.com/apache/dubbo-go/common/constant" "github.com/apache/dubbo-go/common/logger" "github.com/apache/dubbo-go/protocol" "github.com/apache/dubbo-go/protocol/invocation" ) -const anyUrl = "condition://0.0.0.0/com.foo.BarService" +const ( + factory1111Ip = "1.1.1.1" + factoryUrlFormat = "condition://%s/com.foo.BarService" + factoryDubboFormat = "dubbo://%s:20880/com.foo.BarService" + factoryConsumerMethodFormat = "consumer://%s/com.foo.BarService?methods=getFoo" + factory333URL = "dubbo://10.20.3.3:20880/com.foo.BarService" + factoryConsumerFormat = "consumer://%s/com.foo.BarService" + factoryHostIp1234Format = "host = %s => host = 1.2.3.4" +) type MockInvoker struct { url common.URL @@ -61,21 +70,21 @@ func (bi *MockInvoker) GetUrl() common.URL { } func getRouteUrl(rule string) *common.URL { - url, _ := common.NewURL(anyUrl) + url, _ := common.NewURL(fmt.Sprintf(factoryUrlFormat, constant.ANYHOST_VALUE)) url.AddParam("rule", rule) url.AddParam("force", "true") return &url } func getRouteUrlWithForce(rule, force string) *common.URL { - url, _ := common.NewURL(anyUrl) + url, _ := common.NewURL(fmt.Sprintf(factoryUrlFormat, constant.ANYHOST_VALUE)) url.AddParam("rule", rule) url.AddParam("force", force) return &url } func getRouteUrlWithNoForce(rule string) *common.URL { - url, _ := common.NewURL(anyUrl) + url, _ := common.NewURL(fmt.Sprintf(factoryUrlFormat, constant.ANYHOST_VALUE)) url.AddParam("rule", rule) return &url } @@ -118,45 +127,45 @@ func (bi *MockInvoker) Destroy() { bi.available = false } -func TestRouteMatchWhen(t *testing.T) { +func TestRoute_matchWhen(t *testing.T) { inv := &invocation.RPCInvocation{} rule := base64.URLEncoding.EncodeToString([]byte("=> host = 1.2.3.4")) - router, _ := newConditionRouterFactory().NewRouter(getRouteUrl(rule)) - cUrl, _ := common.NewURL("consumer://1.1.1.1/com.foo.BarService") + router, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule)) + cUrl, _ := common.NewURL(fmt.Sprintf(factoryDubboFormat, factory1111Ip)) matchWhen := router.(*ConditionRouter).MatchWhen(&cUrl, inv) assert.Equal(t, true, matchWhen) rule1 := base64.URLEncoding.EncodeToString([]byte("host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4")) - router1, _ := newConditionRouterFactory().NewRouter(getRouteUrl(rule1)) + router1, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule1)) matchWhen1 := router1.(*ConditionRouter).MatchWhen(&cUrl, inv) assert.Equal(t, true, matchWhen1) rule2 := base64.URLEncoding.EncodeToString([]byte("host = 2.2.2.2,1.1.1.1,3.3.3.3 & host !=1.1.1.1 => host = 1.2.3.4")) - router2, _ := newConditionRouterFactory().NewRouter(getRouteUrl(rule2)) + router2, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule2)) matchWhen2 := router2.(*ConditionRouter).MatchWhen(&cUrl, inv) assert.Equal(t, false, matchWhen2) rule3 := base64.URLEncoding.EncodeToString([]byte("host !=4.4.4.4 & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4")) - router3, _ := newConditionRouterFactory().NewRouter(getRouteUrl(rule3)) + router3, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule3)) matchWhen3 := router3.(*ConditionRouter).MatchWhen(&cUrl, inv) assert.Equal(t, true, matchWhen3) rule4 := base64.URLEncoding.EncodeToString([]byte("host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4")) - router4, _ := newConditionRouterFactory().NewRouter(getRouteUrl(rule4)) + router4, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule4)) matchWhen4 := router4.(*ConditionRouter).MatchWhen(&cUrl, inv) assert.Equal(t, true, matchWhen4) rule5 := base64.URLEncoding.EncodeToString([]byte("host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.1 => host = 1.2.3.4")) - router5, _ := newConditionRouterFactory().NewRouter(getRouteUrl(rule5)) + router5, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule5)) matchWhen5 := router5.(*ConditionRouter).MatchWhen(&cUrl, inv) assert.Equal(t, false, matchWhen5) rule6 := base64.URLEncoding.EncodeToString([]byte("host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.2 => host = 1.2.3.4")) - router6, _ := newConditionRouterFactory().NewRouter(getRouteUrl(rule6)) + router6, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule6)) matchWhen6 := router6.(*ConditionRouter).MatchWhen(&cUrl, inv) assert.Equal(t, true, matchWhen6) } -func TestRouteMatchFilter(t *testing.T) { +func TestRoute_matchFilter(t *testing.T) { localIP, _ := gxnet.GetLocalIP() t.Logf("The local ip is %s", localIP) url1, _ := common.NewURL("dubbo://10.20.3.3:20880/com.foo.BarService?default.serialization=fastjson") - url2, _ := common.NewURL(fmt.Sprintf("dubbo://%s:20880/com.foo.BarService", localIP)) - url3, _ := common.NewURL(fmt.Sprintf("dubbo://%s:20880/com.foo.BarService", localIP)) + url2, _ := common.NewURL(fmt.Sprintf(factoryDubboFormat, localIP)) + url3, _ := common.NewURL(fmt.Sprintf(factoryDubboFormat, localIP)) invokers := []protocol.Invoker{NewMockInvoker(url1, 1), NewMockInvoker(url2, 2), NewMockInvoker(url3, 3)} rule1 := base64.URLEncoding.EncodeToString([]byte("host = " + localIP + " => " + " host = 10.20.3.3")) rule2 := base64.URLEncoding.EncodeToString([]byte("host = " + localIP + " => " + " host = 10.20.3.* & host != 10.20.3.3")) @@ -164,13 +173,13 @@ func TestRouteMatchFilter(t *testing.T) { rule4 := base64.URLEncoding.EncodeToString([]byte("host = " + localIP + " => " + " host = 10.20.3.2,10.20.3.3,10.20.3.4")) rule5 := base64.URLEncoding.EncodeToString([]byte("host = " + localIP + " => " + " host != 10.20.3.3")) rule6 := base64.URLEncoding.EncodeToString([]byte("host = " + localIP + " => " + " serialization = fastjson")) - router1, _ := newConditionRouterFactory().NewRouter(getRouteUrl(rule1)) - router2, _ := newConditionRouterFactory().NewRouter(getRouteUrl(rule2)) - router3, _ := newConditionRouterFactory().NewRouter(getRouteUrl(rule3)) - router4, _ := newConditionRouterFactory().NewRouter(getRouteUrl(rule4)) - router5, _ := newConditionRouterFactory().NewRouter(getRouteUrl(rule5)) - router6, _ := newConditionRouterFactory().NewRouter(getRouteUrl(rule6)) - cUrl, _ := common.NewURL("consumer://" + localIP + "/com.foo.BarService") + router1, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule1)) + router2, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule2)) + router3, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule3)) + router4, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule4)) + router5, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule5)) + router6, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule6)) + cUrl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP)) fileredInvokers1 := router1.Route(invokers, &cUrl, &invocation.RPCInvocation{}) fileredInvokers2 := router2.Route(invokers, &cUrl, &invocation.RPCInvocation{}) fileredInvokers3 := router3.Route(invokers, &cUrl, &invocation.RPCInvocation{}) @@ -186,54 +195,54 @@ func TestRouteMatchFilter(t *testing.T) { } -func TestRouteMethodRoute(t *testing.T) { +func TestRoute_methodRoute(t *testing.T) { inv := invocation.NewRPCInvocationWithOptions(invocation.WithMethodName("getFoo"), invocation.WithParameterTypes([]reflect.Type{}), invocation.WithArguments([]interface{}{})) rule := base64.URLEncoding.EncodeToString([]byte("host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4")) - router, _ := newConditionRouterFactory().NewRouter(getRouteUrl(rule)) + router, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule)) url, _ := common.NewURL("consumer://1.1.1.1/com.foo.BarService?methods=setFoo,getFoo,findFoo") matchWhen := router.(*ConditionRouter).MatchWhen(&url, inv) assert.Equal(t, true, matchWhen) - url1, _ := common.NewURL("consumer://1.1.1.1/com.foo.BarService?methods=getFoo") + url1, _ := common.NewURL(fmt.Sprintf(factoryConsumerMethodFormat, factory1111Ip)) matchWhen = router.(*ConditionRouter).MatchWhen(&url1, inv) assert.Equal(t, true, matchWhen) - url2, _ := common.NewURL("consumer://1.1.1.1/com.foo.BarService?methods=getFoo") + url2, _ := common.NewURL(fmt.Sprintf(factoryConsumerMethodFormat, factory1111Ip)) rule2 := base64.URLEncoding.EncodeToString([]byte("methods=getFoo & host!=1.1.1.1 => host = 1.2.3.4")) - router2, _ := newConditionRouterFactory().NewRouter(getRouteUrl(rule2)) + router2, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule2)) matchWhen = router2.(*ConditionRouter).MatchWhen(&url2, inv) assert.Equal(t, false, matchWhen) - url3, _ := common.NewURL("consumer://1.1.1.1/com.foo.BarService?methods=getFoo") + url3, _ := common.NewURL(fmt.Sprintf(factoryConsumerMethodFormat, factory1111Ip)) rule3 := base64.URLEncoding.EncodeToString([]byte("methods=getFoo & host=1.1.1.1 => host = 1.2.3.4")) - router3, _ := newConditionRouterFactory().NewRouter(getRouteUrl(rule3)) + router3, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule3)) matchWhen = router3.(*ConditionRouter).MatchWhen(&url3, inv) assert.Equal(t, true, matchWhen) } -func TestRouteReturnFalse(t *testing.T) { +func TestRoute_ReturnFalse(t *testing.T) { url, _ := common.NewURL("") localIP, _ := gxnet.GetLocalIP() invokers := []protocol.Invoker{NewMockInvoker(url, 1), NewMockInvoker(url, 2), NewMockInvoker(url, 3)} inv := &invocation.RPCInvocation{} rule := base64.URLEncoding.EncodeToString([]byte("host = " + localIP + " => false")) - curl, _ := common.NewURL("consumer://" + localIP + "/com.foo.BarService") - router, _ := newConditionRouterFactory().NewRouter(getRouteUrl(rule)) + curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP)) + router, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule)) fileredInvokers := router.(*ConditionRouter).Route(invokers, &curl, inv) assert.Equal(t, 0, len(fileredInvokers)) } -func TestRouteReturnEmpty(t *testing.T) { +func TestRoute_ReturnEmpty(t *testing.T) { localIP, _ := gxnet.GetLocalIP() url, _ := common.NewURL("") invokers := []protocol.Invoker{NewMockInvoker(url, 1), NewMockInvoker(url, 2), NewMockInvoker(url, 3)} inv := &invocation.RPCInvocation{} rule := base64.URLEncoding.EncodeToString([]byte("host = " + localIP + " => ")) - curl, _ := common.NewURL("consumer://" + localIP + "/com.foo.BarService") - router, _ := newConditionRouterFactory().NewRouter(getRouteUrl(rule)) + curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP)) + router, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule)) fileredInvokers := router.(*ConditionRouter).Route(invokers, &curl, inv) assert.Equal(t, 0, len(fileredInvokers)) } -func TestRouteReturnAll(t *testing.T) { +func TestRoute_ReturnAll(t *testing.T) { localIP, _ := gxnet.GetLocalIP() urlString := "dubbo://" + localIP + "/com.foo.BarService" dubboURL, _ := common.NewURL(urlString) @@ -243,118 +252,118 @@ func TestRouteReturnAll(t *testing.T) { invokers := []protocol.Invoker{mockInvoker1, mockInvoker2, mockInvoker3} inv := &invocation.RPCInvocation{} rule := base64.URLEncoding.EncodeToString([]byte("host = " + localIP + " => " + " host = " + localIP)) - curl, _ := common.NewURL("consumer://" + localIP + "/com.foo.BarService") - router, _ := newConditionRouterFactory().NewRouter(getRouteUrl(rule)) + curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP)) + router, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule)) fileredInvokers := router.(*ConditionRouter).Route(invokers, &curl, inv) assert.Equal(t, invokers, fileredInvokers) } -func TestRouteHostFilter(t *testing.T) { +func TestRoute_HostFilter(t *testing.T) { localIP, _ := gxnet.GetLocalIP() - url1, _ := common.NewURL("dubbo://10.20.3.3:20880/com.foo.BarService") - url2, _ := common.NewURL(fmt.Sprintf("dubbo://%s:20880/com.foo.BarService", localIP)) - url3, _ := common.NewURL(fmt.Sprintf("dubbo://%s:20880/com.foo.BarService", localIP)) + url1, _ := common.NewURL(factory333URL) + url2, _ := common.NewURL(fmt.Sprintf(factoryDubboFormat, localIP)) + url3, _ := common.NewURL(fmt.Sprintf(factoryDubboFormat, localIP)) invoker1 := NewMockInvoker(url1, 1) invoker2 := NewMockInvoker(url2, 2) invoker3 := NewMockInvoker(url3, 3) invokers := []protocol.Invoker{invoker1, invoker2, invoker3} inv := &invocation.RPCInvocation{} rule := base64.URLEncoding.EncodeToString([]byte("host = " + localIP + " => " + " host = " + localIP)) - curl, _ := common.NewURL("consumer://" + localIP + "/com.foo.BarService") - router, _ := newConditionRouterFactory().NewRouter(getRouteUrl(rule)) + curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP)) + router, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule)) fileredInvokers := router.(*ConditionRouter).Route(invokers, &curl, inv) assert.Equal(t, 2, len(fileredInvokers)) assert.Equal(t, invoker2, fileredInvokers[0]) assert.Equal(t, invoker3, fileredInvokers[1]) } -func TestRouteEmptyHostFilter(t *testing.T) { +func TestRoute_Empty_HostFilter(t *testing.T) { localIP, _ := gxnet.GetLocalIP() - url1, _ := common.NewURL("dubbo://10.20.3.3:20880/com.foo.BarService") - url2, _ := common.NewURL(fmt.Sprintf("dubbo://%s:20880/com.foo.BarService", localIP)) - url3, _ := common.NewURL(fmt.Sprintf("dubbo://%s:20880/com.foo.BarService", localIP)) + url1, _ := common.NewURL(factory333URL) + url2, _ := common.NewURL(fmt.Sprintf(factoryDubboFormat, localIP)) + url3, _ := common.NewURL(fmt.Sprintf(factoryDubboFormat, localIP)) invoker1 := NewMockInvoker(url1, 1) invoker2 := NewMockInvoker(url2, 2) invoker3 := NewMockInvoker(url3, 3) invokers := []protocol.Invoker{invoker1, invoker2, invoker3} inv := &invocation.RPCInvocation{} rule := base64.URLEncoding.EncodeToString([]byte(" => " + " host = " + localIP)) - curl, _ := common.NewURL("consumer://" + localIP + "/com.foo.BarService") - router, _ := newConditionRouterFactory().NewRouter(getRouteUrl(rule)) + curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP)) + router, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule)) fileredInvokers := router.(*ConditionRouter).Route(invokers, &curl, inv) assert.Equal(t, 2, len(fileredInvokers)) assert.Equal(t, invoker2, fileredInvokers[0]) assert.Equal(t, invoker3, fileredInvokers[1]) } -func TestRouteFalseHostFilter(t *testing.T) { +func TestRoute_False_HostFilter(t *testing.T) { localIP, _ := gxnet.GetLocalIP() - url1, _ := common.NewURL("dubbo://10.20.3.3:20880/com.foo.BarService") - url2, _ := common.NewURL(fmt.Sprintf("dubbo://%s:20880/com.foo.BarService", localIP)) - url3, _ := common.NewURL(fmt.Sprintf("dubbo://%s:20880/com.foo.BarService", localIP)) + url1, _ := common.NewURL(factory333URL) + url2, _ := common.NewURL(fmt.Sprintf(factoryDubboFormat, localIP)) + url3, _ := common.NewURL(fmt.Sprintf(factoryDubboFormat, localIP)) invoker1 := NewMockInvoker(url1, 1) invoker2 := NewMockInvoker(url2, 2) invoker3 := NewMockInvoker(url3, 3) invokers := []protocol.Invoker{invoker1, invoker2, invoker3} inv := &invocation.RPCInvocation{} rule := base64.URLEncoding.EncodeToString([]byte("true => " + " host = " + localIP)) - curl, _ := common.NewURL("consumer://" + localIP + "/com.foo.BarService") - router, _ := newConditionRouterFactory().NewRouter(getRouteUrl(rule)) + curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP)) + router, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule)) fileredInvokers := router.(*ConditionRouter).Route(invokers, &curl, inv) assert.Equal(t, 2, len(fileredInvokers)) assert.Equal(t, invoker2, fileredInvokers[0]) assert.Equal(t, invoker3, fileredInvokers[1]) } -func TestRoutePlaceholder(t *testing.T) { +func TestRoute_Placeholder(t *testing.T) { localIP, _ := gxnet.GetLocalIP() - url1, _ := common.NewURL("dubbo://10.20.3.3:20880/com.foo.BarService") - url2, _ := common.NewURL(fmt.Sprintf("dubbo://%s:20880/com.foo.BarService", localIP)) - url3, _ := common.NewURL(fmt.Sprintf("dubbo://%s:20880/com.foo.BarService", localIP)) + url1, _ := common.NewURL(factory333URL) + url2, _ := common.NewURL(fmt.Sprintf(factoryDubboFormat, localIP)) + url3, _ := common.NewURL(fmt.Sprintf(factoryDubboFormat, localIP)) invoker1 := NewMockInvoker(url1, 1) invoker2 := NewMockInvoker(url2, 2) invoker3 := NewMockInvoker(url3, 3) invokers := []protocol.Invoker{invoker1, invoker2, invoker3} inv := &invocation.RPCInvocation{} rule := base64.URLEncoding.EncodeToString([]byte("host = " + localIP + " => " + " host = $host")) - curl, _ := common.NewURL("consumer://" + localIP + "/com.foo.BarService") - router, _ := newConditionRouterFactory().NewRouter(getRouteUrl(rule)) + curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP)) + router, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule)) fileredInvokers := router.(*ConditionRouter).Route(invokers, &curl, inv) assert.Equal(t, 2, len(fileredInvokers)) assert.Equal(t, invoker2, fileredInvokers[0]) assert.Equal(t, invoker3, fileredInvokers[1]) } -func TestRouteNoForce(t *testing.T) { +func TestRoute_NoForce(t *testing.T) { localIP, _ := gxnet.GetLocalIP() - url1, _ := common.NewURL("dubbo://10.20.3.3:20880/com.foo.BarService") - url2, _ := common.NewURL(fmt.Sprintf("dubbo://%s:20880/com.foo.BarService", localIP)) - url3, _ := common.NewURL(fmt.Sprintf("dubbo://%s:20880/com.foo.BarService", localIP)) + url1, _ := common.NewURL(factory333URL) + url2, _ := common.NewURL(fmt.Sprintf(factoryDubboFormat, localIP)) + url3, _ := common.NewURL(fmt.Sprintf(factoryDubboFormat, localIP)) invoker1 := NewMockInvoker(url1, 1) invoker2 := NewMockInvoker(url2, 2) invoker3 := NewMockInvoker(url3, 3) invokers := []protocol.Invoker{invoker1, invoker2, invoker3} inv := &invocation.RPCInvocation{} - rule := base64.URLEncoding.EncodeToString([]byte("host = " + localIP + " => " + " host = 1.2.3.4")) - curl, _ := common.NewURL("consumer://" + localIP + "/com.foo.BarService") - router, _ := newConditionRouterFactory().NewRouter(getRouteUrlWithNoForce(rule)) + rule := base64.URLEncoding.EncodeToString([]byte(fmt.Sprintf(factoryHostIp1234Format, localIP))) + curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP)) + router, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrlWithNoForce(rule)) fileredInvokers := router.(*ConditionRouter).Route(invokers, &curl, inv) assert.Equal(t, invokers, fileredInvokers) } -func TestRouteForce(t *testing.T) { +func TestRoute_Force(t *testing.T) { localIP, _ := gxnet.GetLocalIP() - url1, _ := common.NewURL("dubbo://10.20.3.3:20880/com.foo.BarService") - url2, _ := common.NewURL(fmt.Sprintf("dubbo://%s:20880/com.foo.BarService", localIP)) - url3, _ := common.NewURL(fmt.Sprintf("dubbo://%s:20880/com.foo.BarService", localIP)) + url1, _ := common.NewURL(factory333URL) + url2, _ := common.NewURL(fmt.Sprintf(factoryDubboFormat, localIP)) + url3, _ := common.NewURL(fmt.Sprintf(factoryDubboFormat, localIP)) invoker1 := NewMockInvoker(url1, 1) invoker2 := NewMockInvoker(url2, 2) invoker3 := NewMockInvoker(url3, 3) invokers := []protocol.Invoker{invoker1, invoker2, invoker3} inv := &invocation.RPCInvocation{} - rule := base64.URLEncoding.EncodeToString([]byte("host = " + localIP + " => " + " host = 1.2.3.4")) - curl, _ := common.NewURL("consumer://" + localIP + "/com.foo.BarService") - router, _ := newConditionRouterFactory().NewRouter(getRouteUrlWithForce(rule, "true")) + rule := base64.URLEncoding.EncodeToString([]byte(fmt.Sprintf(factoryHostIp1234Format, localIP))) + curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP)) + router, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrlWithForce(rule, "true")) fileredInvokers := router.(*ConditionRouter).Route(invokers, &curl, inv) assert.Equal(t, 0, len(fileredInvokers)) } diff --git a/cluster/router/condition/file.go b/cluster/router/condition/file.go index b2c876690043d18a1a9e746fee13f06c77a0de03..eabdf1c263446140b359b3e791238b020cecb50c 100644 --- a/cluster/router/condition/file.go +++ b/cluster/router/condition/file.go @@ -77,10 +77,7 @@ func (f *FileConditionRouter) URL() common.URL { } func parseCondition(conditions []string) string { - var ( - when string - then string - ) + var when, then string for _, condition := range conditions { condition = strings.Trim(condition, " ") if strings.Contains(condition, "=>") { @@ -101,10 +98,7 @@ func parseCondition(conditions []string) string { then = provider } } - } - } - return strings.Join([]string{when, then}, " => ") } diff --git a/cluster/router/condition/router.go b/cluster/router/condition/router.go index 0267a3c7a462acb43f84ccb4701247147699804a..40a251573f5e73d40032972313565d98b288b1b1 100644 --- a/cluster/router/condition/router.go +++ b/cluster/router/condition/router.go @@ -181,9 +181,7 @@ func parseRule(rule string) (map[string]MatchPair, error) { return condition, nil } - var ( - pair MatchPair - ) + var pair MatchPair values := gxset.NewSet() matches := routerPatternReg.FindAllSubmatch([]byte(rule), -1) for _, groups := range matches { diff --git a/cluster/router/healthcheck/default_health_check_test.go b/cluster/router/healthcheck/default_health_check_test.go index 8a95d9a7e8dffdc3f30f94c76274a729837fc133..5d35ae8e486e3f7b29b2a68a3864ef806a1053c7 100644 --- a/cluster/router/healthcheck/default_health_check_test.go +++ b/cluster/router/healthcheck/default_health_check_test.go @@ -18,6 +18,7 @@ package healthcheck import ( + "fmt" "math" "testing" ) @@ -32,10 +33,16 @@ import ( "github.com/apache/dubbo-go/protocol" ) -func TestDefaultHealthChecker_IsHealthy(t *testing.T) { +const ( + healthCheckDubbo1010IP = "192.168.10.10" + healthCheckDubbo1011IP = "192.168.10.11" + healthCheckMethodTest = "test" + healthCheckDubboUrlFormat = "dubbo://%s:20000/com.ikurento.user.UserProvider" +) +func TestDefaultHealthCheckerIsHealthy(t *testing.T) { defer protocol.CleanAllStatus() - url, _ := common.NewURL("dubbo://192.168.10.10:20000/com.ikurento.user.UserProvider") + url, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1010IP)) hc := NewDefaultHealthChecker(&url).(*DefaultHealthChecker) invoker := NewMockInvoker(url) healthy := hc.IsHealthy(invoker) @@ -45,7 +52,7 @@ func TestDefaultHealthChecker_IsHealthy(t *testing.T) { url.SetParam(constant.SUCCESSIVE_FAILED_REQUEST_THRESHOLD_KEY, "100") // fake the outgoing request for i := 0; i < 11; i++ { - request(url, "test", 0, true, false) + request(url, healthCheckMethodTest, 0, true, false) } hc = NewDefaultHealthChecker(&url).(*DefaultHealthChecker) healthy = hc.IsHealthy(invoker) @@ -54,7 +61,7 @@ func TestDefaultHealthChecker_IsHealthy(t *testing.T) { // successive failed count is more than constant.SUCCESSIVE_FAILED_REQUEST_THRESHOLD_KEY, go to unhealthy for i := 0; i < 11; i++ { - request(url, "test", 0, false, false) + request(url, healthCheckMethodTest, 0, false, false) } url.SetParam(constant.SUCCESSIVE_FAILED_REQUEST_THRESHOLD_KEY, "10") url.SetParam(constant.OUTSTANDING_REQUEST_COUNT_LIMIT_KEY, "1000") @@ -63,18 +70,18 @@ func TestDefaultHealthChecker_IsHealthy(t *testing.T) { assert.False(t, hc.IsHealthy(invoker)) // reset successive failed count and go to healthy - request(url, "test", 0, false, true) + request(url, healthCheckMethodTest, 0, false, true) healthy = hc.IsHealthy(invoker) assert.True(t, hc.IsHealthy(invoker)) } -func TestDefaultHealthChecker_getCircuitBreakerSleepWindowTime(t *testing.T) { +func TestDefaultHealthCheckerGetCircuitBreakerSleepWindowTime(t *testing.T) { defer protocol.CleanAllStatus() - url, _ := common.NewURL("dubbo://192.168.10.10:20000/com.ikurento.user.UserProvider") + url, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1010IP)) defaultHc := NewDefaultHealthChecker(&url).(*DefaultHealthChecker) // Increase the number of failed requests for i := 0; i < 100; i++ { - request(url, "test", 1, false, false) + request(url, healthCheckMethodTest, 1, false, false) } sleepWindowTime := defaultHc.getCircuitBreakerSleepWindowTime(protocol.GetURLStatus(url)) assert.True(t, sleepWindowTime == constant.MAX_CIRCUIT_TRIPPED_TIMEOUT_IN_MS) @@ -84,48 +91,48 @@ func TestDefaultHealthChecker_getCircuitBreakerSleepWindowTime(t *testing.T) { sleepWindowTime = NewDefaultHealthChecker(&url).(*DefaultHealthChecker).getCircuitBreakerSleepWindowTime(protocol.GetURLStatus(url)) assert.True(t, sleepWindowTime == 0) - url1, _ := common.NewURL("dubbo://192.168.10.11:20000/com.ikurento.user.UserProvider") + url1, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1011IP)) sleepWindowTime = defaultHc.getCircuitBreakerSleepWindowTime(protocol.GetURLStatus(url1)) assert.True(t, sleepWindowTime == 0) - request(url1, "test", 1, false, false) - request(url1, "test", 1, false, false) - request(url1, "test", 1, false, false) - request(url1, "test", 1, false, false) - request(url1, "test", 1, false, false) - request(url1, "test", 1, false, false) + request(url1, healthCheckMethodTest, 1, false, false) + request(url1, healthCheckMethodTest, 1, false, false) + request(url1, healthCheckMethodTest, 1, false, false) + request(url1, healthCheckMethodTest, 1, false, false) + request(url1, healthCheckMethodTest, 1, false, false) + request(url1, healthCheckMethodTest, 1, false, false) sleepWindowTime = defaultHc.getCircuitBreakerSleepWindowTime(protocol.GetURLStatus(url1)) assert.True(t, sleepWindowTime > 0 && sleepWindowTime < constant.MAX_CIRCUIT_TRIPPED_TIMEOUT_IN_MS) } -func TestDefaultHealthChecker_getCircuitBreakerTimeout(t *testing.T) { +func TestDefaultHealthCheckerGetCircuitBreakerTimeout(t *testing.T) { defer protocol.CleanAllStatus() - url, _ := common.NewURL("dubbo://192.168.10.10:20000/com.ikurento.user.UserProvider") + url, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1010IP)) defaultHc := NewDefaultHealthChecker(&url).(*DefaultHealthChecker) timeout := defaultHc.getCircuitBreakerTimeout(protocol.GetURLStatus(url)) assert.True(t, timeout == 0) - url1, _ := common.NewURL("dubbo://192.168.10.11:20000/com.ikurento.user.UserProvider") - request(url1, "test", 1, false, false) - request(url1, "test", 1, false, false) - request(url1, "test", 1, false, false) - request(url1, "test", 1, false, false) - request(url1, "test", 1, false, false) - request(url1, "test", 1, false, false) + url1, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1011IP)) + request(url1, healthCheckMethodTest, 1, false, false) + request(url1, healthCheckMethodTest, 1, false, false) + request(url1, healthCheckMethodTest, 1, false, false) + request(url1, healthCheckMethodTest, 1, false, false) + request(url1, healthCheckMethodTest, 1, false, false) + request(url1, healthCheckMethodTest, 1, false, false) timeout = defaultHc.getCircuitBreakerTimeout(protocol.GetURLStatus(url1)) // timeout must after the current time assert.True(t, timeout > protocol.CurrentTimeMillis()) } -func TestDefaultHealthChecker_isCircuitBreakerTripped(t *testing.T) { +func TestDefaultHealthCheckerIsCircuitBreakerTripped(t *testing.T) { defer protocol.CleanAllStatus() - url, _ := common.NewURL("dubbo://192.168.10.10:20000/com.ikurento.user.UserProvider") + url, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1010IP)) defaultHc := NewDefaultHealthChecker(&url).(*DefaultHealthChecker) status := protocol.GetURLStatus(url) tripped := defaultHc.isCircuitBreakerTripped(status) assert.False(t, tripped) // Increase the number of failed requests for i := 0; i < 100; i++ { - request(url, "test", 1, false, false) + request(url, healthCheckMethodTest, 1, false, false) } tripped = defaultHc.isCircuitBreakerTripped(protocol.GetURLStatus(url)) assert.True(t, tripped) @@ -134,13 +141,13 @@ func TestDefaultHealthChecker_isCircuitBreakerTripped(t *testing.T) { func TestNewDefaultHealthChecker(t *testing.T) { defer protocol.CleanAllStatus() - url, _ := common.NewURL("dubbo://192.168.10.10:20000/com.ikurento.user.UserProvider") + url, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1010IP)) defaultHc := NewDefaultHealthChecker(&url).(*DefaultHealthChecker) assert.NotNil(t, defaultHc) assert.Equal(t, defaultHc.outStandingRequestConutLimit, int32(math.MaxInt32)) assert.Equal(t, defaultHc.requestSuccessiveFailureThreshold, int32(constant.DEFAULT_SUCCESSIVE_FAILED_REQUEST_MAX_DIFF)) - url1, _ := common.NewURL("dubbo://192.168.10.10:20000/com.ikurento.user.UserProvider") + url1, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1010IP)) url1.SetParam(constant.OUTSTANDING_REQUEST_COUNT_LIMIT_KEY, "10") url1.SetParam(constant.SUCCESSIVE_FAILED_REQUEST_THRESHOLD_KEY, "10") nondefaultHc := NewDefaultHealthChecker(&url1).(*DefaultHealthChecker) diff --git a/cluster/router/healthcheck/factory.go b/cluster/router/healthcheck/factory.go index 32d84d145ceb2aa05f5a75de352e52d13dd9d6b3..40c9dd7ab9e431a16833507ee4093ff7fbff8c95 100644 --- a/cluster/router/healthcheck/factory.go +++ b/cluster/router/healthcheck/factory.go @@ -33,11 +33,11 @@ type HealthCheckRouteFactory struct { } // newHealthCheckRouteFactory construct a new HealthCheckRouteFactory -func newHealthCheckRouteFactory() router.RouterFactory { +func newHealthCheckRouteFactory() router.PriorityRouterFactory { return &HealthCheckRouteFactory{} } -// NewRouter construct a new NewHealthCheckRouter via url -func (f *HealthCheckRouteFactory) NewRouter(url *common.URL) (router.Router, error) { +// NewPriorityRouter construct a new NewHealthCheckRouter via url +func (f *HealthCheckRouteFactory) NewPriorityRouter(url *common.URL) (router.PriorityRouter, error) { return NewHealthCheckRouter(url) } diff --git a/cluster/router/healthcheck/health_check_route.go b/cluster/router/healthcheck/health_check_route.go index 1ddc9ccb173881a87bc5351711326f02ab2da3f6..ee42e47e3b26c9a1976b4599d3464d752b615e0a 100644 --- a/cluster/router/healthcheck/health_check_route.go +++ b/cluster/router/healthcheck/health_check_route.go @@ -38,7 +38,7 @@ type HealthCheckRouter struct { } // NewHealthCheckRouter construct an HealthCheckRouter via url -func NewHealthCheckRouter(url *common.URL) (router.Router, error) { +func NewHealthCheckRouter(url *common.URL) (router.PriorityRouter, error) { r := &HealthCheckRouter{ url: url, enabled: url.GetParamBool(HEALTH_ROUTE_ENABLED_KEY, false), diff --git a/cluster/router/healthcheck/health_check_route_test.go b/cluster/router/healthcheck/health_check_route_test.go index 7bfffea705bfedade9d1d13ac7e9c380651335dd..d5862fb884114bac0ea2ec9ee8926baac57d5ba6 100644 --- a/cluster/router/healthcheck/health_check_route_test.go +++ b/cluster/router/healthcheck/health_check_route_test.go @@ -18,6 +18,7 @@ package healthcheck import ( + "fmt" "math" "testing" "time" @@ -34,13 +35,22 @@ import ( "github.com/apache/dubbo-go/protocol/invocation" ) -func TestHealthCheckRouter_Route(t *testing.T) { +const ( + healthCheckRoute1010IP = "192.168.10.10" + healthCheckRoute1011IP = "192.168.10.11" + healthCheckRoute1012IP = "192.168.10.12" + healthCheckRouteMethodNameTest = "test" + healthCheck1001URL = "dubbo://192.168.10.1/com.ikurento.user.UserProvider" + healthCheckRouteUrlFormat = "dubbo://%s:20000/com.ikurento.user.UserProvider" +) + +func TestHealthCheckRouterRoute(t *testing.T) { defer protocol.CleanAllStatus() - consumerURL, _ := common.NewURL("dubbo://192.168.10.1/com.ikurento.user.UserProvider") + consumerURL, _ := common.NewURL(healthCheck1001URL) consumerURL.SetParam(HEALTH_ROUTE_ENABLED_KEY, "true") - url1, _ := common.NewURL("dubbo://192.168.10.10:20000/com.ikurento.user.UserProvider") - url2, _ := common.NewURL("dubbo://192.168.10.11:20000/com.ikurento.user.UserProvider") - url3, _ := common.NewURL("dubbo://192.168.10.12:20000/com.ikurento.user.UserProvider") + url1, _ := common.NewURL(fmt.Sprintf(healthCheckRouteUrlFormat, healthCheckRoute1010IP)) + url2, _ := common.NewURL(fmt.Sprintf(healthCheckRouteUrlFormat, healthCheckRoute1011IP)) + url3, _ := common.NewURL(fmt.Sprintf(healthCheckRouteUrlFormat, healthCheckRoute1012IP)) hcr, _ := NewHealthCheckRouter(&consumerURL) var invokers []protocol.Invoker @@ -48,21 +58,21 @@ func TestHealthCheckRouter_Route(t *testing.T) { invoker2 := NewMockInvoker(url2) invoker3 := NewMockInvoker(url3) invokers = append(invokers, invoker1, invoker2, invoker3) - inv := invocation.NewRPCInvocation("test", nil, nil) + inv := invocation.NewRPCInvocation(healthCheckRouteMethodNameTest, nil, nil) res := hcr.Route(invokers, &consumerURL, inv) // now all invokers are healthy assert.True(t, len(res) == len(invokers)) for i := 0; i < 10; i++ { - request(url1, "test", 0, false, false) + request(url1, healthCheckRouteMethodNameTest, 0, false, false) } res = hcr.Route(invokers, &consumerURL, inv) // invokers1 is unhealthy now assert.True(t, len(res) == 2 && !contains(res, invoker1)) for i := 0; i < 10; i++ { - request(url1, "test", 0, false, false) - request(url2, "test", 0, false, false) + request(url1, healthCheckRouteMethodNameTest, 0, false, false) + request(url2, healthCheckRouteMethodNameTest, 0, false, false) } res = hcr.Route(invokers, &consumerURL, inv) @@ -70,9 +80,9 @@ func TestHealthCheckRouter_Route(t *testing.T) { assert.True(t, len(res) == 1 && !contains(res, invoker1) && !contains(res, invoker2)) for i := 0; i < 10; i++ { - request(url1, "test", 0, false, false) - request(url2, "test", 0, false, false) - request(url3, "test", 0, false, false) + request(url1, healthCheckRouteMethodNameTest, 0, false, false) + request(url2, healthCheckRouteMethodNameTest, 0, false, false) + request(url3, healthCheckRouteMethodNameTest, 0, false, false) } res = hcr.Route(invokers, &consumerURL, inv) @@ -80,12 +90,12 @@ func TestHealthCheckRouter_Route(t *testing.T) { assert.True(t, len(res) == 3) // reset the invoker1 successive failed count, so invoker1 go to healthy - request(url1, "test", 0, false, true) + request(url1, healthCheckRouteMethodNameTest, 0, false, true) res = hcr.Route(invokers, &consumerURL, inv) assert.True(t, contains(res, invoker1)) for i := 0; i < 6; i++ { - request(url1, "test", 0, false, false) + request(url1, healthCheckRouteMethodNameTest, 0, false, false) } // now all invokers are unhealthy, so downgraded to all again res = hcr.Route(invokers, &consumerURL, inv) @@ -108,7 +118,7 @@ func contains(invokers []protocol.Invoker, invoker protocol.Invoker) bool { func TestNewHealthCheckRouter(t *testing.T) { defer protocol.CleanAllStatus() - url, _ := common.NewURL("dubbo://192.168.10.10:20000/com.ikurento.user.UserProvider") + url, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1010IP)) hcr, _ := NewHealthCheckRouter(&url) h := hcr.(*HealthCheckRouter) assert.Nil(t, h.checker) diff --git a/cluster/router/router.go b/cluster/router/router.go index 9ee1154437e6fd205f08098deabb1ca260c3c040..1d1f79d277860abf34bebb9deab8a0f0a67c7b5d 100644 --- a/cluster/router/router.go +++ b/cluster/router/router.go @@ -23,34 +23,30 @@ import ( ) // Extension - Router - -// RouterFactory Router create factory -type RouterFactory interface { - // NewRouter Create router instance with URL - NewRouter(*common.URL) (Router, error) +// PriorityRouterFactory creates creates priority router with url +type PriorityRouterFactory interface { + // NewPriorityRouter creates router instance with URL + NewPriorityRouter(*common.URL) (PriorityRouter, error) } -// RouterFactory Router create factory use for parse config file -type FileRouterFactory interface { +// FilePriorityRouterFactory creates priority router with parse config file +type FilePriorityRouterFactory interface { // NewFileRouters Create file router with config file - NewFileRouter([]byte) (Router, error) + NewFileRouter([]byte) (PriorityRouter, error) } // Router -type Router interface { +type router interface { // Route Determine the target invokers list. Route([]protocol.Invoker, *common.URL, protocol.Invocation) []protocol.Invoker - // Priority Return Priority in router - // 0 to ^int(0) is better - Priority() int64 // URL Return URL in router URL() common.URL } -// Chain -type Chain interface { - // Route Determine the target invokers list with chain. - Route([]protocol.Invoker, *common.URL, protocol.Invocation) []protocol.Invoker - // AddRouters Add routers - AddRouters([]Router) +// Router +type PriorityRouter interface { + router + // Priority Return Priority in router + // 0 to ^int(0) is better + Priority() int64 } diff --git a/cluster/router/tag/factory.go b/cluster/router/tag/factory.go index d74924c89862ae4f4cd85b59c7008880298c0c99..a5d989cd31453f6d02eee9c5902dc3666defe4fe 100644 --- a/cluster/router/tag/factory.go +++ b/cluster/router/tag/factory.go @@ -31,17 +31,17 @@ func init() { type tagRouterFactory struct{} // NewTagRouterFactory create a tagRouterFactory -func NewTagRouterFactory() router.RouterFactory { +func NewTagRouterFactory() router.PriorityRouterFactory { return &tagRouterFactory{} } -// NewRouter create a tagRouter by tagRouterFactory with a url +// NewPriorityRouter create a tagRouter by tagRouterFactory with a url // The url contains router configuration information -func (c *tagRouterFactory) NewRouter(url *common.URL) (router.Router, error) { +func (c *tagRouterFactory) NewPriorityRouter(url *common.URL) (router.PriorityRouter, error) { return NewTagRouter(url) } // NewFileRouter create a tagRouter by profile content -func (c *tagRouterFactory) NewFileRouter(content []byte) (router.Router, error) { +func (c *tagRouterFactory) NewFileRouter(content []byte) (router.PriorityRouter, error) { return NewFileTagRouter(content) } diff --git a/cluster/router/tag/factory_test.go b/cluster/router/tag/factory_test.go index 58bff5b18113d69f97ec513e393aa6759a3cf050..ee195820c123e1fc67a2c27cd12aaa544650b615 100644 --- a/cluster/router/tag/factory_test.go +++ b/cluster/router/tag/factory_test.go @@ -18,6 +18,7 @@ package tag import ( + "fmt" "testing" ) @@ -29,11 +30,16 @@ import ( "github.com/apache/dubbo-go/common" ) -func TestTagRouterFactory_NewRouter(t *testing.T) { - u1, err := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0&enabled=true") +const ( + factoryLocalIP = "127.0.0.1" + factoryFormat = "dubbo://%s:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0&enabled=true" +) + +func TestTagRouterFactoryNewRouter(t *testing.T) { + u1, err := common.NewURL(fmt.Sprintf(factoryFormat, factoryLocalIP)) assert.Nil(t, err) factory := NewTagRouterFactory() - tagRouter, e := factory.NewRouter(&u1) + tagRouter, e := factory.NewPriorityRouter(&u1) assert.Nil(t, e) assert.NotNil(t, tagRouter) } diff --git a/cluster/router/tag/file_test.go b/cluster/router/tag/file_test.go index 94fcf9e0e0fabed2445417d14b711f91b65b9e5e..513ba0c0b6c622d6a52fad35a24824121eb71b76 100644 --- a/cluster/router/tag/file_test.go +++ b/cluster/router/tag/file_test.go @@ -29,18 +29,21 @@ import ( "github.com/apache/dubbo-go/common/constant" ) +const ( + fileTestTag = `priority: 100 +force: true` +) + func TestNewFileTagRouter(t *testing.T) { - router, e := NewFileTagRouter([]byte(`priority: 100 -force: true`)) + router, e := NewFileTagRouter([]byte(fileTestTag)) assert.Nil(t, e) assert.NotNil(t, router) assert.Equal(t, 100, router.routerRule.Priority) assert.Equal(t, true, router.routerRule.Force) } -func TestFileTagRouter_URL(t *testing.T) { - router, e := NewFileTagRouter([]byte(`priority: 100 -force: true`)) +func TestFileTagRouterURL(t *testing.T) { + router, e := NewFileTagRouter([]byte(fileTestTag)) assert.Nil(t, e) assert.NotNil(t, router) url := router.URL() @@ -52,9 +55,8 @@ force: true`)) } -func TestFileTagRouter_Priority(t *testing.T) { - router, e := NewFileTagRouter([]byte(`priority: 100 -force: true`)) +func TestFileTagRouterPriority(t *testing.T) { + router, e := NewFileTagRouter([]byte(fileTestTag)) assert.Nil(t, e) assert.NotNil(t, router) priority := router.Priority() diff --git a/cluster/router/tag/tag_router_test.go b/cluster/router/tag/tag_router_test.go index 280b56c8ccb69eb5d32dae2369bdc862adb8e6fd..000b3ec6724d85590c86456a009d5194c4e71e03 100644 --- a/cluster/router/tag/tag_router_test.go +++ b/cluster/router/tag/tag_router_test.go @@ -32,6 +32,21 @@ import ( "github.com/apache/dubbo-go/protocol/invocation" ) +const ( + tagRouterTestHangZhouUrl = "dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0&enabled=true&dubbo.tag=hangzhou" + tagRouterTestShangHaiUrl = "dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0&enabled=true&dubbo.tag=shanghai" + tagRouterTestBeijingUrl = "dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0&enabled=true&dubbo.tag=beijing" + tagRouterTestUserConsumer = "dubbo://127.0.0.1:20000/com.ikurento.user.UserConsumer?interface=com.ikurento.user.UserConsumer&group=&version=2.6.0&enabled=true" + tagRouterTestUserConsumerTag = "dubbo://127.0.0.1:20000/com.ikurento.user.UserConsumer?interface=com.ikurento.user.UserConsumer&group=&version=2.6.0&enabled=true&dubbo.force.tag=true" + + tagRouterTestDubboTag = "dubbo.tag" + tagRouterTestDubboForceTag = "dubbo.force.tag" + tagRouterTestHangZhou = "hangzhou" + tagRouterTestGuangZhou = "guangzhou" + tagRouterTestFalse = "false" + tagRouterTestTrue = "true" +) + // MockInvoker is only mock the Invoker to support test tagRouter type MockInvoker struct { url common.URL @@ -73,8 +88,8 @@ func (bi *MockInvoker) Destroy() { bi.available = false } -func TestTagRouter_Priority(t *testing.T) { - u1, err := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserConsumer?interface=com.ikurento.user.UserConsumer&group=&version=2.6.0&enabled=true&dubbo.force.tag=true") +func TestTagRouterPriority(t *testing.T) { + u1, err := common.NewURL(tagRouterTestUserConsumerTag) assert.Nil(t, err) tagRouter, e := NewTagRouter(&u1) assert.Nil(t, e) @@ -82,15 +97,15 @@ func TestTagRouter_Priority(t *testing.T) { assert.Equal(t, int64(0), p) } -func TestTagRouter_Route_force(t *testing.T) { - u1, e1 := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserConsumer?interface=com.ikurento.user.UserConsumer&group=&version=2.6.0&enabled=true&dubbo.force.tag=true") +func TestTagRouterRouteForce(t *testing.T) { + u1, e1 := common.NewURL(tagRouterTestUserConsumerTag) assert.Nil(t, e1) tagRouter, e := NewTagRouter(&u1) assert.Nil(t, e) - u2, e2 := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0&enabled=true&dubbo.tag=hangzhou") - u3, e3 := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0&enabled=true&dubbo.tag=shanghai") - u4, e4 := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0&enabled=true&dubbo.tag=beijing") + u2, e2 := common.NewURL(tagRouterTestHangZhouUrl) + u3, e3 := common.NewURL(tagRouterTestShangHaiUrl) + u4, e4 := common.NewURL(tagRouterTestBeijingUrl) assert.Nil(t, e2) assert.Nil(t, e3) assert.Nil(t, e4) @@ -100,29 +115,29 @@ func TestTagRouter_Route_force(t *testing.T) { var invokers []protocol.Invoker invokers = append(invokers, inv2, inv3, inv4) inv := &invocation.RPCInvocation{} - inv.SetAttachments("dubbo.tag", "hangzhou") + inv.SetAttachments(tagRouterTestDubboTag, tagRouterTestHangZhou) invRst1 := tagRouter.Route(invokers, &u1, inv) assert.Equal(t, 1, len(invRst1)) - assert.Equal(t, "hangzhou", invRst1[0].GetUrl().GetParam("dubbo.tag", "")) + assert.Equal(t, tagRouterTestHangZhou, invRst1[0].GetUrl().GetParam(tagRouterTestDubboTag, "")) - inv.SetAttachments("dubbo.tag", "guangzhou") + inv.SetAttachments(tagRouterTestDubboTag, tagRouterTestGuangZhou) invRst2 := tagRouter.Route(invokers, &u1, inv) assert.Equal(t, 0, len(invRst2)) - inv.SetAttachments("dubbo.force.tag", "false") - inv.SetAttachments("dubbo.tag", "guangzhou") + inv.SetAttachments(tagRouterTestDubboForceTag, tagRouterTestFalse) + inv.SetAttachments(tagRouterTestDubboTag, tagRouterTestGuangZhou) invRst3 := tagRouter.Route(invokers, &u1, inv) assert.Equal(t, 3, len(invRst3)) } -func TestTagRouter_Route_noForce(t *testing.T) { - u1, e1 := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserConsumer?interface=com.ikurento.user.UserConsumer&group=&version=2.6.0&enabled=true") +func TestTagRouterRouteNoForce(t *testing.T) { + u1, e1 := common.NewURL(tagRouterTestUserConsumer) assert.Nil(t, e1) tagRouter, e := NewTagRouter(&u1) assert.Nil(t, e) - u2, e2 := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0&enabled=true&dubbo.tag=hangzhou") - u3, e3 := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0&enabled=true&dubbo.tag=shanghai") - u4, e4 := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0&enabled=true&dubbo.tag=beijing") + u2, e2 := common.NewURL(tagRouterTestHangZhouUrl) + u3, e3 := common.NewURL(tagRouterTestShangHaiUrl) + u4, e4 := common.NewURL(tagRouterTestShangHaiUrl) assert.Nil(t, e2) assert.Nil(t, e3) assert.Nil(t, e4) @@ -132,16 +147,16 @@ func TestTagRouter_Route_noForce(t *testing.T) { var invokers []protocol.Invoker invokers = append(invokers, inv2, inv3, inv4) inv := &invocation.RPCInvocation{} - inv.SetAttachments("dubbo.tag", "hangzhou") + inv.SetAttachments(tagRouterTestDubboTag, tagRouterTestHangZhou) invRst := tagRouter.Route(invokers, &u1, inv) assert.Equal(t, 1, len(invRst)) - assert.Equal(t, "hangzhou", invRst[0].GetUrl().GetParam("dubbo.tag", "")) + assert.Equal(t, tagRouterTestHangZhou, invRst[0].GetUrl().GetParam(tagRouterTestDubboTag, "")) - inv.SetAttachments("dubbo.tag", "guangzhou") - inv.SetAttachments("dubbo.force.tag", "true") + inv.SetAttachments(tagRouterTestDubboTag, tagRouterTestGuangZhou) + inv.SetAttachments(tagRouterTestDubboForceTag, tagRouterTestTrue) invRst1 := tagRouter.Route(invokers, &u1, inv) assert.Equal(t, 0, len(invRst1)) - inv.SetAttachments("dubbo.force.tag", "false") + inv.SetAttachments(tagRouterTestDubboForceTag, tagRouterTestFalse) invRst2 := tagRouter.Route(invokers, &u1, inv) assert.Equal(t, 3, len(invRst2)) } diff --git a/common/config/environment.go b/common/config/environment.go index 446c46aa1ef71a68aa024bf83dd9088cf03677f2..44cdd1fca18bfed306b135fe38ef536779e148aa 100644 --- a/common/config/environment.go +++ b/common/config/environment.go @@ -131,7 +131,7 @@ func (conf *InmemoryConfiguration) GetSubProperty(subKey string) map[string]stru } properties := make(map[string]struct{}) - conf.store.Range(func(key, value interface{}) bool { + conf.store.Range(func(key, _ interface{}) bool { if idx := strings.Index(key.(string), subKey); idx >= 0 { after := key.(string)[idx+len(subKey):] if i := strings.Index(after, "."); i >= 0 { diff --git a/common/config/environment_test.go b/common/config/environment_test.go index 2d84dc4ae31ef74fdcf2a37d7acb4a3e4cf36a09..183071b0ef0d10e9ce010965668b46d30b008a15 100644 --- a/common/config/environment_test.go +++ b/common/config/environment_test.go @@ -29,14 +29,14 @@ func TestGetEnvInstance(t *testing.T) { assert.NotNil(t, instance) } -func TestEnvironment_UpdateExternalConfigMap(t *testing.T) { +func TestEnvironmentUpdateExternalConfigMap(t *testing.T) { GetEnvInstance().UpdateExternalConfigMap(map[string]string{"1": "2"}) v, ok := GetEnvInstance().externalConfigMap.Load("1") assert.True(t, ok) assert.Equal(t, "2", v) } -func TestEnvironment_ConfigurationAndGetProperty(t *testing.T) { +func TestEnvironmentConfigurationAndGetProperty(t *testing.T) { GetEnvInstance().UpdateExternalConfigMap(map[string]string{"1": "2"}) list := GetEnvInstance().Configuration() ok, v := list.Back().Value.(*InmemoryConfiguration).GetProperty("1") @@ -44,7 +44,7 @@ func TestEnvironment_ConfigurationAndGetProperty(t *testing.T) { assert.Equal(t, "2", v) } -func TestInmemoryConfiguration_GetSubProperty(t *testing.T) { +func TestInmemoryConfigurationGetSubProperty(t *testing.T) { GetEnvInstance().UpdateExternalConfigMap(map[string]string{"123": "2"}) list := GetEnvInstance().Configuration() m := list.Front().Value.(*InmemoryConfiguration).GetSubProperty("1") diff --git a/common/constant/key.go b/common/constant/key.go index f0130b07448140bbb8d71134b688df708e1e3ff7..12a737966dbd8da097fb9fbcd23ab83f0a1a51d4 100644 --- a/common/constant/key.go +++ b/common/constant/key.go @@ -158,6 +158,7 @@ const ( NACOS_CATEGORY_KEY = "category" NACOS_PROTOCOL_KEY = "protocol" NACOS_PATH_KEY = "path" + NACOS_NAMESPACE_ID = "namespaceId" ) const ( diff --git a/common/extension/health_checker.go b/common/extension/health_checker.go index 548d4dc761b31773a2a39ccb0ae3de1d7ab39eb4..8def727614dad8393eeef9ced5e30a056fa65461 100644 --- a/common/extension/health_checker.go +++ b/common/extension/health_checker.go @@ -27,7 +27,7 @@ var ( ) // SethealthChecker sets the HealthChecker with @name -func SethealthChecker(name string, fcn func(url *common.URL) router.HealthChecker) { +func SethealthChecker(name string, fcn func(_ *common.URL) router.HealthChecker) { healthCheckers[name] = fcn } diff --git a/common/extension/health_checker_test.go b/common/extension/health_checker_test.go index ec934e6e9cedc5acbef350f17b87b0b2e37bc844..4e83a6f6e1ed8a57b6e6374377d08eabfb56c604 100644 --- a/common/extension/health_checker_test.go +++ b/common/extension/health_checker_test.go @@ -44,6 +44,6 @@ func (m mockHealthChecker) IsHealthy(invoker protocol.Invoker) bool { return true } -func newMockhealthCheck(url *common.URL) router.HealthChecker { +func newMockhealthCheck(_ *common.URL) router.HealthChecker { return &mockHealthChecker{} } diff --git a/common/extension/metrics_test.go b/common/extension/metrics_test.go index 6a8a3fe538a9cd68c57c91592a88ec257ae4a267..2aaae75f0ccf7929754582aa42aa1bff4ece7c22 100644 --- a/common/extension/metrics_test.go +++ b/common/extension/metrics_test.go @@ -45,5 +45,6 @@ func TestGetMetricReporter(t *testing.T) { type mockReporter struct { } +// Report method for feature expansion func (m mockReporter) Report(ctx context.Context, invoker protocol.Invoker, invocation protocol.Invocation, cost time.Duration, res protocol.Result) { } diff --git a/common/extension/registry.go b/common/extension/registry.go index 542a2206c0bdda658c4ba363e939bbc569b2b49e..187c8fecf4e27c87d6feff8749730c77a83b2f32 100644 --- a/common/extension/registry.go +++ b/common/extension/registry.go @@ -27,7 +27,7 @@ var ( ) // SetRegistry sets the registry extension with @name -func SetRegistry(name string, v func(config *common.URL) (registry.Registry, error)) { +func SetRegistry(name string, v func(_ *common.URL) (registry.Registry, error)) { registrys[name] = v } diff --git a/common/extension/rest_client.go b/common/extension/rest_client.go index 9caf8c67df76bb160d5e2c3100f83e2d198b6381..0c2f4ddf95d2226cfadc3ab6492c629ba15c4063 100644 --- a/common/extension/rest_client.go +++ b/common/extension/rest_client.go @@ -26,7 +26,7 @@ var ( ) // SetRestClient sets the RestClient with @name -func SetRestClient(name string, fun func(restOptions *client.RestOptions) client.RestClient) { +func SetRestClient(name string, fun func(_ *client.RestOptions) client.RestClient) { restClients[name] = fun } diff --git a/common/extension/router_factory.go b/common/extension/router_factory.go index 21a49d2681b500bf4e4942d1b92e5b23bc7cf6b7..b61a05668a0cd24e28f6de46754c00ffbcb766d8 100644 --- a/common/extension/router_factory.go +++ b/common/extension/router_factory.go @@ -26,18 +26,18 @@ import ( ) var ( - routers = make(map[string]func() router.RouterFactory) + routers = make(map[string]func() router.PriorityRouterFactory) fileRouterFactoryOnce sync.Once - fileRouterFactories = make(map[string]router.FileRouterFactory) + fileRouterFactories = make(map[string]router.FilePriorityRouterFactory) ) // SetRouterFactory sets create router factory function with @name -func SetRouterFactory(name string, fun func() router.RouterFactory) { +func SetRouterFactory(name string, fun func() router.PriorityRouterFactory) { routers[name] = fun } // GetRouterFactory gets create router factory function by @name -func GetRouterFactory(name string) router.RouterFactory { +func GetRouterFactory(name string) router.PriorityRouterFactory { if routers[name] == nil { panic("router_factory for " + name + " is not existing, make sure you have import the package.") } @@ -45,12 +45,12 @@ func GetRouterFactory(name string) router.RouterFactory { } // GetRouterFactories gets all create router factory function -func GetRouterFactories() map[string]func() router.RouterFactory { +func GetRouterFactories() map[string]func() router.PriorityRouterFactory { return routers } // GetFileRouterFactories gets all create file router factory instance -func GetFileRouterFactories() map[string]router.FileRouterFactory { +func GetFileRouterFactories() map[string]router.FilePriorityRouterFactory { l := len(routers) if l == 0 { return nil @@ -58,7 +58,7 @@ func GetFileRouterFactories() map[string]router.FileRouterFactory { fileRouterFactoryOnce.Do(func() { for k := range routers { factory := GetRouterFactory(k) - if fr, ok := factory.(router.FileRouterFactory); ok { + if fr, ok := factory.(router.FilePriorityRouterFactory); ok { fileRouterFactories[k] = fr } } diff --git a/common/proxy/proxy_factory/default.go b/common/proxy/proxy_factory/default.go index 1bb1e29c5ced78ad9e2e2483b73379c66328050a..1b8ca222011292040c57c3e86df0438943a5b464 100644 --- a/common/proxy/proxy_factory/default.go +++ b/common/proxy/proxy_factory/default.go @@ -54,7 +54,7 @@ type DefaultProxyFactory struct { //} // NewDefaultProxyFactory returns a proxy factory instance -func NewDefaultProxyFactory(options ...proxy.Option) proxy.ProxyFactory { +func NewDefaultProxyFactory(_ ...proxy.Option) proxy.ProxyFactory { return &DefaultProxyFactory{} } diff --git a/common/proxy/proxy_factory/default_test.go b/common/proxy/proxy_factory/default_test.go index 7159b4b00eb2fcddb0f20f701f56b3179e57c4a0..99d5c020f4bfd0254ddddc65e78bcae2e252b6be 100644 --- a/common/proxy/proxy_factory/default_test.go +++ b/common/proxy/proxy_factory/default_test.go @@ -31,7 +31,7 @@ import ( "github.com/apache/dubbo-go/protocol" ) -func Test_GetProxy(t *testing.T) { +func TestGetProxy(t *testing.T) { proxyFactory := NewDefaultProxyFactory() url := common.NewURLWithOptions() proxy := proxyFactory.GetProxy(protocol.NewBaseInvoker(*url), url) @@ -45,7 +45,7 @@ func (u *TestAsync) CallBack(res common.CallbackResponse) { fmt.Println("CallBack res:", res) } -func Test_GetAsyncProxy(t *testing.T) { +func TestGetAsyncProxy(t *testing.T) { proxyFactory := NewDefaultProxyFactory() url := common.NewURLWithOptions() async := &TestAsync{} @@ -53,7 +53,7 @@ func Test_GetAsyncProxy(t *testing.T) { assert.NotNil(t, proxy) } -func Test_GetInvoker(t *testing.T) { +func TestGetInvoker(t *testing.T) { proxyFactory := NewDefaultProxyFactory() url := common.NewURLWithOptions() invoker := proxyFactory.GetInvoker(*url) diff --git a/common/proxy/proxy_test.go b/common/proxy/proxy_test.go index 8c1c0295d05135095b5be35b5b2b16428691d7f2..14b2befbc47242d9cc9a2f88e9070b84828062c0 100644 --- a/common/proxy/proxy_test.go +++ b/common/proxy/proxy_test.go @@ -53,7 +53,7 @@ func (s *TestServiceInt) Reference() string { return "com.test.TestServiceInt" } -func TestProxy_Implement(t *testing.T) { +func TestProxyImplement(t *testing.T) { invoker := protocol.NewBaseInvoker(common.URL{}) p := NewProxy(invoker, nil, map[string]string{constant.ASYNC_KEY: "false"}) @@ -84,7 +84,7 @@ func TestProxy_Implement(t *testing.T) { TestService methodOne func(context.Context, interface{}, *struct{}) error } - s1 := &S1{TestService: *s, methodOne: func(i context.Context, i2 interface{}, i3 *struct{}) error { + s1 := &S1{TestService: *s, methodOne: func(_ context.Context, _ interface{}, _ *struct{}) error { return perrors.New("errors") }} p.Implement(s1) diff --git a/common/rpc_service.go b/common/rpc_service.go index 6ca0e827cb21a4065468c3f180cecdaab0afb555..200e61b398a663ae677a9a18e4c1ef841ac1b538 100644 --- a/common/rpc_service.go +++ b/common/rpc_service.go @@ -68,7 +68,6 @@ var ( typeOfError = reflect.TypeOf((*error)(nil)).Elem() // ServiceMap store description of service. - // todo: lowerecas? ServiceMap = &serviceMap{ serviceMap: make(map[string]map[string]*Service), interfaceMap: make(map[string][]*Service), diff --git a/common/rpc_service_test.go b/common/rpc_service_test.go index 2311205d0ec0c2fd4642a4d8639c0bf871fe1d17..7c4eb421d7ed0e5e0306eb1a1a2ff5ac31c29b6d 100644 --- a/common/rpc_service_test.go +++ b/common/rpc_service_test.go @@ -27,6 +27,14 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + referenceTestPath = "com.test.Path" + referenceTestPathDistinct = "com.test.Path1" + testInterfaceName = "testService" + testProtocol = "testprotocol" + testSuiteMethodExpectedString = "interface {}" +) + type TestService struct { } @@ -40,7 +48,7 @@ func (s *TestService) MethodThree() error { return nil } func (s *TestService) Reference() string { - return "com.test.Path" + return referenceTestPath } func (s *TestService) MethodMapper() map[string]string { return map[string]string{ @@ -63,36 +71,36 @@ func (s *testService) Method4(ctx context.Context, args []interface{}, rsp *stru return nil } func (s *testService) Reference() string { - return "com.test.Path" + return referenceTestPath } type TestService1 struct { } func (s *TestService1) Reference() string { - return "com.test.Path1" + return referenceTestPathDistinct } -func TestServiceMap_Register(t *testing.T) { +func TestServiceMapRegister(t *testing.T) { // lowercase s0 := &testService{} // methods, err := ServiceMap.Register("testporotocol", s0) - _, err := ServiceMap.Register("testService", "testporotocol", s0) + _, err := ServiceMap.Register(testInterfaceName, "testporotocol", s0) assert.EqualError(t, err, "type testService is not exported") // succ s := &TestService{} - methods, err := ServiceMap.Register("testService", "testporotocol", s) + methods, err := ServiceMap.Register(testInterfaceName, "testporotocol", s) assert.NoError(t, err) assert.Equal(t, "MethodOne,MethodThree,methodTwo", methods) // repeat - _, err = ServiceMap.Register("testService", "testporotocol", s) + _, err = ServiceMap.Register(testInterfaceName, "testporotocol", s) assert.EqualError(t, err, "service already defined: com.test.Path") // no method s1 := &TestService1{} - _, err = ServiceMap.Register("testService", "testporotocol", s1) + _, err = ServiceMap.Register(testInterfaceName, "testporotocol", s1) assert.EqualError(t, err, "type com.test.Path1 has no exported methods of suitable type") ServiceMap = &serviceMap{ @@ -101,28 +109,28 @@ func TestServiceMap_Register(t *testing.T) { } } -func TestServiceMap_UnRegister(t *testing.T) { +func TestServiceMapUnRegister(t *testing.T) { s := &TestService{} - _, err := ServiceMap.Register("TestService", "testprotocol", s) + _, err := ServiceMap.Register("TestService", testProtocol, s) assert.NoError(t, err) - assert.NotNil(t, ServiceMap.GetService("testprotocol", "com.test.Path")) + assert.NotNil(t, ServiceMap.GetService(testProtocol, referenceTestPath)) assert.Equal(t, 1, len(ServiceMap.GetInterface("TestService"))) - err = ServiceMap.UnRegister("", "", "com.test.Path") + err = ServiceMap.UnRegister("", "", referenceTestPath) assert.EqualError(t, err, "protocol or serviceName is nil") - err = ServiceMap.UnRegister("", "protocol", "com.test.Path") + err = ServiceMap.UnRegister("", "protocol", referenceTestPath) assert.EqualError(t, err, "no services for protocol") - err = ServiceMap.UnRegister("", "testprotocol", "com.test.Path1") + err = ServiceMap.UnRegister("", testProtocol, referenceTestPathDistinct) assert.EqualError(t, err, "no service for com.test.Path1") // succ - err = ServiceMap.UnRegister("TestService", "testprotocol", "com.test.Path") + err = ServiceMap.UnRegister("TestService", testProtocol, referenceTestPath) assert.NoError(t, err) } -func TestMethodType_SuiteContext(t *testing.T) { +func TestMethodTypeSuiteContext(t *testing.T) { mt := &MethodType{ctxType: reflect.TypeOf(context.TODO())} ctx := context.WithValue(context.Background(), "key", "value") assert.Equal(t, reflect.ValueOf(ctx), mt.SuiteContext(ctx)) @@ -139,9 +147,9 @@ func TestSuiteMethod(t *testing.T) { method = methodType.Method() assert.Equal(t, "func(*common.TestService, context.Context, interface {}, interface {}, interface {}) error", method.Type.String()) at := methodType.ArgsType() - assert.Equal(t, "interface {}", at[0].String()) - assert.Equal(t, "interface {}", at[1].String()) - assert.Equal(t, "interface {}", at[2].String()) + assert.Equal(t, testSuiteMethodExpectedString, at[0].String()) + assert.Equal(t, testSuiteMethodExpectedString, at[1].String()) + assert.Equal(t, testSuiteMethodExpectedString, at[2].String()) ct := methodType.CtxType() assert.Equal(t, "context.Context", ct.String()) rt := methodType.ReplyType() @@ -153,12 +161,12 @@ func TestSuiteMethod(t *testing.T) { method = methodType.Method() assert.Equal(t, "func(*common.TestService, interface {}, interface {}, interface {}) (interface {}, error)", method.Type.String()) at = methodType.ArgsType() - assert.Equal(t, "interface {}", at[0].String()) - assert.Equal(t, "interface {}", at[1].String()) - assert.Equal(t, "interface {}", at[2].String()) + assert.Equal(t, testSuiteMethodExpectedString, at[0].String()) + assert.Equal(t, testSuiteMethodExpectedString, at[1].String()) + assert.Equal(t, testSuiteMethodExpectedString, at[2].String()) assert.Nil(t, methodType.CtxType()) rt = methodType.ReplyType() - assert.Equal(t, "interface {}", rt.String()) + assert.Equal(t, testSuiteMethodExpectedString, rt.String()) method, ok = reflect.TypeOf(s).MethodByName("MethodThree") assert.True(t, ok) diff --git a/common/url.go b/common/url.go index e0e15739daa926f02280dc69e70ed38f673c1ae5..807d0ed5eff4ecb70d3adeb8524b841d0ec92a58 100644 --- a/common/url.go +++ b/common/url.go @@ -53,6 +53,7 @@ const ( ROUTER // PROVIDER is provider role PROVIDER + PROTOCOL = "protocol" ) var ( @@ -437,7 +438,7 @@ func (c URL) GetParamAndDecoded(key string) (string, error) { // GetRawParam gets raw param func (c URL) GetRawParam(key string) string { switch key { - case "protocol": + case PROTOCOL: return c.Protocol case "username": return c.Username @@ -525,7 +526,7 @@ func (c URL) ToMap() map[string]string { }) if c.Protocol != "" { - paramsMap["protocol"] = c.Protocol + paramsMap[PROTOCOL] = c.Protocol } if c.Username != "" { paramsMap["username"] = c.Username @@ -544,7 +545,7 @@ func (c URL) ToMap() map[string]string { paramsMap["port"] = port } if c.Protocol != "" { - paramsMap["protocol"] = c.Protocol + paramsMap[PROTOCOL] = c.Protocol } if c.Path != "" { paramsMap["path"] = c.Path diff --git a/common/url_test.go b/common/url_test.go index 4d9dff9f373f5d2250deb577621cead8c991cf4d..6845190a7362571ebbd4738bd146c94f6d644253 100644 --- a/common/url_test.go +++ b/common/url_test.go @@ -31,24 +31,30 @@ import ( "github.com/apache/dubbo-go/common/constant" ) +const ( + userName = "username" + password = "password" + loopbackAddress = "127.0.0.1" +) + func TestNewURLWithOptions(t *testing.T) { methods := []string{"Methodone,methodtwo"} params := url.Values{} params.Set("key", "value") u := NewURLWithOptions(WithPath("com.test.Service"), - WithUsername("username"), - WithPassword("password"), + WithUsername(userName), + WithPassword(password), WithProtocol("testprotocol"), - WithIp("127.0.0.1"), + WithIp(loopbackAddress), WithPort("8080"), WithMethods(methods), WithParams(params), WithParamsValue("key2", "value2")) assert.Equal(t, "/com.test.Service", u.Path) - assert.Equal(t, "username", u.Username) - assert.Equal(t, "password", u.Password) + assert.Equal(t, userName, u.Username) + assert.Equal(t, password, u.Password) assert.Equal(t, "testprotocol", u.Protocol) - assert.Equal(t, "127.0.0.1", u.Ip) + assert.Equal(t, loopbackAddress, u.Ip) assert.Equal(t, "8080", u.Port) assert.Equal(t, methods, u.Methods) assert.Equal(t, params, u.params) @@ -65,7 +71,7 @@ func TestURL(t *testing.T) { assert.Equal(t, "/com.ikurento.user.UserProvider", u.Path) assert.Equal(t, "127.0.0.1:20000", u.Location) assert.Equal(t, "dubbo", u.Protocol) - assert.Equal(t, "127.0.0.1", u.Ip) + assert.Equal(t, loopbackAddress, u.Ip) assert.Equal(t, "20000", u.Port) assert.Equal(t, URL{}.Methods, u.Methods) assert.Equal(t, "", u.Username) @@ -92,7 +98,7 @@ func TestURLWithoutSchema(t *testing.T) { assert.Equal(t, "/com.ikurento.user.UserProvider", u.Path) assert.Equal(t, "127.0.0.1:20000", u.Location) assert.Equal(t, "dubbo", u.Protocol) - assert.Equal(t, "127.0.0.1", u.Ip) + assert.Equal(t, loopbackAddress, u.Ip) assert.Equal(t, "20000", u.Port) assert.Equal(t, URL{}.Methods, u.Methods) assert.Equal(t, "", u.Username) @@ -108,7 +114,7 @@ func TestURLWithoutSchema(t *testing.T) { "ZX&pid=1447&revision=0.0.1&side=provider&timeout=3000×tamp=1556509797245", u.String()) } -func TestURL_URLEqual(t *testing.T) { +func TestURLEqual(t *testing.T) { u1, err := NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0") assert.NoError(t, err) u2, err := NewURL("dubbo://127.0.0.2:20001/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0") @@ -147,7 +153,7 @@ func TestURL_URLEqual(t *testing.T) { assert.True(t, categoryAny.URLEqual(u3)) } -func TestURL_GetParam(t *testing.T) { +func TestURLGetParam(t *testing.T) { params := url.Values{} params.Set("key", "value") u := URL{baseUrl: baseUrl{params: params}} @@ -159,7 +165,7 @@ func TestURL_GetParam(t *testing.T) { assert.Equal(t, "default", v) } -func TestURL_GetParamInt(t *testing.T) { +func TestURLGetParamInt(t *testing.T) { params := url.Values{} params.Set("key", "3") u := URL{baseUrl: baseUrl{params: params}} @@ -171,7 +177,7 @@ func TestURL_GetParamInt(t *testing.T) { assert.Equal(t, int64(1), v) } -func TestURL_GetParamBool(t *testing.T) { +func TestURLGetParamBool(t *testing.T) { params := url.Values{} params.Set("force", "true") u := URL{baseUrl: baseUrl{params: params}} @@ -183,7 +189,7 @@ func TestURL_GetParamBool(t *testing.T) { assert.Equal(t, false, v) } -func TestURL_GetParamAndDecoded(t *testing.T) { +func TestURLGetParamAndDecoded(t *testing.T) { rule := "host = 2.2.2.2,1.1.1.1,3.3.3.3 & host !=1.1.1.1 => host = 1.2.3.4" params := url.Values{} params.Set("rule", base64.URLEncoding.EncodeToString([]byte(rule))) @@ -192,20 +198,20 @@ func TestURL_GetParamAndDecoded(t *testing.T) { assert.Equal(t, rule, v) } -func TestURL_GetRawParam(t *testing.T) { +func TestURLGetRawParam(t *testing.T) { u, _ := NewURL("condition://0.0.0.0:8080/com.foo.BarService?serialization=fastjson") u.Username = "test" u.Password = "test" assert.Equal(t, "condition", u.GetRawParam("protocol")) assert.Equal(t, "0.0.0.0", u.GetRawParam("host")) assert.Equal(t, "8080", u.GetRawParam("port")) - assert.Equal(t, "test", u.GetRawParam("username")) - assert.Equal(t, "test", u.GetRawParam("password")) + assert.Equal(t, "test", u.GetRawParam(userName)) + assert.Equal(t, "test", u.GetRawParam(password)) assert.Equal(t, "/com.foo.BarService", u.GetRawParam("path")) assert.Equal(t, "fastjson", u.GetRawParam("serialization")) } -func TestURL_ToMap(t *testing.T) { +func TestURLToMap(t *testing.T) { u, _ := NewURL("condition://0.0.0.0:8080/com.foo.BarService?serialization=fastjson") u.Username = "test" u.Password = "test" @@ -215,13 +221,13 @@ func TestURL_ToMap(t *testing.T) { assert.Equal(t, "condition", m["protocol"]) assert.Equal(t, "0.0.0.0", m["host"]) assert.Equal(t, "8080", m["port"]) - assert.Equal(t, "test", m["username"]) - assert.Equal(t, "test", m["password"]) + assert.Equal(t, "test", m[userName]) + assert.Equal(t, "test", m[password]) assert.Equal(t, "/com.foo.BarService", m["path"]) assert.Equal(t, "fastjson", m["serialization"]) } -func TestURL_GetMethodParamInt(t *testing.T) { +func TestURLGetMethodParamInt(t *testing.T) { params := url.Values{} params.Set("methods.GetValue.timeout", "3") u := URL{baseUrl: baseUrl{params: params}} @@ -233,7 +239,7 @@ func TestURL_GetMethodParamInt(t *testing.T) { assert.Equal(t, int64(1), v) } -func TestURL_GetMethodParam(t *testing.T) { +func TestURLGetMethodParam(t *testing.T) { params := url.Values{} params.Set("methods.GetValue.timeout", "3s") u := URL{baseUrl: baseUrl{params: params}} @@ -245,7 +251,7 @@ func TestURL_GetMethodParam(t *testing.T) { assert.Equal(t, "1s", v) } -func TestURL_GetMethodParamBool(t *testing.T) { +func TestURLGetMethodParamBool(t *testing.T) { params := url.Values{} params.Set("methods.GetValue.async", "true") u := URL{baseUrl: baseUrl{params: params}} @@ -279,7 +285,7 @@ func TestMergeUrl(t *testing.T) { assert.Equal(t, "2", mergedUrl.GetParam(constant.METHOD_KEYS+".testMethod."+constant.RETRIES_KEY, "")) } -func TestURL_SetParams(t *testing.T) { +func TestURLSetParams(t *testing.T) { u1, err := NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0&configVersion=1.0") assert.NoError(t, err) params := url.Values{} diff --git a/common/yaml/yaml_test.go b/common/yaml/yaml_test.go index c8b8258a68951a1437ac2e617c13ee5af4b3a5ee..5a271a25823f576cb9cdb10c657520bbf5666017 100644 --- a/common/yaml/yaml_test.go +++ b/common/yaml/yaml_test.go @@ -38,7 +38,7 @@ func TestUnmarshalYMLConfig(t *testing.T) { assert.Equal(t, "childStrTest", c.ChildConfig.StrTest) } -func TestUnmarshalYMLConfig_Error(t *testing.T) { +func TestUnmarshalYMLConfigError(t *testing.T) { c := &Config{} _, err := UnmarshalYMLConfig("./testdata/config", c) assert.Error(t, err) diff --git a/config/base_config.go b/config/base_config.go index 46ff5fb174b9204b00c7d7a0369615ca377fd2d4..0ba5bc7ef98cb30a13890b93a659c467adcbf73b 100644 --- a/config/base_config.go +++ b/config/base_config.go @@ -144,20 +144,20 @@ func getKeyPrefix(val reflect.Value) []string { var ( prefix string ) - + configPrefixMethod := "Prefix" if val.CanAddr() { - prefix = val.Addr().MethodByName("Prefix").Call(nil)[0].String() + prefix = val.Addr().MethodByName(configPrefixMethod).Call(nil)[0].String() } else { - prefix = val.MethodByName("Prefix").Call(nil)[0].String() + prefix = val.MethodByName(configPrefixMethod).Call(nil)[0].String() } - var retPrefixs []string + var retPrefixes []string for _, pfx := range strings.Split(prefix, "|") { - retPrefixs = append(retPrefixs, pfx) + retPrefixes = append(retPrefixes, pfx) } - return retPrefixs + return retPrefixes } @@ -184,13 +184,13 @@ func setFieldValue(val reflect.Value, id reflect.Value, config *config.InmemoryC idStr string ) - prefixs := getKeyPrefix(val) + prefixes := getKeyPrefix(val) if id.Kind() == reflect.String { idStr = id.Interface().(string) } - for _, pfx := range prefixs { + for _, pfx := range prefixes { if len(pfx) > 0 { if len(idStr) > 0 { @@ -210,18 +210,20 @@ func setFieldValue(val reflect.Value, id reflect.Value, config *config.InmemoryC } if ok { + errMsg := func(structName string, fieldName string, errorDetails error) { + logger.Errorf("Dynamic change the configuration in struct {%v} field {%v} error ,error message is {%v}", + structName, fieldName, errorDetails) + } switch f.Kind() { case reflect.Int64: x, err := strconv.Atoi(value) if err != nil { - logger.Errorf("Dynamic change the configuration in struct {%v} field {%v} error ,error message is {%v}", - val.Type().Name(), val.Type().Field(i).Name, err) + errMsg(val.Type().Name(), val.Type().Field(i).Name, err) } else { if !f.OverflowInt(int64(x)) { f.SetInt(int64(x)) } else { - logger.Errorf("Dynamic change the configuration in struct {%v} field {%v} error ,error message is {%v}", - val.Type().Name(), val.Type().Field(i).Name, perrors.Errorf("the int64 value {%v} from config center is overflow", int64(x))) + errMsg(val.Type().Name(), val.Type().Field(i).Name, perrors.Errorf("the int64 value {%v} from config center is overflow", int64(x))) } } case reflect.String: @@ -229,21 +231,18 @@ func setFieldValue(val reflect.Value, id reflect.Value, config *config.InmemoryC case reflect.Bool: x, err := strconv.ParseBool(value) if err != nil { - logger.Errorf("Dynamic change the configuration in struct {%v} field {%v} error ,error message is {%v}", - val.Type().Name(), val.Type().Field(i).Name, err) + errMsg(val.Type().Name(), val.Type().Field(i).Name, err) } f.SetBool(x) case reflect.Float64: x, err := strconv.ParseFloat(value, 64) if err != nil { - logger.Errorf("Dynamic change the configuration in struct {%v} field {%v} error ,error message is {%v}", - val.Type().Name(), val.Type().Field(i).Name, err) + errMsg(val.Type().Name(), val.Type().Field(i).Name, err) } else { if !f.OverflowFloat(x) { f.SetFloat(x) } else { - logger.Errorf("Dynamic change the configuration in struct {%v} field {%v} error ,error message is {%v}", - val.Type().Name(), val.Type().Field(i).Name, perrors.Errorf("the float64 value {%v} from config center is overflow", x)) + errMsg(val.Type().Name(), val.Type().Field(i).Name, perrors.Errorf("the float64 value {%v} from config center is overflow", x)) } } default: @@ -348,38 +347,40 @@ func (c *BaseConfig) SetFatherConfig(fatherConfig interface{}) { } func initializeStruct(t reflect.Type, v reflect.Value) { - if v.Kind() == reflect.Struct { - for i := 0; i < v.NumField(); i++ { - f := v.Field(i) - ft := t.Field(i) - - if ft.Tag.Get("property") != "" { - switch ft.Type.Kind() { - case reflect.Map: - if f.IsNil() { - f.Set(reflect.MakeMap(ft.Type)) - } - case reflect.Slice: - if f.IsNil() { - f.Set(reflect.MakeSlice(ft.Type, 0, 0)) - } - case reflect.Chan: - if f.IsNil() { - f.Set(reflect.MakeChan(ft.Type, 0)) - } - case reflect.Struct: - if f.IsNil() { - initializeStruct(ft.Type, f) - } - case reflect.Ptr: - if f.IsNil() { - fv := reflect.New(ft.Type.Elem()) - initializeStruct(ft.Type.Elem(), fv.Elem()) - f.Set(fv) - } - default: - } + if v.Kind() != reflect.Struct { + return + } + for i := 0; i < v.NumField(); i++ { + f := v.Field(i) + ft := t.Field(i) + + if ft.Tag.Get("property") == "" { + continue + } + switch ft.Type.Kind() { + case reflect.Map: + if f.IsNil() { + f.Set(reflect.MakeMap(ft.Type)) + } + case reflect.Slice: + if f.IsNil() { + f.Set(reflect.MakeSlice(ft.Type, 0, 0)) + } + case reflect.Chan: + if f.IsNil() { + f.Set(reflect.MakeChan(ft.Type, 0)) + } + case reflect.Struct: + if f.IsNil() { + initializeStruct(ft.Type, f) + } + case reflect.Ptr: + if f.IsNil() { + fv := reflect.New(ft.Type.Elem()) + initializeStruct(ft.Type.Elem(), fv.Elem()) + f.Set(fv) } + default: } } } diff --git a/config/base_config_test.go b/config/base_config_test.go index ea53ca5208cd0fdee4ab2fb22f5c895a524381aa..7fa895ad497bace41f3112d83ace22d80c7fc8c4 100644 --- a/config/base_config_test.go +++ b/config/base_config_test.go @@ -33,84 +33,95 @@ import ( _ "github.com/apache/dubbo-go/config_center/apollo" ) -func Test_refresh(t *testing.T) { - c := &BaseConfig{} - mockMap := map[string]string{} - mockMap["dubbo.registries.shanghai_reg1.protocol"] = "mock100" - mockMap["dubbo.reference.com.MockService.MockService.retries"] = "10" - mockMap["dubbo.com.MockService.MockService.GetUser.retries"] = "10" - mockMap["dubbo.consumer.check"] = "false" - mockMap["dubbo.application.name"] = "dubbo" - mockMap["dubbo.shutdown.timeout"] = "12s" +func getMockMap() map[string]string { + baseMockMap := map[string]string{ + "dubbo.registries.shanghai_reg1.protocol": "mock100", + "dubbo.reference.com.MockService.MockService.retries": "10", + "dubbo.com.MockService.MockService.GetUser.retries": "10", + "dubbo.consumer.check": "false", + "dubbo.application.name": "dubbo", + } + return baseMockMap +} - config.GetEnvInstance().UpdateExternalConfigMap(mockMap) +var baseAppConfig = &ApplicationConfig{ + Organization: "dubbo_org", + Name: "dubbo", + Module: "module", + Version: "2.6.0", + Owner: "dubbo", + Environment: "test", +} - father := &ConsumerConfig{ - Check: &[]bool{true}[0], - BaseConfig: BaseConfig{ - ApplicationConfig: &ApplicationConfig{ - Organization: "dubbo_org", - Name: "dubbo", - Module: "module", - Version: "2.6.0", - Owner: "dubbo", - Environment: "test"}, - }, +var baseRegistries = map[string]*RegistryConfig{ + "shanghai_reg2": { + Protocol: "mock", + TimeoutStr: "2s", + Group: "shanghai_idc", + Address: "127.0.0.2:2181", + Username: "user1", + Password: "pwd1", + }, + "hangzhou_reg1": { + Protocol: "mock", + TimeoutStr: "2s", + Group: "hangzhou_idc", + Address: "127.0.0.3:2181", + Username: "user1", + Password: "pwd1", + }, + "hangzhou_reg2": { + Protocol: "mock", + TimeoutStr: "2s", + Group: "hangzhou_idc", + Address: "127.0.0.4:2181", + Username: "user1", + Password: "pwd1", + }, +} - Registries: map[string]*RegistryConfig{ - "shanghai_reg2": { - Protocol: "mock", - TimeoutStr: "2s", - Group: "shanghai_idc", - Address: "127.0.0.2:2181", - Username: "user1", - Password: "pwd1", - }, - "hangzhou_reg1": { - Protocol: "mock", - TimeoutStr: "2s", - Group: "hangzhou_idc", - Address: "127.0.0.3:2181", - Username: "user1", - Password: "pwd1", - }, - "hangzhou_reg2": { - Protocol: "mock", - TimeoutStr: "2s", - Group: "hangzhou_idc", - Address: "127.0.0.4:2181", - Username: "user1", - Password: "pwd1", +var baseMockRef = map[string]*ReferenceConfig{ + "MockService": { + InterfaceName: "com.MockService", + Protocol: "mock", + Cluster: "failover", + Loadbalance: "random", + Retries: "3", + Group: "huadong_idc", + Version: "1.0.0", + Methods: []*MethodConfig{ + { + InterfaceId: "MockService", + InterfaceName: "com.MockService", + Name: "GetUser", + Retries: "2", + Loadbalance: "random", }, - }, - - References: map[string]*ReferenceConfig{ - "MockService": { + { + InterfaceId: "MockService", InterfaceName: "com.MockService", - Protocol: "mock", - Cluster: "failover", + Name: "GetUser1", + Retries: "2", Loadbalance: "random", - Retries: "3", - Group: "huadong_idc", - Version: "1.0.0", - Methods: []*MethodConfig{ - { - InterfaceId: "MockService", - InterfaceName: "com.MockService", - Name: "GetUser", - Retries: "2", - Loadbalance: "random", - }, - { - InterfaceId: "MockService", - InterfaceName: "com.MockService", - Name: "GetUser1", - Retries: "2", - Loadbalance: "random", - }, - }, }, }, + }, +} + +func TestRefresh(t *testing.T) { + c := &BaseConfig{} + mockMap := getMockMap() + mockMap["dubbo.shutdown.timeout"] = "12s" + + config.GetEnvInstance().UpdateExternalConfigMap(mockMap) + + father := &ConsumerConfig{ + Check: &[]bool{true}[0], + BaseConfig: BaseConfig{ + ApplicationConfig:baseAppConfig, + }, + Registries: baseRegistries, + References: baseMockRef, ShutdownConfig: &ShutdownConfig{ Timeout: "12s", StepTimeout: "2s", @@ -130,84 +141,21 @@ func Test_refresh(t *testing.T) { assert.Equal(t, "dubbo", father.ApplicationConfig.Name) } -func Test_appExternal_refresh(t *testing.T) { +func TestAppExternalRefresh(t *testing.T) { c := &BaseConfig{} - mockMap := map[string]string{} - mockMap["dubbo.registries.shanghai_reg1.protocol"] = "mock100" - mockMap["dubbo.reference.com.MockService.MockService.retries"] = "10" + mockMap := getMockMap() mockMap["dubbo.reference.com.MockService.retries"] = "5" - mockMap["dubbo.com.MockService.MockService.GetUser.retries"] = "10" - mockMap["dubbo.consumer.check"] = "false" - mockMap["dubbo.application.name"] = "dubbo" config.GetEnvInstance().UpdateAppExternalConfigMap(mockMap) mockMap["dubbo.consumer.check"] = "true" config.GetEnvInstance().UpdateExternalConfigMap(mockMap) father := &ConsumerConfig{ - Check: &[]bool{true}[0], + Check: &[]bool{true}[0], BaseConfig: BaseConfig{ - ApplicationConfig: &ApplicationConfig{ - Organization: "dubbo_org", - Name: "dubbo", - Module: "module", - Version: "2.6.0", - Owner: "dubbo", - Environment: "test"}, - }, - - Registries: map[string]*RegistryConfig{ - "shanghai_reg2": { - Protocol: "mock", - TimeoutStr: "2s", - Group: "shanghai_idc", - Address: "127.0.0.2:2181", - Username: "user1", - Password: "pwd1", - }, - "hangzhou_reg1": { - Protocol: "mock", - TimeoutStr: "2s", - Group: "hangzhou_idc", - Address: "127.0.0.3:2181", - Username: "user1", - Password: "pwd1", - }, - "hangzhou_reg2": { - Protocol: "mock", - TimeoutStr: "2s", - Group: "hangzhou_idc", - Address: "127.0.0.4:2181", - Username: "user1", - Password: "pwd1", - }, - }, - References: map[string]*ReferenceConfig{ - "MockService": { - InterfaceName: "com.MockService", - Protocol: "mock", - Cluster: "failover", - Loadbalance: "random", - Retries: "3", - Group: "huadong_idc", - Version: "1.0.0", - Methods: []*MethodConfig{ - { - InterfaceId: "MockService", - InterfaceName: "com.MockService", - Name: "GetUser", - Retries: "2", - Loadbalance: "random", - }, - { - InterfaceId: "MockService", - InterfaceName: "com.MockService", - Name: "GetUser1", - Retries: "2", - Loadbalance: "random", - }, - }, - }, + ApplicationConfig:baseAppConfig, }, + Registries: baseRegistries, + References: baseMockRef, } c.SetFatherConfig(father) @@ -220,84 +168,22 @@ func Test_appExternal_refresh(t *testing.T) { assert.Equal(t, "dubbo", father.ApplicationConfig.Name) } -func Test_appExternalWithoutId_refresh(t *testing.T) { +func TestAppExternalWithoutIDRefresh(t *testing.T) { c := &BaseConfig{} - mockMap := map[string]string{} - mockMap["dubbo.registries.shanghai_reg1.protocol"] = "mock100" + mockMap := getMockMap() + delete(mockMap, "dubbo.reference.com.MockService.MockService.retries") mockMap["dubbo.reference.com.MockService.retries"] = "10" - mockMap["dubbo.com.MockService.MockService.GetUser.retries"] = "10" - mockMap["dubbo.consumer.check"] = "false" - mockMap["dubbo.application.name"] = "dubbo" config.GetEnvInstance().UpdateAppExternalConfigMap(mockMap) mockMap["dubbo.consumer.check"] = "true" config.GetEnvInstance().UpdateExternalConfigMap(mockMap) father := &ConsumerConfig{ - Check: &[]bool{true}[0], + Check: &[]bool{true}[0], BaseConfig: BaseConfig{ - ApplicationConfig: &ApplicationConfig{ - Organization: "dubbo_org", - Name: "dubbo", - Module: "module", - Version: "2.6.0", - Owner: "dubbo", - Environment: "test"}, - }, - - Registries: map[string]*RegistryConfig{ - "shanghai_reg2": { - Protocol: "mock", - TimeoutStr: "2s", - Group: "shanghai_idc", - Address: "127.0.0.2:2181", - Username: "user1", - Password: "pwd1", - }, - "hangzhou_reg1": { - Protocol: "mock", - TimeoutStr: "2s", - Group: "hangzhou_idc", - Address: "127.0.0.3:2181", - Username: "user1", - Password: "pwd1", - }, - "hangzhou_reg2": { - Protocol: "mock", - TimeoutStr: "2s", - Group: "hangzhou_idc", - Address: "127.0.0.4:2181", - Username: "user1", - Password: "pwd1", - }, - }, - - References: map[string]*ReferenceConfig{ - "MockService": { - InterfaceName: "com.MockService", - Protocol: "mock", - Cluster: "failover", - Loadbalance: "random", - Retries: "3", - Group: "huadong_idc", - Version: "1.0.0", - Methods: []*MethodConfig{ - { - InterfaceId: "MockService", - InterfaceName: "com.MockService", - Name: "GetUser", - Retries: "3", - Loadbalance: "random", - }, - { - InterfaceId: "MockService", - InterfaceName: "com.MockService", - Name: "GetUser1", - Retries: "2", - Loadbalance: "random", - }, - }, - }, + ApplicationConfig:baseAppConfig, }, + Registries: baseRegistries, + References: baseMockRef, } c.SetFatherConfig(father) @@ -310,7 +196,7 @@ func Test_appExternalWithoutId_refresh(t *testing.T) { assert.Equal(t, "dubbo", father.ApplicationConfig.Name) } -func Test_refresh_singleRegistry(t *testing.T) { +func TestRefreshSingleRegistry(t *testing.T) { c := &BaseConfig{} mockMap := map[string]string{} mockMap["dubbo.registry.address"] = "mock100://127.0.0.1:2181" @@ -322,48 +208,13 @@ func Test_refresh_singleRegistry(t *testing.T) { config.GetEnvInstance().UpdateExternalConfigMap(mockMap) father := &ConsumerConfig{ - Check: &[]bool{true}[0], + Check: &[]bool{true}[0], BaseConfig: BaseConfig{ - - ApplicationConfig: &ApplicationConfig{ - Organization: "dubbo_org", - Name: "dubbo", - Module: "module", - Version: "2.6.0", - Owner: "dubbo", - Environment: "test"}, - }, - - Registries: map[string]*RegistryConfig{}, - Registry: &RegistryConfig{}, - - References: map[string]*ReferenceConfig{ - "MockService": { - InterfaceName: "com.MockService", - Protocol: "mock", - Cluster: "failover", - Loadbalance: "random", - Retries: "3", - Group: "huadong_idc", - Version: "1.0.0", - Methods: []*MethodConfig{ - { - InterfaceId: "MockService", - InterfaceName: "com.MockService", - Name: "GetUser", - Retries: "2", - Loadbalance: "random", - }, - { - InterfaceId: "MockService", - InterfaceName: "com.MockService", - Name: "GetUser1", - Retries: "2", - Loadbalance: "random", - }, - }, - }, + ApplicationConfig: baseAppConfig, }, + Registries: map[string]*RegistryConfig{}, + Registry: &RegistryConfig{}, + References: baseMockRef, } c.SetFatherConfig(father) @@ -376,14 +227,11 @@ func Test_refresh_singleRegistry(t *testing.T) { assert.Equal(t, "dubbo", father.ApplicationConfig.Name) } -func Test_refreshProvider(t *testing.T) { +func TestRefreshProvider(t *testing.T) { c := &BaseConfig{} - mockMap := map[string]string{} - mockMap["dubbo.registries.shanghai_reg1.protocol"] = "mock100" + mockMap := getMockMap() + delete(mockMap, "dubbo.reference.com.MockService.MockService.retries") mockMap["dubbo.service.com.MockService.MockService.retries"] = "10" - mockMap["dubbo.com.MockService.MockService.GetUser.retries"] = "10" - mockMap["dubbo.consumer.check"] = "false" - mockMap["dubbo.application.name"] = "dubbo" mockMap["dubbo.protocols.jsonrpc1.name"] = "jsonrpc" mockMap["dubbo.protocols.jsonrpc1.ip"] = "127.0.0.1" mockMap["dubbo.protocols.jsonrpc1.port"] = "20001" @@ -392,42 +240,9 @@ func Test_refreshProvider(t *testing.T) { father := &ProviderConfig{ BaseConfig: BaseConfig{ - ApplicationConfig: &ApplicationConfig{ - Organization: "dubbo_org", - Name: "dubbo", - Module: "module", - Version: "2.6.0", - Owner: "dubbo", - Environment: "test"}, - }, - - Registries: map[string]*RegistryConfig{ - "shanghai_reg2": { - Protocol: "mock", - TimeoutStr: "2s", - Group: "shanghai_idc", - Address: "127.0.0.2:2181", - Username: "user1", - Password: "pwd1", - }, - "hangzhou_reg1": { - Protocol: "mock", - TimeoutStr: "2s", - Group: "hangzhou_idc", - Address: "127.0.0.3:2181", - Username: "user1", - Password: "pwd1", - }, - "hangzhou_reg2": { - Protocol: "mock", - TimeoutStr: "2s", - Group: "hangzhou_idc", - Address: "127.0.0.4:2181", - Username: "user1", - Password: "pwd1", - }, + ApplicationConfig: baseAppConfig, }, - + Registries: baseRegistries, Services: map[string]*ServiceConfig{ "MockService": { InterfaceName: "com.MockService", @@ -445,7 +260,8 @@ func Test_refreshProvider(t *testing.T) { Retries: "2", Loadbalance: "random", }, - {InterfaceId: "MockService", + { + InterfaceId: "MockService", InterfaceName: "com.MockService", Name: "GetUser1", Retries: "2", @@ -466,7 +282,7 @@ func Test_refreshProvider(t *testing.T) { assert.Equal(t, "20001", father.Protocols["jsonrpc1"].Port) } -func Test_startConfigCenter(t *testing.T) { +func TestStartConfigCenter(t *testing.T) { extension.SetConfigCenterFactory("mock", func() config_center.DynamicConfigurationFactory { return &config_center.MockDynamicConfigurationFactory{} }) @@ -483,7 +299,7 @@ func Test_startConfigCenter(t *testing.T) { assert.Equal(t, "ikurento.com", v) } -func Test_initializeStruct(t *testing.T) { +func TestInitializeStruct(t *testing.T) { testConsumerConfig := &ConsumerConfig{} tp := reflect.TypeOf(ConsumerConfig{}) v := reflect.New(tp) diff --git a/config/config_loader.go b/config/config_loader.go index 89a32771dc09c963ba2270eb9b42eba61c815036..d5f8c68c1bf35c40c09d7d15bae4b6b9f161e9e7 100644 --- a/config/config_loader.go +++ b/config/config_loader.go @@ -104,7 +104,7 @@ func loadConsumerConfig() { // init other consumer config conConfigType := consumerConfig.ConfigType for key, value := range extension.GetDefaultConfigReader() { - if conConfigType == nil { + if conConfigType != nil { if v, ok := conConfigType[key]; ok { value = v } diff --git a/config/config_loader_test.go b/config/config_loader_test.go index a239621dd0e43fb940e6e94ea87df62b9123cd26..2cbf526a70b52f184f500bad98edb01b97d239ec 100644 --- a/config/config_loader_test.go +++ b/config/config_loader_test.go @@ -37,10 +37,13 @@ import ( "github.com/apache/dubbo-go/config_center" ) +const mockConsumerConfigPath = "./testdata/consumer_config.yml" +const mockProviderConfigPath = "./testdata/provider_config.yml" + func TestConfigLoader(t *testing.T) { - conPath, err := filepath.Abs("./testdata/consumer_config.yml") + conPath, err := filepath.Abs(mockConsumerConfigPath) assert.NoError(t, err) - proPath, err := filepath.Abs("./testdata/provider_config.yml") + proPath, err := filepath.Abs(mockProviderConfigPath) assert.NoError(t, err) assert.Nil(t, consumerConfig) @@ -153,7 +156,7 @@ func TestConfigLoaderWithConfigCenter(t *testing.T) { conPath, err := filepath.Abs("./testdata/consumer_config_with_configcenter.yml") assert.NoError(t, err) - proPath, err := filepath.Abs("./testdata/provider_config.yml") + proPath, err := filepath.Abs(mockProviderConfigPath) assert.NoError(t, err) assert.Nil(t, consumerConfig) @@ -206,7 +209,7 @@ func TestConfigLoaderWithConfigCenterSingleRegistry(t *testing.T) { conPath, err := filepath.Abs("./testdata/consumer_config_with_configcenter.yml") assert.NoError(t, err) - proPath, err := filepath.Abs("./testdata/provider_config.yml") + proPath, err := filepath.Abs(mockProviderConfigPath) assert.NoError(t, err) assert.Nil(t, consumerConfig) diff --git a/config/config_utils.go b/config/config_utils.go index 6bc574a546ebad548aaa15ce7dc9bcf68b95c3a1..5759ff34f6e5673c4a6de8af3b4e1a34a2e7af4c 100644 --- a/config/config_utils.go +++ b/config/config_utils.go @@ -18,6 +18,7 @@ package config import ( + "fmt" "regexp" "strings" ) @@ -30,50 +31,35 @@ func mergeValue(str1, str2, def string) string { if str1 == "" && str2 == "" { return def } - str := "," + strings.Trim(str1, ",") - if str1 == "" { - str = "," + strings.Trim(str2, ",") - } else if str2 != "" { - str = str + "," + strings.Trim(str2, ",") - } + s1 := strings.Split(str1, ",") + s2 := strings.Split(str2, ",") + str := "," + strings.Join(append(s1, s2...), ",") defKey := strings.Contains(str, ","+constant.DEFAULT_KEY) if !defKey { str = "," + constant.DEFAULT_KEY + str } str = strings.TrimPrefix(strings.Replace(str, ","+constant.DEFAULT_KEY, ","+def, -1), ",") + return removeMinus(strings.Split(str, ",")) +} - strArr := strings.Split(str, ",") - strMap := make(map[string][]int) - for k, v := range strArr { - add := true +func removeMinus(strArr []string) string { + if len(strArr) == 0 { + return "" + } + var normalStr string + var minusStrArr []string + for _, v := range strArr { if strings.HasPrefix(v, "-") { - v = v[1:] - add = false - } - if _, ok := strMap[v]; !ok { - if add { - strMap[v] = []int{1, k} - } + minusStrArr = append(minusStrArr, v[1:]) } else { - if add { - strMap[v][0] += 1 - strMap[v] = append(strMap[v], k) - } else { - strMap[v][0] -= 1 - strMap[v] = strMap[v][:len(strMap[v])-1] - } + normalStr += fmt.Sprintf(",%s", v) } } - strArr = make([]string, len(strArr)) - for key, value := range strMap { - if value[0] == 0 { - continue - } - for i := 1; i < len(value); i++ { - strArr[value[i]] = key - } + normalStr = strings.Trim(normalStr, ",") + for _, v := range minusStrArr { + normalStr = strings.Replace(normalStr, v, "", 1) } reg := regexp.MustCompile("[,]+") - str = reg.ReplaceAllString(strings.Join(strArr, ","), ",") - return strings.Trim(str, ",") + normalStr = reg.ReplaceAllString(strings.Trim(normalStr, ","), ",") + return normalStr } diff --git a/config/config_utils_test.go b/config/config_utils_test.go index 5170b90c83a0f31bbbe1b5de5bca9b8dc5869ac6..81fc3a3721d5915ec3652e03f80ec203e170d1fa 100644 --- a/config/config_utils_test.go +++ b/config/config_utils_test.go @@ -41,3 +41,23 @@ func TestMergeValue(t *testing.T) { str = mergeValue("", "default,-b,e,f", "a,b") assert.Equal(t, "a,e,f", str) } + +func TestRemoveMinus(t *testing.T) { + strList := removeMinus([]string{}) + assert.Equal(t, strList, "") + + strList = removeMinus([]string{"a", "b", "c", "d", "-a"}) + assert.Equal(t, strList, "b,c,d") + + strList = removeMinus([]string{"a", "b", "c", "d", "-a", "-b"}) + assert.Equal(t, strList, "c,d") + + strList = removeMinus([]string{"a", "b", "c", "-c", "-a", "-b"}) + assert.Equal(t, strList, "") + + strList = removeMinus([]string{"b", "a", "-c", "c"}) + assert.Equal(t, strList, "b,a") + + strList = removeMinus([]string{"c", "b", "a", "d", "c", "-c", "-a", "e", "f"}) + assert.Equal(t, strList, "b,d,c,e,f") +} diff --git a/config/graceful_shutdown_config_test.go b/config/graceful_shutdown_config_test.go index 583ed70b838a8271a47e180ee3c6eb32cbb46984..80eb5317386f4e9d966f7a9f07635a810727d77c 100644 --- a/config/graceful_shutdown_config_test.go +++ b/config/graceful_shutdown_config_test.go @@ -26,7 +26,7 @@ import ( "github.com/stretchr/testify/assert" ) -func TestShutdownConfig_GetTimeout(t *testing.T) { +func TestShutdownConfigGetTimeout(t *testing.T) { config := ShutdownConfig{} assert.False(t, config.RejectRequest) assert.False(t, config.RequestsFinished) diff --git a/config/reference_config_test.go b/config/reference_config_test.go index 05b386f75e2b1fc062783e1de224a49329fda1fb..3fbf8da44ca7d00e335260cf107e99dae3a2fa8a 100644 --- a/config/reference_config_test.go +++ b/config/reference_config_test.go @@ -127,6 +127,7 @@ func (m *MockProvider) Reference() string { } func (m *MockProvider) CallBack(res common.CallbackResponse) { + // CallBack is a mock function. to implement the interface } func doInitConsumerAsync() { @@ -186,7 +187,7 @@ func doInitConsumerWithSingleRegistry() { } } -func Test_ReferMultireg(t *testing.T) { +func TestReferMultireg(t *testing.T) { doInitConsumer() extension.SetProtocol("registry", GetProtocol) extension.SetCluster("registryAware", cluster_impl.NewRegistryAwareCluster) @@ -199,7 +200,7 @@ func Test_ReferMultireg(t *testing.T) { consumerConfig = nil } -func Test_Refer(t *testing.T) { +func TestRefer(t *testing.T) { doInitConsumer() extension.SetProtocol("registry", GetProtocol) extension.SetCluster("registryAware", cluster_impl.NewRegistryAwareCluster) @@ -213,7 +214,7 @@ func Test_Refer(t *testing.T) { consumerConfig = nil } -func Test_ReferAsync(t *testing.T) { +func TestReferAsync(t *testing.T) { doInitConsumerAsync() extension.SetProtocol("registry", GetProtocol) extension.SetCluster("registryAware", cluster_impl.NewRegistryAwareCluster) @@ -228,7 +229,7 @@ func Test_ReferAsync(t *testing.T) { consumerConfig = nil } -func Test_ReferP2P(t *testing.T) { +func TestReferP2P(t *testing.T) { doInitConsumer() extension.SetProtocol("dubbo", GetProtocol) m := consumerConfig.References["MockService"] @@ -242,7 +243,7 @@ func Test_ReferP2P(t *testing.T) { consumerConfig = nil } -func Test_ReferMultiP2P(t *testing.T) { +func TestReferMultiP2P(t *testing.T) { doInitConsumer() extension.SetProtocol("dubbo", GetProtocol) m := consumerConfig.References["MockService"] @@ -256,7 +257,7 @@ func Test_ReferMultiP2P(t *testing.T) { consumerConfig = nil } -func Test_ReferMultiP2PWithReg(t *testing.T) { +func TestReferMultiP2PWithReg(t *testing.T) { doInitConsumer() extension.SetProtocol("dubbo", GetProtocol) extension.SetProtocol("registry", GetProtocol) @@ -271,7 +272,7 @@ func Test_ReferMultiP2PWithReg(t *testing.T) { consumerConfig = nil } -func Test_Implement(t *testing.T) { +func TestImplement(t *testing.T) { doInitConsumer() extension.SetProtocol("registry", GetProtocol) extension.SetCluster("registryAware", cluster_impl.NewRegistryAwareCluster) @@ -284,7 +285,7 @@ func Test_Implement(t *testing.T) { consumerConfig = nil } -func Test_Forking(t *testing.T) { +func TestForking(t *testing.T) { doInitConsumer() extension.SetProtocol("dubbo", GetProtocol) extension.SetProtocol("registry", GetProtocol) @@ -301,7 +302,7 @@ func Test_Forking(t *testing.T) { consumerConfig = nil } -func Test_Sticky(t *testing.T) { +func TestSticky(t *testing.T) { doInitConsumer() extension.SetProtocol("dubbo", GetProtocol) extension.SetProtocol("registry", GetProtocol) @@ -340,4 +341,6 @@ func (*mockRegistryProtocol) Export(invoker protocol.Invoker) protocol.Exporter return protocol.NewBaseExporter("test", invoker, &sync.Map{}) } -func (*mockRegistryProtocol) Destroy() {} +func (*mockRegistryProtocol) Destroy() { + // Destroy is a mock function +} diff --git a/config/registry_config_test.go b/config/registry_config_test.go index 6c2fed605d6c50b483f7ad2900e5a483b3986e1b..6e5dedc34ff5489fc190841bce73cd015eb78132 100644 --- a/config/registry_config_test.go +++ b/config/registry_config_test.go @@ -29,7 +29,7 @@ import ( "github.com/apache/dubbo-go/common" ) -func Test_loadRegistries(t *testing.T) { +func TestLoadRegistries(t *testing.T) { target := "shanghai1" regs := map[string]*RegistryConfig{ @@ -47,7 +47,7 @@ func Test_loadRegistries(t *testing.T) { assert.Equal(t, "127.0.0.2:2181,128.0.0.1:2181", urls[0].Location) } -func Test_loadRegistries1(t *testing.T) { +func TestLoadRegistries1(t *testing.T) { target := "shanghai1" regs := map[string]*RegistryConfig{ diff --git a/config/service_config_test.go b/config/service_config_test.go index 7630d5845e6770ec269bb2e07876bc7ba0d18329..e7d55077beb56b0ccf8da833f5aeebfac07a9e3f 100644 --- a/config/service_config_test.go +++ b/config/service_config_test.go @@ -140,7 +140,7 @@ func doInitProvider() { } } -func Test_Export(t *testing.T) { +func TestExport(t *testing.T) { doInitProvider() extension.SetProtocol("registry", GetProtocol) @@ -153,7 +153,7 @@ func Test_Export(t *testing.T) { providerConfig = nil } -func Test_getRandomPort(t *testing.T) { +func TestgetRandomPort(t *testing.T) { protocolConfigs := make([]*ProtocolConfig, 0, 3) ip, err := gxnet.GetLocalIP() diff --git a/config_center/apollo/impl_test.go b/config_center/apollo/impl_test.go index a95524b41b887313993aad4e774ed6d96b24c08f..335fb71045ca6349557cf7c736cead0565bdc193 100644 --- a/config_center/apollo/impl_test.go +++ b/config_center/apollo/impl_test.go @@ -125,7 +125,7 @@ func initApollo() *httptest.Server { return runMockConfigServer(handlerMap, notifyResponse) } -func configResponse(rw http.ResponseWriter, req *http.Request) { +func configResponse(rw http.ResponseWriter, _ *http.Request) { result := fmt.Sprintf(mockConfigRes) fmt.Fprintf(rw, "%s", result) } @@ -135,7 +135,7 @@ func notifyResponse(rw http.ResponseWriter, req *http.Request) { fmt.Fprintf(rw, "%s", result) } -func serviceConfigResponse(rw http.ResponseWriter, req *http.Request) { +func serviceConfigResponse(rw http.ResponseWriter, _ *http.Request) { result := fmt.Sprintf(mockServiceConfigRes) fmt.Fprintf(rw, "%s", result) } @@ -164,7 +164,7 @@ func runMockConfigServer(handlerMap map[string]func(http.ResponseWriter, *http.R return ts } -func Test_GetConfig(t *testing.T) { +func TestGetConfig(t *testing.T) { configuration := initMockApollo(t) configs, err := configuration.GetProperties(mockNamespace, config_center.WithGroup("dubbo")) assert.NoError(t, err) @@ -175,7 +175,7 @@ func Test_GetConfig(t *testing.T) { deleteMockJson(t) } -func Test_GetConfigItem(t *testing.T) { +func TestGetConfigItem(t *testing.T) { configuration := initMockApollo(t) configs, err := configuration.GetInternalProperty("application.organization") assert.NoError(t, err) @@ -238,7 +238,7 @@ func TestRemoveListener(t *testing.T) { apollo.RemoveListener(mockNamespace, listener) assert.Equal(t, "", listener.event) listenerCount := 0 - apollo.listeners.Range(func(key, value interface{}) bool { + apollo.listeners.Range(func(_, value interface{}) bool { apolloListener := value.(*apolloListener) for e := range apolloListener.listeners { fmt.Println(e) diff --git a/config_center/configurator/override.go b/config_center/configurator/override.go index ebd3dc601b2821f3f4e1e4405720e4ebc55b607e..294a60ebb2e4e18cfc47cd90aedeaa615b5626d2 100644 --- a/config_center/configurator/override.go +++ b/config_center/configurator/override.go @@ -72,42 +72,46 @@ func (c *overrideConfigurator) Configure(url *common.URL) { } } +func (c *overrideConfigurator) configureIfMatchInternal(url *common.URL) { + configApp := c.configuratorUrl.GetParam(constant.APPLICATION_KEY, c.configuratorUrl.Username) + currentApp := url.GetParam(constant.APPLICATION_KEY, url.Username) + if len(configApp) == 0 || constant.ANY_VALUE == configApp || configApp == currentApp { + conditionKeys := gxset.NewSet() + conditionKeys.Add(constant.CATEGORY_KEY) + conditionKeys.Add(constant.CHECK_KEY) + conditionKeys.Add(constant.ENABLED_KEY) + conditionKeys.Add(constant.GROUP_KEY) + conditionKeys.Add(constant.VERSION_KEY) + conditionKeys.Add(constant.APPLICATION_KEY) + conditionKeys.Add(constant.SIDE_KEY) + conditionKeys.Add(constant.CONFIG_VERSION_KEY) + conditionKeys.Add(constant.COMPATIBLE_CONFIG_KEY) + returnUrl := false + c.configuratorUrl.RangeParams(func(k, _ string) bool { + value := c.configuratorUrl.GetParam(k, "") + if strings.HasPrefix(k, "~") || k == constant.APPLICATION_KEY || k == constant.SIDE_KEY { + conditionKeys.Add(k) + if len(value) != 0 && value != constant.ANY_VALUE && value != url.GetParam(strings.TrimPrefix(k, "~"), "") { + returnUrl = true + return false + } + } + return true + }) + if returnUrl { + return + } + configUrl := c.configuratorUrl.CloneExceptParams(conditionKeys) + url.SetParams(configUrl.GetParams()) + } +} + // configureIfMatch translate from java, compatible rules in java func (c *overrideConfigurator) configureIfMatch(host string, url *common.URL) { if constant.ANYHOST_VALUE == c.configuratorUrl.Ip || host == c.configuratorUrl.Ip { providers := c.configuratorUrl.GetParam(constant.OVERRIDE_PROVIDERS_KEY, "") if len(providers) == 0 || strings.Index(providers, url.Location) >= 0 || strings.Index(providers, constant.ANYHOST_VALUE) >= 0 { - configApp := c.configuratorUrl.GetParam(constant.APPLICATION_KEY, c.configuratorUrl.Username) - currentApp := url.GetParam(constant.APPLICATION_KEY, url.Username) - if len(configApp) == 0 || constant.ANY_VALUE == configApp || configApp == currentApp { - conditionKeys := gxset.NewSet() - conditionKeys.Add(constant.CATEGORY_KEY) - conditionKeys.Add(constant.CHECK_KEY) - conditionKeys.Add(constant.ENABLED_KEY) - conditionKeys.Add(constant.GROUP_KEY) - conditionKeys.Add(constant.VERSION_KEY) - conditionKeys.Add(constant.APPLICATION_KEY) - conditionKeys.Add(constant.SIDE_KEY) - conditionKeys.Add(constant.CONFIG_VERSION_KEY) - conditionKeys.Add(constant.COMPATIBLE_CONFIG_KEY) - returnUrl := false - c.configuratorUrl.RangeParams(func(k, v string) bool { - value := c.configuratorUrl.GetParam(k, "") - if strings.HasPrefix(k, "~") || k == constant.APPLICATION_KEY || k == constant.SIDE_KEY { - conditionKeys.Add(k) - if len(value) != 0 && value != constant.ANY_VALUE && value != url.GetParam(strings.TrimPrefix(k, "~"), "") { - returnUrl = true - return false - } - } - return true - }) - if returnUrl { - return - } - configUrl := c.configuratorUrl.CloneExceptParams(conditionKeys) - url.SetParams(configUrl.GetParams()) - } + c.configureIfMatchInternal(url) } } } diff --git a/config_center/configurator/override_test.go b/config_center/configurator/override_test.go index c0aeb15130e7862fcb00d6cb82cbef60df777acb..8eccb5091272b033cf31b612dfb19bce6514ccce 100644 --- a/config_center/configurator/override_test.go +++ b/config_center/configurator/override_test.go @@ -30,51 +30,58 @@ import ( "github.com/apache/dubbo-go/common/extension" ) -func Test_configureVerison2p6(t *testing.T) { +const ( + defaults = "default" + override = "override" + failfast = "failfast" + failover = "failover" +) + +func TestConfigureVerison2p6(t *testing.T) { url, err := common.NewURL("override://0.0.0.0:0/com.xxx.mock.userProvider?group=1&version=1&cluster=failfast&application=BDTService") assert.NoError(t, err) - configurator := extension.GetConfigurator("default", &url) - assert.Equal(t, "override", configurator.GetUrl().Protocol) + configurator := extension.GetConfigurator(defaults, &url) + assert.Equal(t, override, configurator.GetUrl().Protocol) providerUrl, err := common.NewURL("jsonrpc://127.0.0.1:20001/com.ikurento.user.UserProvider?anyhost=true&app.version=0.0.1&application=BDTService&category=providers&cluster=failover&dubbo=dubbo-provider-golang-2.6.0&environment=dev&group=&interface=com.ikurento.user.UserProvider&ip=10.32.20.124&loadbalance=random&methods.GetUser.loadbalance=random&methods.GetUser.retries=1&methods.GetUser.weight=0&module=dubbogo+user-info+server&name=BDTService&organization=ikurento.com&owner=ZX&pid=64225&retries=0&service.filter=echo&side=provider×tamp=1562076628&version=&warmup=100") assert.NoError(t, err) configurator.Configure(&providerUrl) - assert.Equal(t, "failfast", providerUrl.GetParam(constant.CLUSTER_KEY, "")) + assert.Equal(t, failfast, providerUrl.GetParam(constant.CLUSTER_KEY, "")) } -func Test_configureVerisonOverrideAddr(t *testing.T) { +func TestConfigureVerisonOverrideAddr(t *testing.T) { url, err := common.NewURL("override://0.0.0.0:0/com.xxx.mock.userProvider?group=1&version=1&cluster=failfast&application=BDTService&providerAddresses=127.0.0.2:20001|127.0.0.3:20001") assert.NoError(t, err) - configurator := extension.GetConfigurator("default", &url) - assert.Equal(t, "override", configurator.GetUrl().Protocol) + configurator := extension.GetConfigurator(defaults, &url) + assert.Equal(t, override, configurator.GetUrl().Protocol) providerUrl, err := common.NewURL("jsonrpc://127.0.0.1:20001/com.ikurento.user.UserProvider?anyhost=true&app.version=0.0.1&application=BDTService&category=providers&cluster=failover&dubbo=dubbo-provider-golang-2.6.0&environment=dev&group=&interface=com.ikurento.user.UserProvider&ip=10.32.20.124&loadbalance=random&methods.GetUser.loadbalance=random&methods.GetUser.retries=1&methods.GetUser.weight=0&module=dubbogo+user-info+server&name=BDTService&organization=ikurento.com&owner=ZX&pid=64225&retries=0&service.filter=echo&side=provider×tamp=1562076628&version=&warmup=100") assert.NoError(t, err) configurator.Configure(&providerUrl) - assert.Equal(t, "failover", providerUrl.GetParam(constant.CLUSTER_KEY, "")) + assert.Equal(t, failover, providerUrl.GetParam(constant.CLUSTER_KEY, "")) } -func Test_configureVerison2p6WithIp(t *testing.T) { +func TestConfigureVerison2p6WithIp(t *testing.T) { url, err := common.NewURL("override://127.0.0.1:20001/com.xxx.mock.userProvider?group=1&version=1&cluster=failfast&application=BDTService") assert.NoError(t, err) - configurator := extension.GetConfigurator("default", &url) - assert.Equal(t, "override", configurator.GetUrl().Protocol) + configurator := extension.GetConfigurator(defaults, &url) + assert.Equal(t, override, configurator.GetUrl().Protocol) providerUrl, err := common.NewURL("jsonrpc://127.0.0.1:20001/com.ikurento.user.UserProvider?anyhost=true&app.version=0.0.1&application=BDTService&category=providers&cluster=failover&dubbo=dubbo-provider-golang-2.6.0&environment=dev&group=&interface=com.ikurento.user.UserProvider&ip=10.32.20.124&loadbalance=random&methods.GetUser.loadbalance=random&methods.GetUser.retries=1&methods.GetUser.weight=0&module=dubbogo+user-info+server&name=BDTService&organization=ikurento.com&owner=ZX&pid=64225&retries=0&service.filter=echo&side=provider×tamp=1562076628&version=&warmup=100") assert.NoError(t, err) configurator.Configure(&providerUrl) - assert.Equal(t, "failfast", providerUrl.GetParam(constant.CLUSTER_KEY, "")) + assert.Equal(t, failfast, providerUrl.GetParam(constant.CLUSTER_KEY, "")) } -func Test_configureVerison2p7(t *testing.T) { +func TestConfigureVerison2p7(t *testing.T) { url, err := common.NewURL("jsonrpc://0.0.0.0:20001/com.xxx.mock.userProvider?group=1&version=1&cluster=failfast&application=BDTService&configVersion=1.0&side=provider") assert.NoError(t, err) - configurator := extension.GetConfigurator("default", &url) + configurator := extension.GetConfigurator(defaults, &url) providerUrl, err := common.NewURL("jsonrpc://127.0.0.1:20001/com.ikurento.user.UserProvider?anyhost=true&app.version=0.0.1&application=BDTService&category=providers&cluster=failover&dubbo=dubbo-provider-golang-2.6.0&environment=dev&group=&interface=com.ikurento.user.UserProvider&ip=10.32.20.124&loadbalance=random&methods.GetUser.loadbalance=random&methods.GetUser.retries=1&methods.GetUser.weight=0&module=dubbogo+user-info+server&name=BDTService&organization=ikurento.com&owner=ZX&pid=64225&retries=0&service.filter=echo&side=provider×tamp=1562076628&version=&warmup=100") assert.NoError(t, err) configurator.Configure(&providerUrl) - assert.Equal(t, "failfast", providerUrl.GetParam(constant.CLUSTER_KEY, "")) + assert.Equal(t, failfast, providerUrl.GetParam(constant.CLUSTER_KEY, "")) } diff --git a/config_center/mock_dynamic_config.go b/config_center/mock_dynamic_config.go index 9cfb9e6078be60fbe2072e8e293143e8b111df58..de208946f1715878c2afc62fdd41df93f74797c7 100644 --- a/config_center/mock_dynamic_config.go +++ b/config_center/mock_dynamic_config.go @@ -38,6 +38,10 @@ type MockDynamicConfigurationFactory struct { Content string } +const ( + mockServiceName = "org.apache.dubbo-go.mockService" +) + var ( once sync.Once dynamicConfiguration *MockDynamicConfiguration @@ -106,6 +110,7 @@ func (c *MockDynamicConfiguration) AddListener(key string, listener Configuratio // RemoveListener removes the listener for MockDynamicConfiguration func (c *MockDynamicConfiguration) RemoveListener(_ string, _ ConfigurationListener, _ ...Option) { + // mock remove } // GetConfig returns content of MockDynamicConfiguration @@ -149,20 +154,20 @@ func (c *MockDynamicConfiguration) MockServiceConfigEvent() { config := &parser.ConfiguratorConfig{ ConfigVersion: "2.7.1", Scope: parser.GeneralType, - Key: "org.apache.dubbo-go.mockService", + Key: mockServiceName, Enabled: true, Configs: []parser.ConfigItem{ {Type: parser.GeneralType, Enabled: true, Addresses: []string{"0.0.0.0"}, - Services: []string{"org.apache.dubbo-go.mockService"}, + Services: []string{mockServiceName}, Side: "provider", Parameters: map[string]string{"cluster": "mock1"}, }, }, } value, _ := yaml.Marshal(config) - key := "group*org.apache.dubbo-go.mockService:1.0.0" + constant.CONFIGURATORS_SUFFIX + key := "group*" + mockServiceName + ":1.0.0" + constant.CONFIGURATORS_SUFFIX c.listener[key].Process(&ConfigChangeEvent{Key: key, Value: string(value), ConfigType: remoting.EventTypeAdd}) } @@ -171,13 +176,13 @@ func (c *MockDynamicConfiguration) MockApplicationConfigEvent() { config := &parser.ConfiguratorConfig{ ConfigVersion: "2.7.1", Scope: parser.ScopeApplication, - Key: "org.apache.dubbo-go.mockService", + Key: mockServiceName, Enabled: true, Configs: []parser.ConfigItem{ {Type: parser.ScopeApplication, Enabled: true, Addresses: []string{"0.0.0.0"}, - Services: []string{"org.apache.dubbo-go.mockService"}, + Services: []string{mockServiceName}, Side: "provider", Parameters: map[string]string{"cluster": "mock1"}, }, diff --git a/config_center/nacos/client_test.go b/config_center/nacos/client_test.go index d5e351e2bbf7d78301926c8394d07183f18bb678..0cc36eb7c1648349047fea795e8bd8fef4bed72d 100644 --- a/config_center/nacos/client_test.go +++ b/config_center/nacos/client_test.go @@ -31,7 +31,7 @@ import ( "github.com/apache/dubbo-go/common" ) -func Test_newNacosClient(t *testing.T) { +func TestNewNacosClient(t *testing.T) { server := mockCommonNacosServer() nacosURL := strings.ReplaceAll(server.URL, "http", "registry") registryUrl, _ := common.NewURL(nacosURL) @@ -54,7 +54,7 @@ func Test_newNacosClient(t *testing.T) { c.Destroy() } -func Test_setNacosClient(t *testing.T) { +func TestSetNacosClient(t *testing.T) { server := mockCommonNacosServer() nacosURL := server.Listener.Addr().String() registryUrl, _ := common.NewURL(nacosURL) @@ -88,7 +88,7 @@ func Test_setNacosClient(t *testing.T) { c.Destroy() } -func Test_newNacosClient_connectError(t *testing.T) { +func TestNewNacosClient_connectError(t *testing.T) { nacosURL := "registry://127.0.0.1:8888" registryUrl, err := common.NewURL(nacosURL) assert.NoError(t, err) diff --git a/config_center/nacos/impl_test.go b/config_center/nacos/impl_test.go index 03fc6772e70d623575575c8522508ae4fff12a04..88d200edc927c62967975dff28e19c03743125f0 100644 --- a/config_center/nacos/impl_test.go +++ b/config_center/nacos/impl_test.go @@ -59,10 +59,10 @@ func runMockConfigServer(configHandler func(http.ResponseWriter, *http.Request), } func mockCommonNacosServer() *httptest.Server { - return runMockConfigServer(func(writer http.ResponseWriter, request *http.Request) { + return runMockConfigServer(func(writer http.ResponseWriter, _ *http.Request) { data := "true" fmt.Fprintf(writer, "%s", data) - }, func(writer http.ResponseWriter, request *http.Request) { + }, func(writer http.ResponseWriter, _ *http.Request) { data := `dubbo.properties%02dubbo%02dubbo.service.com.ikurento.user.UserProvider.cluster=failback` fmt.Fprintf(writer, "%s", data) }) @@ -81,7 +81,7 @@ func initNacosData(t *testing.T) (*nacosDynamicConfiguration, error) { return nacosConfiguration.(*nacosDynamicConfiguration), err } -func Test_GetConfig(t *testing.T) { +func TestGetConfig(t *testing.T) { nacos, err := initNacosData(t) assert.NoError(t, err) configs, err := nacos.GetProperties("dubbo.properties", config_center.WithGroup("dubbo")) @@ -117,7 +117,7 @@ func TestNacosDynamicConfiguration_GetConfigKeysByGroup(t *testing.T) { } -func TestNacosDynamicConfiguration_PublishConfig(t *testing.T) { +func TestNacosDynamicConfigurationPublishConfig(t *testing.T) { nacos, err := initNacosData(t) assert.Nil(t, err) key := "myKey" @@ -127,7 +127,7 @@ func TestNacosDynamicConfiguration_PublishConfig(t *testing.T) { assert.Nil(t, err) } -func Test_AddListener(t *testing.T) { +func TestAddListener(t *testing.T) { nacos, err := initNacosData(t) assert.NoError(t, err) listener := &mockDataListener{} @@ -135,8 +135,8 @@ func Test_AddListener(t *testing.T) { nacos.AddListener("dubbo.properties", listener) } -func Test_RemoveListener(t *testing.T) { - // TODO not supported in current go_nacos_sdk version +func TestRemoveListener(_ *testing.T) { + //TODO not supported in current go_nacos_sdk version } type mockDataListener struct { diff --git a/config_center/nacos/listener.go b/config_center/nacos/listener.go index fdf5a20d2ff4b97c1e0de40c8b5a0e573214fea4..3118a9d0529bf8762dc7ee864af32b044b74fd49 100644 --- a/config_center/nacos/listener.go +++ b/config_center/nacos/listener.go @@ -31,7 +31,7 @@ import ( "github.com/apache/dubbo-go/remoting" ) -func callback(listener config_center.ConfigurationListener, namespace, group, dataId, data string) { +func callback(listener config_center.ConfigurationListener, _, _, dataId, data string) { listener.Process(&config_center.ConfigChangeEvent{Key: dataId, Value: data, ConfigType: remoting.EventTypeUpdate}) } diff --git a/config_center/parser/configuration_parser_test.go b/config_center/parser/configuration_parser_test.go index 3ba10f73a4549181f37b89aedd4aedf4612bd7d4..be2d45b25e835eb6cf6c2cf69afe2d9d69d3f90a 100644 --- a/config_center/parser/configuration_parser_test.go +++ b/config_center/parser/configuration_parser_test.go @@ -25,7 +25,7 @@ import ( "github.com/stretchr/testify/assert" ) -func TestDefaultConfigurationParser_Parser(t *testing.T) { +func TestDefaultConfigurationParserParser(t *testing.T) { parser := &DefaultConfigurationParser{} m, err := parser.Parse("dubbo.registry.address=172.0.0.1\ndubbo.registry.name=test") assert.NoError(t, err) @@ -33,7 +33,7 @@ func TestDefaultConfigurationParser_Parser(t *testing.T) { assert.Equal(t, "172.0.0.1", m["dubbo.registry.address"]) } -func TestDefaultConfigurationParser_appItemToUrls_ParserToUrls(t *testing.T) { +func TestDefaultConfigurationParserAppItemToUrls_ParserToUrls(t *testing.T) { parser := &DefaultConfigurationParser{} content := `configVersion: 2.7.1 scope: application @@ -60,7 +60,7 @@ configs: assert.Equal(t, "0.0.0.0", urls[0].Location) } -func TestDefaultConfigurationParser_serviceItemToUrls_ParserToUrls(t *testing.T) { +func TestDefaultConfigurationParserServiceItemToUrls_ParserToUrls(t *testing.T) { parser := &DefaultConfigurationParser{} content := `configVersion: 2.7.1 scope: notApplication diff --git a/config_center/zookeeper/impl_test.go b/config_center/zookeeper/impl_test.go index cfeba07a87e2534dc60e9ca2235550c1136bd978..ecc3527c486fdd2aa2bc6f4d2f2adab1147e495a 100644 --- a/config_center/zookeeper/impl_test.go +++ b/config_center/zookeeper/impl_test.go @@ -18,6 +18,7 @@ package zookeeper import ( "fmt" + "path" "strconv" "sync" "testing" @@ -36,6 +37,10 @@ import ( "github.com/apache/dubbo-go/config_center/parser" ) +const ( + dubboPropertyFileName = "dubbo.properties" +) + func initZkData(group string, t *testing.T) (*zk.TestCluster, *zookeeperDynamicConfiguration) { ts, err := zk.StartTestCluster(1, nil, nil) assert.NoError(t, err) @@ -76,43 +81,43 @@ func initZkData(group string, t *testing.T) (*zk.TestCluster, *zookeeperDynamicC dubbo.service.com.ikurento.user.UserProvider.cluster=failover ` if group != "" { - err = zreg.client.Create(zreg.rootPath + "/dubbo/dubbo.properties") + err = zreg.client.Create(path.Join(zreg.rootPath, "dubbo", dubboPropertyFileName)) assert.NoError(t, err) - _, err = zreg.client.Conn.Set(zreg.rootPath+"/dubbo/dubbo.properties", []byte(data), 0) + _, err = zreg.client.Conn.Set(path.Join(zreg.rootPath, "dubbo", dubboPropertyFileName), []byte(data), 0) assert.NoError(t, err) } else { - err = zreg.client.Create(zreg.rootPath + "/dubbo.properties") + err = zreg.client.Create(path.Join(zreg.rootPath, dubboPropertyFileName)) assert.NoError(t, err) - _, err = zreg.client.Conn.Set(zreg.rootPath+"/dubbo.properties", []byte(data), 0) + _, err = zreg.client.Conn.Set(path.Join(zreg.rootPath, dubboPropertyFileName), []byte(data), 0) assert.NoError(t, err) } return ts, zreg } -func Test_GetConfig(t *testing.T) { +func TestGetConfig(t *testing.T) { ts, reg := initZkData("dubbo", t) defer ts.Stop() - configs, err := reg.GetProperties("dubbo.properties", config_center.WithGroup("dubbo")) + configs, err := reg.GetProperties(dubboPropertyFileName, config_center.WithGroup("dubbo")) assert.NoError(t, err) m, err := reg.Parser().Parse(configs) assert.NoError(t, err) assert.Equal(t, "5s", m["dubbo.consumer.request_timeout"]) - configs, err = reg.GetProperties("dubbo.properties") + configs, err = reg.GetProperties(dubboPropertyFileName) assert.Error(t, err) - configs, err = reg.GetInternalProperty("dubbo.properties") + configs, err = reg.GetInternalProperty(dubboPropertyFileName) assert.Error(t, err) - configs, err = reg.GetRule("dubbo.properties") + configs, err = reg.GetRule(dubboPropertyFileName) assert.Error(t, err) } -func Test_AddListener(t *testing.T) { +func TestAddListener(t *testing.T) { ts, reg := initZkData("", t) defer ts.Stop() listener := &mockDataListener{} - reg.AddListener("dubbo.properties", listener) + reg.AddListener(dubboPropertyFileName, listener) listener.wg.Add(1) data := ` dubbo.consumer.request_timeout=3s @@ -135,17 +140,17 @@ func Test_AddListener(t *testing.T) { dubbo.service.com.ikurento.user.UserProvider.warmup=100 dubbo.service.com.ikurento.user.UserProvider.cluster=failover ` - _, err := reg.client.Conn.Set(reg.rootPath+"/dubbo.properties", []byte(data), 1) + _, err := reg.client.Conn.Set(path.Join(reg.rootPath, dubboPropertyFileName), []byte(data), 1) assert.NoError(t, err) listener.wg.Wait() - assert.Equal(t, "dubbo.properties", listener.event) + assert.Equal(t, dubboPropertyFileName, listener.event) } -func Test_RemoveListener(t *testing.T) { +func TestRemoveListener(t *testing.T) { ts, reg := initZkData("", t) defer ts.Stop() listener := &mockDataListener{} - reg.AddListener("dubbo.properties", listener) + reg.AddListener(dubboPropertyFileName, listener) listener.wg.Add(1) data := ` dubbo.consumer.request_timeout=3s @@ -168,15 +173,15 @@ func Test_RemoveListener(t *testing.T) { dubbo.service.com.ikurento.user.UserProvider.warmup=100 dubbo.service.com.ikurento.user.UserProvider.cluster=failover ` - reg.RemoveListener("dubbo.properties", listener) + reg.RemoveListener(dubboPropertyFileName, listener) listener.wg.Done() - _, err := reg.client.Conn.Set(reg.rootPath+"/dubbo.properties", []byte(data), 1) + _, err := reg.client.Conn.Set(path.Join(reg.rootPath, dubboPropertyFileName), []byte(data), 1) assert.NoError(t, err) listener.wg.Wait() assert.Equal(t, "", listener.event) } -func TestZookeeperDynamicConfiguration_PublishConfig(t *testing.T) { +func TestZookeeperDynamicConfigurationPublishConfig(t *testing.T) { value := "Test Data" customGroup := "Custom Group" key := "myKey" diff --git a/go.mod b/go.mod index 16335d10bc811f1588ec53f6b11d8a80d57f3c92..9e98e4ef0989e828be13fcb72b7ddd64f05d9df0 100644 --- a/go.mod +++ b/go.mod @@ -3,14 +3,16 @@ module github.com/apache/dubbo-go require ( github.com/Workiva/go-datastructures v1.0.50 github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5 - github.com/apache/dubbo-go-hessian2 v1.5.0 + github.com/aliyun/aliyun-oss-go-sdk v0.0.0-20190307165228-86c17b95fcd5 // indirect + github.com/apache/dubbo-go-hessian2 v1.6.1-0.20200623062814-707fde850279 + github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f // indirect github.com/coreos/bbolt v1.3.3 // indirect github.com/coreos/etcd v3.3.13+incompatible github.com/coreos/go-semver v0.3.0 // indirect github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f // indirect github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f // indirect github.com/creasty/defaults v1.3.0 - github.com/dubbogo/getty v1.3.5 + github.com/dubbogo/getty v1.3.7 github.com/dubbogo/go-zookeeper v1.0.1 github.com/dubbogo/gost v1.9.0 github.com/emicklei/go-restful/v3 v3.0.0 @@ -44,8 +46,9 @@ require ( github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5 // indirect github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2 // indirect github.com/zouyx/agollo v0.0.0-20191114083447-dde9fc9f35b8 - go.uber.org/atomic v1.4.0 - go.uber.org/zap v1.10.0 + go.etcd.io/bbolt v1.3.4 // indirect + go.uber.org/atomic v1.6.0 + go.uber.org/zap v1.15.0 golang.org/x/time v0.0.0-20190308202827-9d24e82272b4 // indirect google.golang.org/grpc v1.22.1 gopkg.in/yaml.v2 v2.2.2 diff --git a/go.sum b/go.sum index 780aab034c780a3d70c705987827ca4b0bf51335..5f35190e4cd1678e871b2a445e23f7289be329cd 100644 --- a/go.sum +++ b/go.sum @@ -35,10 +35,14 @@ github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5 h1:rFw4nCn9iMW+Vaj github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5/go.mod h1:SkGFH1ia65gfNATL8TAiHDNxPzPdmEL5uirI2Uyuz6c= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/aliyun/alibaba-cloud-sdk-go v0.0.0-20190802083043-4cd0c391755e/go.mod h1:myCDvQSzCW+wB1WAlocEru4wMGJxy+vlxHdhegi1CDQ= github.com/aliyun/alibaba-cloud-sdk-go v1.61.18 h1:zOVTBdCKFd9JbCKz9/nt+FovbjPFmb7mUnp8nH9fQBA= github.com/aliyun/alibaba-cloud-sdk-go v1.61.18/go.mod h1:v8ESoHo4SyHmuB4b1tJqDHxfTGEciD+yhvOU/5s1Rfk= +github.com/aliyun/aliyun-oss-go-sdk v0.0.0-20190307165228-86c17b95fcd5/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8= github.com/apache/dubbo-go-hessian2 v1.5.0 h1:fzulDG5G7nX0ccgKdiN9XipJ7tZ4WXKgmk4stdlDS6s= github.com/apache/dubbo-go-hessian2 v1.5.0/go.mod h1:VwEnsOMidkM1usya2uPfGpSLO9XUF//WQcWn3y+jFz8= +github.com/apache/dubbo-go-hessian2 v1.6.1-0.20200623062814-707fde850279 h1:1g3IJdaUjXWs++NA9Ail8+r6WgrkfhjS6hD/YXvRzjk= +github.com/apache/dubbo-go-hessian2 v1.6.1-0.20200623062814-707fde850279/go.mod h1:7rEw9guWABQa6Aqb8HeZcsYPHsOS7XT1qtJvkmI6c5w= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e h1:QEF07wC0T1rKkctt1RINW/+RMTVmiwxETico2l3gxJA= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= @@ -50,6 +54,7 @@ github.com/asaskevich/govalidator v0.0.0-20180319081651-7d2e70ef918f h1:/8NcnxL6 github.com/asaskevich/govalidator v0.0.0-20180319081651-7d2e70ef918f/go.mod h1:lB+ZfQJz7igIIfQNfa7Ml4HSf2uFQQRzpGGRXenZAgY= github.com/aws/aws-sdk-go v1.15.24 h1:xLAdTA/ore6xdPAljzZRed7IGqQgC+nY+ERS5vaj4Ro= github.com/aws/aws-sdk-go v1.15.24/go.mod h1:mFuSZ37Z9YOHbQEwBWztmVzqXrEkub65tZoCYDt7FT0= +github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f/go.mod h1:AuiFmCCPBSrqvVMvuqFuk0qogytodnVFVSN5CeJB8Gc= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= @@ -106,6 +111,8 @@ github.com/docker/go-units v0.3.3 h1:Xk8S3Xj5sLGlG5g67hJmYMmUgXv5N4PhkjJHHqrwnTk github.com/docker/go-units v0.3.3/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/dubbogo/getty v1.3.5 h1:xJxdDj9jm7wlrRSsVZSk2TDNxJbbac5GpxV0QpjO+Tw= github.com/dubbogo/getty v1.3.5/go.mod h1:T55vN8Q6tZjf2AQZiGmkujneD3LfqYbv2b3QjacwYOY= +github.com/dubbogo/getty v1.3.7 h1:xlkYD2/AH34iGteuLMsGjLl2PwBVrbIhHjf3tlUsv1M= +github.com/dubbogo/getty v1.3.7/go.mod h1:XWO4+wAaMqgnBN9Ykv2YxxOAkGxymg6LGO9RK+EiCDY= github.com/dubbogo/go-zookeeper v1.0.1 h1:irLzvOsDOTNsN8Sv9tvYYxVu6DCQfLtziZQtUHmZgz8= github.com/dubbogo/go-zookeeper v1.0.1/go.mod h1:fn6n2CAEer3novYgk9ULLwAjuV8/g4DdC2ENwRb6E+c= github.com/dubbogo/gost v1.5.1/go.mod h1:pPTjVyoJan3aPxBPNUX0ADkXjPibLo+/Ib0/fADXSG8= @@ -197,6 +204,7 @@ github.com/google/gofuzz v0.0.0-20161122191042-44d81051d367/go.mod h1:HP5RmnzzSN github.com/google/gofuzz v0.0.0-20170612174753-24818f796faf/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI= github.com/google/gofuzz v1.0.0 h1:A8PeW59pxE9IoFRqBp37U+mSNaQoZ46F1f0f863XSXw= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/googleapis/gnostic v0.0.0-20170729233727-0c5108395e2d/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY= github.com/googleapis/gnostic v0.2.0 h1:l6N3VoaVzTncYYW+9yOz2LJJammFZGBO13sqgEhpy9g= github.com/googleapis/gnostic v0.2.0/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY= @@ -207,6 +215,8 @@ github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGa github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= +github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gotestyourself/gotestyourself v2.2.0+incompatible h1:AQwinXlbQR2HvPjQZOmDhRqsv5mZf+Jb1RnSLxcqZcI= github.com/gotestyourself/gotestyourself v2.2.0+incompatible/go.mod h1:zZKM6oeNM8k+FRljX1mnzVYeS8wiGgQyvST1/GafPbY= github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7 h1:pdN6V1QBWetyv/0+wjACpqVH+eVULgEjkurDLq3goeM= @@ -454,9 +464,11 @@ github.com/prometheus/procfs v0.0.3/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDa github.com/renier/xmlrpc v0.0.0-20170708154548-ce4a1a486c03 h1:Wdi9nwnhFNAlseAOekn6B5G/+GMtks9UKbvRU/CMM/o= github.com/renier/xmlrpc v0.0.0-20170708154548-ce4a1a486c03/go.mod h1:gRAiPF5C5Nd0eyyRdqIu9qTiFSoZzpTq727b5B8fkkU= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/ryanuber/go-glob v0.0.0-20170128012129-256dc444b735 h1:7YvPJVmEeFHR1Tj9sZEYsmarJEQfMVYpd/Vyy/A8dqE= github.com/ryanuber/go-glob v0.0.0-20170128012129-256dc444b735/go.mod h1:807d1WSdnB0XRJzKNil9Om6lcp/3a0v4qIHxIXzX/Yc= +github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= github.com/satori/go.uuid v1.2.1-0.20181028125025-b2ce2384e17b h1:gQZ0qzfKHQIybLANtM3mBXNUtOfsCFXeTsnBqCsx1KM= github.com/satori/go.uuid v1.2.1-0.20181028125025-b2ce2384e17b/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 h1:nn5Wsu0esKSJiIVhscUtVbo7ada43DJhG55ua/hjS5I= @@ -513,17 +525,28 @@ go.etcd.io/bbolt v1.3.4 h1:hi1bXHMVrlQh6WwxAy+qZCV/SYIlqo+Ushwdpa4tAKg= go.etcd.io/bbolt v1.3.4/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ= go.uber.org/atomic v1.4.0 h1:cxzIVoETapQEqDhQu3QfnvXAV4AlzcvUCxkVUFw3+EU= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/atomic v1.6.0 h1:Ezj3JGmsOnG1MoRWQkPBsKLe9DwWD9QeXzTRzzldNVk= +go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= go.uber.org/multierr v1.1.0 h1:HoEmRHQPVSqub6w2z2d2EOVs2fjyFRGyofhKuyDq0QI= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= +go.uber.org/multierr v1.5.0 h1:KCa4XfM8CWFCpxXRGok+Q0SS/0XBhMDbHHGABQLvD2A= +go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= go.uber.org/zap v1.10.0 h1:ORx85nbTijNz8ljznvCMR1ZBIPKFn3jQrag10X2AsuM= go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= +go.uber.org/zap v1.15.0 h1:ZZCA22JRF2gQE5FoNmhmrf7jeJJ2uhqDUNRYKm8dvmM= +go.uber.org/zap v1.15.0/go.mod h1:Mb2vm2krFEG5DV0W9qcHBYFtp/Wku1cvYaqPsS/WYfc= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c h1:Vj5n4GlwjmQteupaxJ9+0FNOmBrHfq7vN4btdGoDZgI= golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529 h1:iMGN4xG0cnqj3t+zOM8wUB0BiPKHEwSxEZCvzcbZuvk= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= golang.org/x/net v0.0.0-20170114055629-f2499483f923/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -532,8 +555,10 @@ golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73r golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190628185345-da137c7871d7 h1:rTIdg5QFRR7XCaK4LCjBiPbx8j4DQRpdYMnGn/bJUEU= golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b h1:0mm1VjtFUOIlE1SbDlwjYaDxZVDP2S5ou6y0gSgXHu8= @@ -557,6 +582,7 @@ golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190508220229-2d0786266e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190523142557-0e01d883c5c5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190801041406-cbf593c0f2f3 h1:4y9KwBHBgBNwDbtu44R5o1fdOCQUEXhbk/P4A9WmJq0= @@ -578,6 +604,10 @@ golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3 golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/api v0.0.0-20180829000535-087779f1d2c9 h1:z1TeLUmxf9ws9KLICfmX+KGXTs+rjm+aGWzfsv7MZ9w= google.golang.org/api v0.0.0-20180829000535-087779f1d2c9/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= google.golang.org/appengine v1.1.0 h1:igQkv0AAhEIvTEpD5LIpAfav2eeVO9HBTjvKHVJPRSs= @@ -595,6 +625,7 @@ gopkg.in/asn1-ber.v1 v1.0.0-20181015200546-f715ec2f112d/go.mod h1:cuepJuh7vyXfUy gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2/go.mod h1:Xk6kEKp8OKb+X14hQBKWaSkCsqBpgog8nAV2xsGOxlo= @@ -619,6 +650,7 @@ gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= istio.io/gogo-genproto v0.0.0-20190124151557-6d926a6e6feb/go.mod h1:eIDJ6jNk/IeJz6ODSksHl5Aiczy5JUq6vFhJWI5OtiI= k8s.io/api v0.0.0-20180806132203-61b11ee65332/go.mod h1:iuAfoD4hCxJ8Onx9kaTIt30j7jUFS00AXQi6QMi99vA= k8s.io/api v0.0.0-20190325185214-7544f9db76f6 h1:9MWtbqhwTyDvF4cS1qAhxDb9Mi8taXiAu+5nEacl7gY= diff --git a/protocol/dubbo/client_test.go b/protocol/dubbo/client_test.go index 744ffa80d6bc65e8526201b8cd327bb12b43caef..8b0ba169b82910652c64011c47568c7a018ae5e0 100644 --- a/protocol/dubbo/client_test.go +++ b/protocol/dubbo/client_test.go @@ -37,7 +37,13 @@ import ( "github.com/apache/dubbo-go/protocol" ) -func TestClient_CallOneway(t *testing.T) { +const ( + mockMethodNameGetUser = "GetUser" + mockMethodNameGetBigPkg = "GetBigPkg" + mockAddress = "127.0.0.1:20000" +) + +func TestClientCallOneway(t *testing.T) { proto, url := InitTest(t) c := &Client{ @@ -50,15 +56,14 @@ func TestClient_CallOneway(t *testing.T) { } c.pool = newGettyRPCClientConnPool(c, clientConf.PoolSize, time.Duration(int(time.Second)*clientConf.PoolTTL)) - //user := &User{} - err := c.CallOneway(NewRequest("127.0.0.1:20000", url, "GetUser", []interface{}{"1", "username"}, nil)) + err := c.CallOneway(NewRequest(mockAddress, url, mockMethodNameGetUser, []interface{}{"1", "username"}, nil)) assert.NoError(t, err) // destroy proto.Destroy() } -func TestClient_Call(t *testing.T) { +func TestClientCall(t *testing.T) { proto, url := InitTest(t) c := &Client{ @@ -77,50 +82,50 @@ func TestClient_Call(t *testing.T) { ) user = &User{} - err = c.Call(NewRequest("127.0.0.1:20000", url, "GetBigPkg", []interface{}{nil}, nil), NewResponse(user, nil)) + err = c.Call(NewRequest(mockAddress, url, mockMethodNameGetBigPkg, []interface{}{nil}, nil), NewResponse(user, nil)) assert.NoError(t, err) assert.NotEqual(t, "", user.Id) assert.NotEqual(t, "", user.Name) user = &User{} - err = c.Call(NewRequest("127.0.0.1:20000", url, "GetUser", []interface{}{"1", "username"}, nil), NewResponse(user, nil)) + err = c.Call(NewRequest(mockAddress, url, mockMethodNameGetUser, []interface{}{"1", "username"}, nil), NewResponse(user, nil)) assert.NoError(t, err) assert.Equal(t, User{Id: "1", Name: "username"}, *user) user = &User{} - err = c.Call(NewRequest("127.0.0.1:20000", url, "GetUser0", []interface{}{"1", nil, "username"}, nil), NewResponse(user, nil)) + err = c.Call(NewRequest(mockAddress, url, "GetUser0", []interface{}{"1", nil, "username"}, nil), NewResponse(user, nil)) assert.NoError(t, err) assert.Equal(t, User{Id: "1", Name: "username"}, *user) - err = c.Call(NewRequest("127.0.0.1:20000", url, "GetUser1", []interface{}{}, nil), NewResponse(user, nil)) + err = c.Call(NewRequest(mockAddress, url, "GetUser1", []interface{}{}, nil), NewResponse(user, nil)) assert.NoError(t, err) - err = c.Call(NewRequest("127.0.0.1:20000", url, "GetUser2", []interface{}{}, nil), NewResponse(user, nil)) + err = c.Call(NewRequest(mockAddress, url, "GetUser2", []interface{}{}, nil), NewResponse(user, nil)) assert.EqualError(t, err, "error") user2 := []interface{}{} - err = c.Call(NewRequest("127.0.0.1:20000", url, "GetUser3", []interface{}{}, nil), NewResponse(&user2, nil)) + err = c.Call(NewRequest(mockAddress, url, "GetUser3", []interface{}{}, nil), NewResponse(&user2, nil)) assert.NoError(t, err) assert.Equal(t, &User{Id: "1", Name: "username"}, user2[0]) user2 = []interface{}{} - err = c.Call(NewRequest("127.0.0.1:20000", url, "GetUser4", []interface{}{[]interface{}{"1", "username"}}, nil), NewResponse(&user2, nil)) + err = c.Call(NewRequest(mockAddress, url, "GetUser4", []interface{}{[]interface{}{"1", "username"}}, nil), NewResponse(&user2, nil)) assert.NoError(t, err) assert.Equal(t, &User{Id: "1", Name: "username"}, user2[0]) user3 := map[interface{}]interface{}{} - err = c.Call(NewRequest("127.0.0.1:20000", url, "GetUser5", []interface{}{map[interface{}]interface{}{"id": "1", "name": "username"}}, nil), NewResponse(&user3, nil)) + err = c.Call(NewRequest(mockAddress, url, "GetUser5", []interface{}{map[interface{}]interface{}{"id": "1", "name": "username"}}, nil), NewResponse(&user3, nil)) assert.NoError(t, err) assert.NotNil(t, user3) assert.Equal(t, &User{Id: "1", Name: "username"}, user3["key"]) user = &User{} - err = c.Call(NewRequest("127.0.0.1:20000", url, "GetUser6", []interface{}{0}, nil), NewResponse(user, nil)) + err = c.Call(NewRequest(mockAddress, url, "GetUser6", []interface{}{0}, nil), NewResponse(user, nil)) assert.NoError(t, err) assert.Equal(t, User{Id: "", Name: ""}, *user) user = &User{} - err = c.Call(NewRequest("127.0.0.1:20000", url, "GetUser6", []interface{}{1}, nil), NewResponse(user, nil)) + err = c.Call(NewRequest(mockAddress, url, "GetUser6", []interface{}{1}, nil), NewResponse(user, nil)) assert.NoError(t, err) assert.Equal(t, User{Id: "1", Name: ""}, *user) @@ -128,7 +133,7 @@ func TestClient_Call(t *testing.T) { proto.Destroy() } -func TestClient_AsyncCall(t *testing.T) { +func TestClientAsyncCall(t *testing.T) { proto, url := InitTest(t) c := &Client{ @@ -144,7 +149,7 @@ func TestClient_AsyncCall(t *testing.T) { user := &User{} lock := sync.Mutex{} lock.Lock() - err := c.AsyncCall(NewRequest("127.0.0.1:20000", url, "GetUser", []interface{}{"1", "username"}, nil), func(response common.CallbackResponse) { + err := c.AsyncCall(NewRequest(mockAddress, url, mockMethodNameGetUser, []interface{}{"1", "username"}, nil), func(response common.CallbackResponse) { r := response.(AsyncCallbackResponse) assert.Equal(t, User{Id: "1", Name: "username"}, *r.Reply.(*Response).reply.(*User)) lock.Unlock() diff --git a/protocol/dubbo/codec_test.go b/protocol/dubbo/codec_test.go index 5dc71f0d080c8c862d68029c7983a4407913307e..c2ca443637e23101679770e464f49e0cbdeab2a9 100644 --- a/protocol/dubbo/codec_test.go +++ b/protocol/dubbo/codec_test.go @@ -29,7 +29,7 @@ import ( "github.com/stretchr/testify/assert" ) -func TestDubboPackage_MarshalAndUnmarshal(t *testing.T) { +func TestDubboPackageMarshalAndUnmarshal(t *testing.T) { pkg := &DubboPackage{} pkg.Body = []interface{}{"a"} pkg.Header.Type = hessian.PackageHeartbeat diff --git a/protocol/dubbo/dubbo_invoker_test.go b/protocol/dubbo/dubbo_invoker_test.go index 1a64301f8200a4264001284cca1af3f0f1e07814..c0640d5558fcb9fb00f02eba0fddc54bb4162592 100644 --- a/protocol/dubbo/dubbo_invoker_test.go +++ b/protocol/dubbo/dubbo_invoker_test.go @@ -35,7 +35,7 @@ import ( "github.com/apache/dubbo-go/protocol/invocation" ) -func TestDubboInvoker_Invoke(t *testing.T) { +func TestDubboInvokerInvoke(t *testing.T) { proto, url := InitTest(t) c := &Client{ @@ -51,7 +51,7 @@ func TestDubboInvoker_Invoke(t *testing.T) { invoker := NewDubboInvoker(url, c) user := &User{} - inv := invocation.NewRPCInvocationWithOptions(invocation.WithMethodName("GetUser"), invocation.WithArguments([]interface{}{"1", "username"}), + inv := invocation.NewRPCInvocationWithOptions(invocation.WithMethodName(mockMethodNameGetUser), invocation.WithArguments([]interface{}{"1", "username"}), invocation.WithReply(user), invocation.WithAttachments(map[string]string{"test_key": "test_value"})) // Call diff --git a/protocol/dubbo/dubbo_protocol_test.go b/protocol/dubbo/dubbo_protocol_test.go index 14f6868ad4a7f2bf6f549a2fbbce8234cbb4aa12..6f3892be67be533dea09dc7bd54de56844dbc79c 100644 --- a/protocol/dubbo/dubbo_protocol_test.go +++ b/protocol/dubbo/dubbo_protocol_test.go @@ -31,15 +31,19 @@ import ( "github.com/apache/dubbo-go/protocol" ) -func TestDubboProtocol_Export(t *testing.T) { - // Export - proto := GetProtocol() - srvConf = &ServerConfig{} - url, err := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?anyhost=true&" + +const ( + mockCommonUrl = "dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?anyhost=true&" + "application=BDTService&category=providers&default.timeout=10000&dubbo=dubbo-provider-golang-1.0.0&" + "environment=dev&interface=com.ikurento.user.UserProvider&ip=192.168.56.1&methods=GetUser%2C&" + "module=dubbogo+user-info+server&org=ikurento.com&owner=ZX&pid=1447&revision=0.0.1&" + - "side=provider&timeout=3000×tamp=1556509797245") + "side=provider&timeout=3000×tamp=1556509797245" +) + +func TestDubboProtocolExport(t *testing.T) { + // Export + proto := GetProtocol() + srvConf = &ServerConfig{} + url, err := common.NewURL(mockCommonUrl) assert.NoError(t, err) exporter := proto.Export(protocol.NewBaseInvoker(url)) @@ -48,11 +52,7 @@ func TestDubboProtocol_Export(t *testing.T) { assert.True(t, eq) // second service: the same path and the different version - url2, err := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?anyhost=true&"+ - "application=BDTService&category=providers&default.timeout=10000&dubbo=dubbo-provider-golang-1.0.0&"+ - "environment=dev&interface=com.ikurento.user.UserProvider&ip=192.168.56.1&methods=GetUser%2C&"+ - "module=dubbogo+user-info+server&org=ikurento.com&owner=ZX&pid=1447&revision=0.0.1&"+ - "side=provider&timeout=3000×tamp=1556509797245", common.WithParamsValue(constant.VERSION_KEY, "v1.1")) + url2, err := common.NewURL(mockCommonUrl, common.WithParamsValue(constant.VERSION_KEY, "v1.1")) assert.NoError(t, err) exporter2 := proto.Export(protocol.NewBaseInvoker(url2)) // make sure url @@ -74,14 +74,10 @@ func TestDubboProtocol_Export(t *testing.T) { assert.False(t, ok) } -func TestDubboProtocol_Refer(t *testing.T) { +func TestDubboProtocolRefer(t *testing.T) { // Refer proto := GetProtocol() - url, err := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?anyhost=true&" + - "application=BDTService&category=providers&default.timeout=10000&dubbo=dubbo-provider-golang-1.0.0&" + - "environment=dev&interface=com.ikurento.user.UserProvider&ip=192.168.56.1&methods=GetUser%2C&" + - "module=dubbogo+user-info+server&org=ikurento.com&owner=ZX&pid=1447&revision=0.0.1&" + - "side=provider&timeout=3000×tamp=1556509797245") + url, err := common.NewURL(mockCommonUrl) assert.NoError(t, err) clientConf = &ClientConfig{} invoker := proto.Refer(url) diff --git a/protocol/grpc/common_test.go b/protocol/grpc/common_test.go index 33c2fc617d52795d13d9b4fc02054ef5a79d0934..b732283a9bf9d316c1b9d4356a1b9563bfa1d3ec 100644 --- a/protocol/grpc/common_test.go +++ b/protocol/grpc/common_test.go @@ -106,7 +106,7 @@ func dubboGreeterSayHelloHandler(srv interface{}, ctx context.Context, Server: srv, FullMethod: "/helloworld.Greeter/SayHello", } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { + handler := func(context.Context, interface{}) (interface{}, error) { result := base.GetProxyImpl().Invoke(context.Background(), invo) return result.Result(), result.Error() } diff --git a/protocol/grpc/grpc_invoker_test.go b/protocol/grpc/grpc_invoker_test.go index 3054ada13340a9c9cc038a63d89c45ced9ec7ac7..d5ebbb4f47a324791a3367a649bd49b06281540f 100644 --- a/protocol/grpc/grpc_invoker_test.go +++ b/protocol/grpc/grpc_invoker_test.go @@ -33,11 +33,19 @@ import ( "github.com/apache/dubbo-go/protocol/invocation" ) +const ( + mockGrpcCommonUrl = "grpc://127.0.0.1:30000/GrpcGreeterImpl?accesslog=&anyhost=true&app.version=0.0.1&application=BDTService&async=false&bean.name=GrpcGreeterImpl" + + "&category=providers&cluster=failover&dubbo=dubbo-provider-golang-2.6.0&environment=dev&execute.limit=&execute.limit.rejected.handler=&generic=false&group=&interface=io.grpc.examples.helloworld.GreeterGrpc%24IGreeter" + + "&ip=192.168.1.106&loadbalance=random&methods.SayHello.loadbalance=random&methods.SayHello.retries=1&methods.SayHello.tps.limit.interval=&methods.SayHello.tps.limit.rate=&methods.SayHello.tps.limit.strategy=" + + "&methods.SayHello.weight=0&module=dubbogo+say-hello+client&name=BDTService&organization=ikurento.com&owner=ZX&pid=49427&reference.filter=cshutdown®istry.role=3&remote.timestamp=1576923717&retries=" + + "&service.filter=echo%2Ctoken%2Caccesslog%2Ctps%2Cexecute%2Cpshutdown&side=provider×tamp=1576923740&tps.limit.interval=&tps.limit.rate=&tps.limit.rejected.handler=&tps.limit.strategy=&tps.limiter=&version=&warmup=100!" +) + func TestInvoke(t *testing.T) { go internal.InitGrpcServer() defer internal.ShutdownGrpcServer() - url, err := common.NewURL("grpc://127.0.0.1:30000/GrpcGreeterImpl?accesslog=&anyhost=true&app.version=0.0.1&application=BDTService&async=false&bean.name=GrpcGreeterImpl&category=providers&cluster=failover&dubbo=dubbo-provider-golang-2.6.0&environment=dev&execute.limit=&execute.limit.rejected.handler=&generic=false&group=&interface=io.grpc.examples.helloworld.GreeterGrpc%24IGreeter&ip=192.168.1.106&loadbalance=random&methods.SayHello.loadbalance=random&methods.SayHello.retries=1&methods.SayHello.tps.limit.interval=&methods.SayHello.tps.limit.rate=&methods.SayHello.tps.limit.strategy=&methods.SayHello.weight=0&module=dubbogo+say-hello+client&name=BDTService&organization=ikurento.com&owner=ZX&pid=49427&reference.filter=cshutdown®istry.role=3&remote.timestamp=1576923717&retries=&service.filter=echo%2Ctoken%2Caccesslog%2Ctps%2Cexecute%2Cpshutdown&side=provider×tamp=1576923740&tps.limit.interval=&tps.limit.rate=&tps.limit.rejected.handler=&tps.limit.strategy=&tps.limiter=&version=&warmup=100!") + url, err := common.NewURL(mockGrpcCommonUrl) assert.Nil(t, err) cli := NewClient(url) diff --git a/protocol/grpc/grpc_protocol_test.go b/protocol/grpc/grpc_protocol_test.go index d028f8ef4285b0183e6e0b5b32deede59ce5c531..87ce714fc7437eca53509bb368ed7bc774929634 100644 --- a/protocol/grpc/grpc_protocol_test.go +++ b/protocol/grpc/grpc_protocol_test.go @@ -32,12 +32,12 @@ import ( "github.com/apache/dubbo-go/protocol/grpc/internal" ) -func TestGrpcProtocol_Export(t *testing.T) { +func TestGrpcProtocolExport(t *testing.T) { // Export addService() proto := GetProtocol() - url, err := common.NewURL("grpc://127.0.0.1:40000/GrpcGreeterImpl?accesslog=&app.version=0.0.1&application=BDTService&bean.name=GrpcGreeterImpl&cluster=failover&environment=dev&execute.limit=&execute.limit.rejected.handler=&group=&interface=io.grpc.examples.helloworld.GreeterGrpc%24IGreeter&loadbalance=random&methods.SayHello.loadbalance=random&methods.SayHello.retries=1&methods.SayHello.tps.limit.interval=&methods.SayHello.tps.limit.rate=&methods.SayHello.tps.limit.strategy=&methods.SayHello.weight=0&module=dubbogo+say-hello+client&name=BDTService&organization=ikurento.com&owner=ZX®istry.role=3&retries=&service.filter=echo%2Ctoken%2Caccesslog%2Ctps%2Cexecute%2Cpshutdown×tamp=1576923717&tps.limit.interval=&tps.limit.rate=&tps.limit.rejected.handler=&tps.limit.strategy=&tps.limiter=&version=&warmup=100") + url, err := common.NewURL(mockGrpcCommonUrl) assert.NoError(t, err) exporter := proto.Export(protocol.NewBaseInvoker(url)) time.Sleep(time.Second) @@ -61,13 +61,13 @@ func TestGrpcProtocol_Export(t *testing.T) { assert.False(t, ok) } -func TestGrpcProtocol_Refer(t *testing.T) { +func TestGrpcProtocolRefer(t *testing.T) { go internal.InitGrpcServer() defer internal.ShutdownGrpcServer() time.Sleep(time.Second) proto := GetProtocol() - url, err := common.NewURL("grpc://127.0.0.1:30000/GrpcGreeterImpl?accesslog=&anyhost=true&app.version=0.0.1&application=BDTService&async=false&bean.name=GrpcGreeterImpl&category=providers&cluster=failover&dubbo=dubbo-provider-golang-2.6.0&environment=dev&execute.limit=&execute.limit.rejected.handler=&generic=false&group=&interface=io.grpc.examples.helloworld.GreeterGrpc%24IGreeter&ip=192.168.1.106&loadbalance=random&methods.SayHello.loadbalance=random&methods.SayHello.retries=1&methods.SayHello.tps.limit.interval=&methods.SayHello.tps.limit.rate=&methods.SayHello.tps.limit.strategy=&methods.SayHello.weight=0&module=dubbogo+say-hello+client&name=BDTService&organization=ikurento.com&owner=ZX&pid=49427&reference.filter=cshutdown®istry.role=3&remote.timestamp=1576923717&retries=&service.filter=echo%2Ctoken%2Caccesslog%2Ctps%2Cexecute%2Cpshutdown&side=provider×tamp=1576923740&tps.limit.interval=&tps.limit.rate=&tps.limit.rejected.handler=&tps.limit.strategy=&tps.limiter=&version=&warmup=100!") + url, err := common.NewURL(mockGrpcCommonUrl) assert.NoError(t, err) invoker := proto.Refer(url) diff --git a/protocol/jsonrpc/http_test.go b/protocol/jsonrpc/http_test.go index f8480bf32e15ad428209eedb72757a299455eb20..576591940dd3021e7bbd9d2eda0ac5498391a1f7 100644 --- a/protocol/jsonrpc/http_test.go +++ b/protocol/jsonrpc/http_test.go @@ -48,7 +48,15 @@ type ( } ) -func TestHTTPClient_Call(t *testing.T) { +const ( + mockJsonCommonUrl = "jsonrpc://127.0.0.1:20001/UserProvider?anyhost=true&" + + "application=BDTService&category=providers&default.timeout=10000&dubbo=dubbo-provider-golang-1.0.0&" + + "environment=dev&interface=com.ikurento.user.UserProvider&ip=192.168.56.1&methods=GetUser%2C&" + + "module=dubbogo+user-info+server&org=ikurento.com&owner=ZX&pid=1447&revision=0.0.1&" + + "side=provider&timeout=3000×tamp=1556509797245&bean.name=UserProvider" +) + +func TestHTTPClientCall(t *testing.T) { methods, err := common.ServiceMap.Register("com.ikurento.user.UserProvider", "jsonrpc", &UserProvider{}) assert.NoError(t, err) @@ -56,11 +64,7 @@ func TestHTTPClient_Call(t *testing.T) { // Export proto := GetProtocol() - url, err := common.NewURL("jsonrpc://127.0.0.1:20001/UserProvider?anyhost=true&" + - "application=BDTService&category=providers&default.timeout=10000&dubbo=dubbo-provider-golang-1.0.0&" + - "environment=dev&interface=com.ikurento.user.UserProvider&ip=192.168.56.1&methods=GetUser%2C&" + - "module=dubbogo+user-info+server&org=ikurento.com&owner=ZX&pid=1447&revision=0.0.1&" + - "side=provider&timeout=3000×tamp=1556509797245&bean.name=UserProvider") + url, err := common.NewURL(mockJsonCommonUrl) assert.NoError(t, err) proto.Export(&proxy_factory.ProxyInvoker{ BaseInvoker: *protocol.NewBaseInvoker(url), diff --git a/protocol/jsonrpc/json.go b/protocol/jsonrpc/json.go index 389ead9c1a530742c872a238d89b2df5ae3462ca..7b05a229437958b44a405780bbe1649a995478d0 100644 --- a/protocol/jsonrpc/json.go +++ b/protocol/jsonrpc/json.go @@ -124,10 +124,8 @@ func (c *jsonClientCodec) Write(d *CodecData) ([]byte, error) { if param != nil { switch k := reflect.TypeOf(param).Kind(); k { case reflect.Map: - if reflect.TypeOf(param).Key().Kind() == reflect.String { - if reflect.ValueOf(param).IsNil() { - param = nil - } + if reflect.TypeOf(param).Key().Kind() == reflect.String && reflect.ValueOf(param).IsNil() { + param = nil } case reflect.Slice: if reflect.ValueOf(param).IsNil() { @@ -137,10 +135,8 @@ func (c *jsonClientCodec) Write(d *CodecData) ([]byte, error) { case reflect.Ptr: switch ptrK := reflect.TypeOf(param).Elem().Kind(); ptrK { case reflect.Map: - if reflect.TypeOf(param).Elem().Key().Kind() == reflect.String { - if reflect.ValueOf(param).Elem().IsNil() { - param = nil - } + if reflect.TypeOf(param).Elem().Key().Kind() == reflect.String && reflect.ValueOf(param).Elem().IsNil() { + param = nil } case reflect.Slice: if reflect.ValueOf(param).Elem().IsNil() { diff --git a/protocol/jsonrpc/json_test.go b/protocol/jsonrpc/json_test.go index ade74246121b5f275c8dbeaa5923228dbab2804f..a3814e9ad5e1df2c3a8d8cc4305e5787b44596ec 100644 --- a/protocol/jsonrpc/json_test.go +++ b/protocol/jsonrpc/json_test.go @@ -30,7 +30,7 @@ type TestData struct { Test string } -func TestJsonClientCodec_Write(t *testing.T) { +func TestJsonClientCodecWrite(t *testing.T) { cd := &CodecData{ ID: 1, Method: "GetUser", @@ -46,7 +46,7 @@ func TestJsonClientCodec_Write(t *testing.T) { assert.EqualError(t, err, "unsupported param type: int") } -func TestJsonClientCodec_Read(t *testing.T) { +func TestJsonClientCodecRead(t *testing.T) { codec := newJsonClientCodec() codec.pending[1] = "GetUser" rsp := &TestData{} @@ -60,7 +60,7 @@ func TestJsonClientCodec_Read(t *testing.T) { assert.EqualError(t, err, "{\"code\":-32000,\"message\":\"error\"}") } -func TestServerCodec_Write(t *testing.T) { +func TestServerCodecWrite(t *testing.T) { codec := newServerCodec() a := json.RawMessage([]byte("1")) codec.req = serverRequest{Version: "1.0", Method: "GetUser", ID: &a} @@ -73,7 +73,7 @@ func TestServerCodec_Write(t *testing.T) { assert.Equal(t, "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"Test\":\"test\"},\"error\":{\"code\":-32000,\"message\":\"error\"}}\n", string(data)) } -func TestServerCodec_Read(t *testing.T) { +func TestServerCodecRead(t *testing.T) { codec := newServerCodec() header := map[string]string{} err := codec.ReadHeader(header, []byte("{\"jsonrpc\":\"2.0\",\"method\":\"GetUser\",\"params\":[\"args\",2],\"id\":1}\n")) diff --git a/protocol/jsonrpc/jsonrpc_invoker_test.go b/protocol/jsonrpc/jsonrpc_invoker_test.go index 0f14ba11e2dec18bbd4d63e87e8c0fb2727f3755..d7124ca07c6ba6d79dc72e7fb6bd98cd4b3a97b2 100644 --- a/protocol/jsonrpc/jsonrpc_invoker_test.go +++ b/protocol/jsonrpc/jsonrpc_invoker_test.go @@ -34,7 +34,7 @@ import ( "github.com/apache/dubbo-go/protocol/invocation" ) -func TestJsonrpcInvoker_Invoke(t *testing.T) { +func TestJsonrpcInvokerInvoke(t *testing.T) { methods, err := common.ServiceMap.Register("UserProvider", "jsonrpc", &UserProvider{}) assert.NoError(t, err) diff --git a/protocol/jsonrpc/jsonrpc_protocol_test.go b/protocol/jsonrpc/jsonrpc_protocol_test.go index c00bed12fe9fbb4937f21810cee548a25e3b1c05..10a9016913c77551efc54a92149ef377ade399f5 100644 --- a/protocol/jsonrpc/jsonrpc_protocol_test.go +++ b/protocol/jsonrpc/jsonrpc_protocol_test.go @@ -34,7 +34,7 @@ import ( "github.com/apache/dubbo-go/protocol" ) -func TestJsonrpcProtocol_Export(t *testing.T) { +func TestJsonrpcProtocolExport(t *testing.T) { // Export proto := GetProtocol() url, err := common.NewURL("jsonrpc://127.0.0.1:20000/com.ikurento.user.UserProvider?anyhost=true&" + @@ -65,7 +65,7 @@ func TestJsonrpcProtocol_Export(t *testing.T) { assert.False(t, ok) } -func TestJsonrpcProtocol_Refer(t *testing.T) { +func TestJsonrpcProtocolRefer(t *testing.T) { // Refer proto := GetProtocol() url, err := common.NewURL("jsonrpc://127.0.0.1:20000/com.ikurento.user.UserProvider?anyhost=true&" + diff --git a/protocol/protocolwrapper/mock_protocol_filter.go b/protocol/protocolwrapper/mock_protocol_filter.go index 8763c20410915d4e81afd35691be7d9ed490f7a1..2e9ffed06f03d196c91f6679df21538612bac405 100644 --- a/protocol/protocolwrapper/mock_protocol_filter.go +++ b/protocol/protocolwrapper/mock_protocol_filter.go @@ -45,5 +45,5 @@ func (pfw *mockProtocolFilter) Refer(url common.URL) protocol.Invoker { // Destroy will do nothing func (pfw *mockProtocolFilter) Destroy() { - + return } diff --git a/protocol/protocolwrapper/protocol_filter_wrapper_test.go b/protocol/protocolwrapper/protocol_filter_wrapper_test.go index 8491d57462d47d6af72040d41b78dcb30e6da697..b03ea7b9b66d926aff8851f88e1bd7434b254903 100644 --- a/protocol/protocolwrapper/protocol_filter_wrapper_test.go +++ b/protocol/protocolwrapper/protocol_filter_wrapper_test.go @@ -36,7 +36,7 @@ import ( "github.com/apache/dubbo-go/protocol" ) -func TestProtocolFilterWrapper_Export(t *testing.T) { +func TestProtocolFilterWrapperExport(t *testing.T) { filtProto := extension.GetProtocol(FILTER) filtProto.(*ProtocolFilterWrapper).protocol = &protocol.BaseProtocol{} @@ -48,7 +48,7 @@ func TestProtocolFilterWrapper_Export(t *testing.T) { assert.True(t, ok) } -func TestProtocolFilterWrapper_Refer(t *testing.T) { +func TestProtocolFilterWrapperRefer(t *testing.T) { filtProto := extension.GetProtocol(FILTER) filtProto.(*ProtocolFilterWrapper).protocol = &protocol.BaseProtocol{} diff --git a/protocol/rest/client/client_impl/resty_client.go b/protocol/rest/client/client_impl/resty_client.go index b60f50a5a70cde01a051dbb2a4490cbb792e0116..f301d945045a445b5370252044442080f042d126 100644 --- a/protocol/rest/client/client_impl/resty_client.go +++ b/protocol/rest/client/client_impl/resty_client.go @@ -50,7 +50,7 @@ func NewRestyClient(restOption *client.RestOptions) client.RestClient { client := resty.New() client.SetTransport( &http.Transport{ - DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { + DialContext: func(_ context.Context, network, addr string) (net.Conn, error) { c, err := net.DialTimeout(network, addr, restOption.ConnectTimeout) if err != nil { return nil, err diff --git a/protocol/rest/config/reader/rest_config_reader_test.go b/protocol/rest/config/reader/rest_config_reader_test.go index d2dba40b9b85a6cd7772e0fee619720c79e91eb4..c6f891262ce3ba5ec6645ade9084005d14716789 100644 --- a/protocol/rest/config/reader/rest_config_reader_test.go +++ b/protocol/rest/config/reader/rest_config_reader_test.go @@ -31,7 +31,7 @@ import ( "github.com/apache/dubbo-go/protocol/rest/config" ) -func TestRestConfigReader_ReadConsumerConfig(t *testing.T) { +func TestRestConfigReaderReadConsumerConfig(t *testing.T) { bs, err := yaml.LoadYMLConfig("./testdata/consumer_config.yml") assert.NoError(t, err) configReader := NewRestConfigReader() @@ -40,7 +40,7 @@ func TestRestConfigReader_ReadConsumerConfig(t *testing.T) { assert.NotEmpty(t, config.GetRestConsumerServiceConfigMap()) } -func TestRestConfigReader_ReadProviderConfig(t *testing.T) { +func TestRestConfigReaderReadProviderConfig(t *testing.T) { bs, err := yaml.LoadYMLConfig("./testdata/provider_config.yml") assert.NoError(t, err) configReader := NewRestConfigReader() diff --git a/protocol/rest/rest_invoker_test.go b/protocol/rest/rest_invoker_test.go index 2ea260c58d03c27a691e48b953ce6d64f75040a2..9df97a211e9d90daa3206b94926ceeac42df4606 100644 --- a/protocol/rest/rest_invoker_test.go +++ b/protocol/rest/rest_invoker_test.go @@ -39,7 +39,15 @@ import ( "github.com/apache/dubbo-go/protocol/rest/server/server_impl" ) -func TestRestInvoker_Invoke(t *testing.T) { +const ( + mockRestCommonUrl = "rest://127.0.0.1:8877/com.ikurento.user.UserProvider?anyhost=true&" + + "application=BDTService&category=providers&default.timeout=10000&dubbo=dubbo-provider-golang-1.0.0&" + + "environment=dev&interface=com.ikurento.user.UserProvider&ip=192.168.56.1&methods=GetUser%2C&" + + "module=dubbogo+user-info+server&org=ikurento.com&owner=ZX&pid=1447&revision=0.0.1&" + + "side=provider&timeout=3000×tamp=1556509797245" +) + +func TestRestInvokerInvoke(t *testing.T) { // Refer proto := GetRestProtocol() defer proto.Destroy() @@ -55,11 +63,7 @@ func TestRestInvoker_Invoke(t *testing.T) { chain.ProcessFilter(request, response) }) - url, err := common.NewURL("rest://127.0.0.1:8877/com.ikurento.user.UserProvider?anyhost=true&" + - "application=BDTService&category=providers&default.timeout=10000&dubbo=dubbo-provider-golang-1.0.0&" + - "environment=dev&interface=com.ikurento.user.UserProvider&ip=192.168.56.1&methods=GetUser%2C&" + - "module=dubbogo+user-info+server&org=ikurento.com&owner=ZX&pid=1447&revision=0.0.1&" + - "side=provider&timeout=3000×tamp=1556509797245") + url, err := common.NewURL(mockRestCommonUrl) assert.NoError(t, err) _, err = common.ServiceMap.Register("UserProvider", url.Protocol, &UserProvider{}) assert.NoError(t, err) diff --git a/protocol/rest/rest_protocol_test.go b/protocol/rest/rest_protocol_test.go index 9117148777ca868cb7d2672236e800c836d3de84..9ff4e7df7fe41d7fd028bf476cc2192cf7cefcca 100644 --- a/protocol/rest/rest_protocol_test.go +++ b/protocol/rest/rest_protocol_test.go @@ -38,14 +38,10 @@ import ( rest_config "github.com/apache/dubbo-go/protocol/rest/config" ) -func TestRestProtocol_Refer(t *testing.T) { +func TestRestProtocolRefer(t *testing.T) { // Refer proto := GetRestProtocol() - url, err := common.NewURL("rest://127.0.0.1:20000/com.ikurento.user.UserProvider?anyhost=true&" + - "application=BDTService&category=providers&default.timeout=10000&dubbo=dubbo-provider-golang-1.0.0&" + - "environment=dev&interface=com.ikurento.user.UserProvider&ip=192.168.56.1&methods=GetUser%2C&" + - "module=dubbogo+user-info+server&org=ikurento.com&owner=ZX&pid=1447&revision=0.0.1&" + - "side=provider&timeout=3000×tamp=1556509797245") + url, err := common.NewURL(mockRestCommonUrl) assert.NoError(t, err) con := config.ConsumerConfig{ ConnectTimeout: 5 * time.Second, @@ -71,14 +67,10 @@ func TestRestProtocol_Refer(t *testing.T) { assert.Equal(t, 0, invokersLen) } -func TestRestProtocol_Export(t *testing.T) { +func TestRestProtocolExport(t *testing.T) { // Export proto := GetRestProtocol() - url, err := common.NewURL("rest://127.0.0.1:8888/com.ikurento.user.UserProvider?anyhost=true&" + - "application=BDTService&category=providers&default.timeout=10000&dubbo=dubbo-provider-golang-1.0.0&" + - "environment=dev&interface=com.ikurento.user.UserProvider&ip=192.168.56.1&methods=GetUser%2C&" + - "module=dubbogo+user-info+server&org=ikurento.com&owner=ZX&pid=1447&revision=0.0.1&" + - "side=provider&timeout=3000×tamp=1556509797245") + url, err := common.NewURL(mockRestCommonUrl) assert.NoError(t, err) _, err = common.ServiceMap.Register("UserProvider", url.Protocol, &UserProvider{}) assert.NoError(t, err) diff --git a/protocol/rpc_status.go b/protocol/rpc_status.go index 0eeca6c1bba1f471117eb687a92d0458b9d5901d..60becfb34135470b0e69972c25a743f44efe19d5 100644 --- a/protocol/rpc_status.go +++ b/protocol/rpc_status.go @@ -170,12 +170,12 @@ func CurrentTimeMillis() int64 { // Destroy is used to clean all status func CleanAllStatus() { - delete1 := func(key interface{}, value interface{}) bool { + delete1 := func(key, _ interface{}) bool { methodStatistics.Delete(key) return true } methodStatistics.Range(delete1) - delete2 := func(key interface{}, value interface{}) bool { + delete2 := func(key, _ interface{}) bool { serviceStatistic.Delete(key) return true } diff --git a/protocol/rpc_status_test.go b/protocol/rpc_status_test.go index 611b7cba6e453cdf00624b4414d468278fd62cb1..cc12753cf25007ab6d1010836b203aee22d78ca9 100644 --- a/protocol/rpc_status_test.go +++ b/protocol/rpc_status_test.go @@ -30,10 +30,14 @@ import ( "github.com/apache/dubbo-go/common" ) +const ( + mockCommonDubboUrl = "dubbo://192.168.10.10:20000/com.ikurento.user.UserProvider" +) + func TestBeginCount(t *testing.T) { defer CleanAllStatus() - url, _ := common.NewURL("dubbo://192.168.10.10:20000/com.ikurento.user.UserProvider") + url, _ := common.NewURL(mockCommonDubboUrl) BeginCount(url, "test") urlStatus := GetURLStatus(url) methodStatus := GetMethodStatus(url, "test") @@ -47,7 +51,7 @@ func TestBeginCount(t *testing.T) { func TestEndCount(t *testing.T) { defer CleanAllStatus() - url, _ := common.NewURL("dubbo://192.168.10.10:20000/com.ikurento.user.UserProvider") + url, _ := common.NewURL(mockCommonDubboUrl) EndCount(url, "test", 100, true) urlStatus := GetURLStatus(url) methodStatus := GetMethodStatus(url, "test") @@ -60,7 +64,7 @@ func TestEndCount(t *testing.T) { func TestGetMethodStatus(t *testing.T) { defer CleanAllStatus() - url, _ := common.NewURL("dubbo://192.168.10.10:20000/com.ikurento.user.UserProvider") + url, _ := common.NewURL(mockCommonDubboUrl) status := GetMethodStatus(url, "test") assert.NotNil(t, status) assert.Equal(t, int32(0), status.total) @@ -69,25 +73,25 @@ func TestGetMethodStatus(t *testing.T) { func TestGetUrlStatus(t *testing.T) { defer CleanAllStatus() - url, _ := common.NewURL("dubbo://192.168.10.10:20000/com.ikurento.user.UserProvider") + url, _ := common.NewURL(mockCommonDubboUrl) status := GetURLStatus(url) assert.NotNil(t, status) assert.Equal(t, int32(0), status.total) } -func Test_beginCount0(t *testing.T) { +func TestbeginCount0(t *testing.T) { defer CleanAllStatus() - url, _ := common.NewURL("dubbo://192.168.10.10:20000/com.ikurento.user.UserProvider") + url, _ := common.NewURL(mockCommonDubboUrl) status := GetURLStatus(url) beginCount0(status) assert.Equal(t, int32(1), status.active) } -func Test_All(t *testing.T) { +func TestAll(t *testing.T) { defer CleanAllStatus() - url, _ := common.NewURL("dubbo://192.168.10.10:20000/com.ikurento.user.UserProvider") + url, _ := common.NewURL(mockCommonDubboUrl) request(url, "test", 100, false, true) urlStatus := GetURLStatus(url) methodStatus := GetMethodStatus(url, "test") diff --git a/remoting/etcdv3/client_test.go b/remoting/etcdv3/client_test.go index 287d93e30dd125d743bf718dcdab574a4b5a4afc..60f5968c6ac0f5b608dc2b1ca59e78590441f6f3 100644 --- a/remoting/etcdv3/client_test.go +++ b/remoting/etcdv3/client_test.go @@ -154,7 +154,7 @@ func (suite *ClientTestSuite) TestClientValid() { c := suite.client t := suite.T() - if c.Valid() != true { + if !c.Valid() { t.Fatal("client is not valid") } c.Close() @@ -174,7 +174,7 @@ func (suite *ClientTestSuite) TestClientDone() { c.Wait.Wait() - if c.Valid() == true { + if c.Valid() { suite.T().Fatal("client should be invalid then") } } diff --git a/remoting/etcdv3/facade.go b/remoting/etcdv3/facade.go index 3f5999fdf3c5a0791d780e8f5521ef3ea51e9372..2edbb6650890d6d655d8356e1c0a2979a022f0a8 100644 --- a/remoting/etcdv3/facade.go +++ b/remoting/etcdv3/facade.go @@ -85,10 +85,8 @@ LOOP: ) logger.Infof("ETCDV3ProviderRegistry.validateETCDV3Client(etcd Addr{%s}) = error{%#v}", endpoint, perrors.WithStack(err)) - if err == nil { - if r.RestartCallBack() { - break - } + if err == nil && r.RestartCallBack() { + break } failTimes++ if MaxFailTimes <= failTimes { diff --git a/remoting/kubernetes/client_test.go b/remoting/kubernetes/client_test.go index e116c48b1aa85b9b2331045dfbc42891aee1f2e1..d6c5a2e88057459c0a87cd9a607e9c10970b07b2 100644 --- a/remoting/kubernetes/client_test.go +++ b/remoting/kubernetes/client_test.go @@ -59,6 +59,9 @@ var tests = []struct { // test dataset prefix const prefix = "name" +var ( + watcherStopLog = "the watcherSet watcher was stopped" +) var clientPodListJsonData = `{ "apiVersion": "v1", "items": [ @@ -258,12 +261,12 @@ func TestClientValid(t *testing.T) { client := getTestClient(t) defer client.Close() - if client.Valid() != true { + if !client.Valid() { t.Fatal("client is not valid") } client.Close() - if client.Valid() != false { + if client.Valid() { t.Fatal("client is valid") } } @@ -278,7 +281,7 @@ func TestClientDone(t *testing.T) { <-client.Done() - if client.Valid() == true { + if client.Valid() { t.Fatal("client should be invalid") } } @@ -331,7 +334,7 @@ func TestClientGetChildrenKVList(t *testing.T) { return } case <-done: - t.Log("the watcherSet watcher was stopped") + t.Log(watcherStopLog) return } } @@ -399,7 +402,7 @@ func TestClientWatchPrefix(t *testing.T) { case e := <-wc: t.Logf("got event %v k %s v %s", e.EventType, e.Key, e.Value) case <-done: - t.Log("the watcherSet watcher was stopped") + t.Log(watcherStopLog) return } } @@ -441,7 +444,7 @@ func TestClientWatch(t *testing.T) { case e := <-wc: t.Logf("got event %v k %s v %s", e.EventType, e.Key, e.Value) case <-done: - t.Log("the watcherSet watcher was stopped") + t.Log(watcherStopLog) return } } diff --git a/remoting/kubernetes/facade_test.go b/remoting/kubernetes/facade_test.go index 4323c0ec565d64f445f15c3e5c265451b2b87ce7..65c5d715a38bd0862245255e0276ff5e959de3a3 100644 --- a/remoting/kubernetes/facade_test.go +++ b/remoting/kubernetes/facade_test.go @@ -48,6 +48,7 @@ func (r *mockFacade) GetUrl() common.URL { } func (r *mockFacade) Destroy() { + // TODO implementation me } func (r *mockFacade) RestartCallBack() bool { diff --git a/remoting/zookeeper/facade.go b/remoting/zookeeper/facade.go index 10de42523e731d0780ff7132f4655850409135aa..f9b9332504f445724a54b94356771e4ad49b62f0 100644 --- a/remoting/zookeeper/facade.go +++ b/remoting/zookeeper/facade.go @@ -78,10 +78,8 @@ LOOP: err = ValidateZookeeperClient(r, WithZkName(zkName)) logger.Infof("ZkProviderRegistry.validateZookeeperClient(zkAddr{%s}) = error{%#v}", zkAddress, perrors.WithStack(err)) - if err == nil { - if r.RestartCallBack() { - break - } + if err == nil && r.RestartCallBack() { + break } failTimes++ if MaxFailTimes <= failTimes { diff --git a/remoting/zookeeper/listener.go b/remoting/zookeeper/listener.go index a8ac55ba6c47115ae1d761a5d465f41925475342..e4de429e21b5ae17ba7180eca1301e896d4ada47 100644 --- a/remoting/zookeeper/listener.go +++ b/remoting/zookeeper/listener.go @@ -247,8 +247,14 @@ func (l *ZkEventListener) listenDirEvent(conf *common.URL, zkPath string, listen l.pathMapLock.Lock() l.pathMap[dubboPath] = struct{}{} l.pathMapLock.Unlock() - + //When Zk disconnected, the Conn will be set to nil, so here need check the value of Conn + l.client.RLock() + if l.client.Conn == nil { + l.client.RUnlock() + break + } content, _, err := l.client.Conn.Get(dubboPath) + l.client.RUnlock() if err != nil { logger.Errorf("Get new node path {%v} 's content error,message is {%v}", dubboPath, perrors.WithStack(err)) } diff --git a/remoting/zookeeper/listener_test.go b/remoting/zookeeper/listener_test.go index ba7d6ba81b6af97dc5ad3788e8399d08cbe5b2bb..37ef1b4b967d2f6708a4a099875ae90f273ae483 100644 --- a/remoting/zookeeper/listener_test.go +++ b/remoting/zookeeper/listener_test.go @@ -32,6 +32,10 @@ import ( "github.com/apache/dubbo-go/remoting" ) +var ( + dubboPropertiesPath = "/dubbo/dubbo.properties" +) + func initZkData(t *testing.T) (*zk.TestCluster, *ZookeeperClient, <-chan zk.Event) { ts, client, event, err := NewMockZookeeperClient("test", 15*time.Second) assert.NoError(t, err) @@ -58,10 +62,10 @@ func initZkData(t *testing.T) (*zk.TestCluster, *ZookeeperClient, <-chan zk.Even dubbo.service.com.ikurento.user.UserProvider.cluster=failover ` - err = client.Create("/dubbo/dubbo.properties") + err = client.Create(dubboPropertiesPath) assert.NoError(t, err) - _, err = client.Conn.Set("/dubbo/dubbo.properties", []byte(data), 0) + _, err = client.Conn.Set(dubboPropertiesPath, []byte(data), 0) assert.NoError(t, err) return ts, client, event @@ -99,7 +103,7 @@ func TestListener(t *testing.T) { dataListener := &mockDataListener{client: client, changedData: changedData, wait: &wait} listener.ListenServiceEvent(nil, "/dubbo", dataListener) time.Sleep(1 * time.Second) - _, err := client.Conn.Set("/dubbo/dubbo.properties", []byte(changedData), 1) + _, err := client.Conn.Set(dubboPropertiesPath, []byte(changedData), 1) assert.NoError(t, err) wait.Wait() assert.Equal(t, changedData, dataListener.eventList[1].Content)