diff --git a/cluster/cluster_impl/base_cluster_invoker.go b/cluster/cluster_impl/base_cluster_invoker.go index 0ac851f72752ab7f91ff3cd7bc9a9e462a927c57..ed30559ed3c4b3930e65d6e66d5e91d8619516a1 100644 --- a/cluster/cluster_impl/base_cluster_invoker.go +++ b/cluster/cluster_impl/base_cluster_invoker.go @@ -51,7 +51,7 @@ func newBaseClusterInvoker(directory cluster.Directory) baseClusterInvoker { } } -func (invoker *baseClusterInvoker) GetUrl() common.URL { +func (invoker *baseClusterInvoker) GetUrl() *common.URL { return invoker.directory.GetUrl() } diff --git a/cluster/cluster_impl/failover_cluster_test.go b/cluster/cluster_impl/failover_cluster_test.go index d3ac2c8a5ffd7fce647649c53fe343ba93999636..3ea6232d4747f722c5a933cc056ff06304913965 100644 --- a/cluster/cluster_impl/failover_cluster_test.go +++ b/cluster/cluster_impl/failover_cluster_test.go @@ -45,7 +45,7 @@ import ( // nolint type MockInvoker struct { - url common.URL + url *common.URL available bool destroyed bool @@ -53,7 +53,7 @@ type MockInvoker struct { } // nolint -func NewMockInvoker(url common.URL, successCount int) *MockInvoker { +func NewMockInvoker(url *common.URL, successCount int) *MockInvoker { return &MockInvoker{ url: url, available: true, @@ -63,7 +63,7 @@ func NewMockInvoker(url common.URL, successCount int) *MockInvoker { } // nolint -func (bi *MockInvoker) GetUrl() common.URL { +func (bi *MockInvoker) GetUrl() *common.URL { return bi.url } diff --git a/cluster/directory/base_directory.go b/cluster/directory/base_directory.go index 20db1f2b7de71c843caf7c7abda39e40c68e4ecd..d1025a152b599d70c40bba5bc16009d8d5adee37 100644 --- a/cluster/directory/base_directory.go +++ b/cluster/directory/base_directory.go @@ -65,8 +65,8 @@ func (dir *BaseDirectory) SetRouterChain(routerChain router.Chain) { } // GetUrl Get URL -func (dir *BaseDirectory) GetUrl() common.URL { - return *dir.url +func (dir *BaseDirectory) GetUrl() *common.URL { + return dir.url } // GetDirectoryUrl Get URL instance diff --git a/cluster/directory/base_directory_test.go b/cluster/directory/base_directory_test.go index e51e533f2e27ac8fbb6e4b19e8a32e6be2025855..16e3c5a960912af66739bcc1c5736d44d437503e 100644 --- a/cluster/directory/base_directory_test.go +++ b/cluster/directory/base_directory_test.go @@ -40,19 +40,16 @@ var ( ) func TestNewBaseDirectory(t *testing.T) { - directory := NewBaseDirectory(&url) - assert.NotNil(t, directory) - assert.Equal(t, url, directory.GetUrl()) - assert.Equal(t, &url, directory.GetDirectoryUrl()) + dir := NewBaseDirectory(url) + assert.Equal(t, url, dir.GetUrl()) + assert.Equal(t, url, dir.GetDirectoryUrl()) } func TestBuildRouterChain(t *testing.T) { regURL := url regURL.AddParam(constant.INTERFACE_KEY, "mock-app") - directory := NewBaseDirectory(®URL) - - assert.NotNil(t, directory) + directory := NewBaseDirectory(regURL) localIP := common.GetLocalIp() rule := base64.URLEncoding.EncodeToString([]byte("true => " + " host = " + localIP)) @@ -66,18 +63,18 @@ func TestBuildRouterChain(t *testing.T) { assert.NotNil(t, chain) } -func getRouteURL(rule string, u common.URL) *common.URL { +func getRouteURL(rule string, u *common.URL) *common.URL { ru := u ru.AddParam("rule", rule) ru.AddParam("force", "true") ru.AddParam(constant.ROUTER_KEY, "router") - return &ru + return ru } func TestIsProperRouter(t *testing.T) { regURL := url regURL.AddParam(constant.APPLICATION_KEY, "mock-app") - d := NewBaseDirectory(®URL) + d := NewBaseDirectory(regURL) localIP := common.GetLocalIp() rule := base64.URLEncoding.EncodeToString([]byte("true => " + " host = " + localIP)) routeURL := getRouteURL(rule, anyURL) @@ -87,7 +84,7 @@ func TestIsProperRouter(t *testing.T) { regURL.AddParam(constant.APPLICATION_KEY, "") regURL.AddParam(constant.INTERFACE_KEY, "com.foo.BarService") - d = NewBaseDirectory(®URL) + d = NewBaseDirectory(regURL) routeURL = getRouteURL(rule, anyURL) routeURL.AddParam(constant.INTERFACE_KEY, "com.foo.BarService") rst = d.isProperRouter(routeURL) @@ -95,14 +92,14 @@ func TestIsProperRouter(t *testing.T) { regURL.AddParam(constant.APPLICATION_KEY, "") regURL.AddParam(constant.INTERFACE_KEY, "") - d = NewBaseDirectory(®URL) + d = NewBaseDirectory(regURL) routeURL = getRouteURL(rule, anyURL) rst = d.isProperRouter(routeURL) assert.True(t, rst) regURL.SetParam(constant.APPLICATION_KEY, "") regURL.SetParam(constant.INTERFACE_KEY, "") - d = NewBaseDirectory(®URL) + d = NewBaseDirectory(regURL) routeURL = getRouteURL(rule, anyURL) routeURL.AddParam(constant.APPLICATION_KEY, "mock-service") rst = d.isProperRouter(routeURL) @@ -110,7 +107,7 @@ func TestIsProperRouter(t *testing.T) { regURL.SetParam(constant.APPLICATION_KEY, "") regURL.SetParam(constant.INTERFACE_KEY, "") - d = NewBaseDirectory(®URL) + d = NewBaseDirectory(regURL) routeURL = getRouteURL(rule, anyURL) routeURL.AddParam(constant.INTERFACE_KEY, "mock-service") rst = d.isProperRouter(routeURL) diff --git a/cluster/directory/static_directory.go b/cluster/directory/static_directory.go index 6d75dff5da09cc18828c9105d257c8f80b8de885..d9695d46b3d25dd89a80e10c2396e650492840ad 100644 --- a/cluster/directory/static_directory.go +++ b/cluster/directory/static_directory.go @@ -34,13 +34,13 @@ type staticDirectory struct { // NewStaticDirectory Create a new staticDirectory with invokers func NewStaticDirectory(invokers []protocol.Invoker) *staticDirectory { - var url common.URL + var url *common.URL if len(invokers) > 0 { url = invokers[0].GetUrl() } dir := &staticDirectory{ - BaseDirectory: NewBaseDirectory(&url), + BaseDirectory: NewBaseDirectory(url), invokers: invokers, } @@ -72,7 +72,7 @@ func (dir *staticDirectory) List(invocation protocol.Invocation) []protocol.Invo return invokers } dirUrl := dir.GetUrl() - return routerChain.Route(&dirUrl, invocation) + return routerChain.Route(dirUrl, invocation) } // Destroy Destroy @@ -91,7 +91,7 @@ func (dir *staticDirectory) BuildRouterChain(invokers []protocol.Invoker) error return perrors.Errorf("invokers == null") } url := invokers[0].GetUrl() - routerChain, e := chain.NewRouterChain(&url) + routerChain, e := chain.NewRouterChain(url) if e != nil { return e } diff --git a/cluster/loadbalance/consistent_hash_test.go b/cluster/loadbalance/consistent_hash_test.go index 9f22d39dc46243dddda89151e07dbea39ab933fb..0fbb74059cf0af6cf7e75aab646d7c5c146bcc28 100644 --- a/cluster/loadbalance/consistent_hash_test.go +++ b/cluster/loadbalance/consistent_hash_test.go @@ -84,9 +84,9 @@ func TestConsistentHashLoadBalanceSuite(t *testing.T) { type consistentHashLoadBalanceSuite struct { suite.Suite - url1 common.URL - url2 common.URL - url3 common.URL + url1 *common.URL + url2 *common.URL + url3 *common.URL invokers []protocol.Invoker invoker1 protocol.Invoker invoker2 protocol.Invoker diff --git a/cluster/router/chain/chain.go b/cluster/router/chain/chain.go index 252093af0b52873281511b5fa6d50cc8bb685d52..612c12d87d463a86c6f9f85d4167100f55bf25ab 100644 --- a/cluster/router/chain/chain.go +++ b/cluster/router/chain/chain.go @@ -55,7 +55,7 @@ type RouterChain struct { mutex sync.RWMutex - url common.URL + url *common.URL // The times of address notification since last update for address cache count int64 @@ -215,7 +215,7 @@ func (c *RouterChain) buildCache() { } // URL Return URL in RouterChain -func (c *RouterChain) URL() common.URL { +func (c *RouterChain) URL() *common.URL { return c.url } @@ -248,7 +248,7 @@ func NewRouterChain(url *common.URL) (*RouterChain, error) { notify: make(chan struct{}), } if url != nil { - chain.url = *url + chain.url = url } go chain.loop() diff --git a/cluster/router/chain/chain_test.go b/cluster/router/chain/chain_test.go index 5a9f2d1c74db847df56b1ebab609b65c0cbd7484..b21990b08c5b960c407a395cddf7ef7518ba5822 100644 --- a/cluster/router/chain/chain_test.go +++ b/cluster/router/chain/chain_test.go @@ -65,7 +65,6 @@ func TestNewRouterChain(t *testing.T) { assert.NoError(t, err) err = z.Create(path) assert.NoError(t, err) - testyml := `scope: application key: mock-app enabled: true @@ -81,7 +80,7 @@ conditions: defer z.Close() zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, localIP, ts.Servers[0].Port)) - configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(&zkUrl) + configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(zkUrl) config.GetEnvInstance().SetDynamicConfiguration(configuration) assert.Nil(t, err) @@ -133,7 +132,7 @@ conditions: defer z.Close() zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, localIP, ts.Servers[0].Port)) - configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(&zkUrl) + configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(zkUrl) config.GetEnvInstance().SetDynamicConfiguration(configuration) chain, err := NewRouterChain(getConditionRouteUrl(applicationKey)) @@ -159,7 +158,7 @@ func TestRouterChainRoute(t *testing.T) { defer z.Close() zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, localIP, ts.Servers[0].Port)) - configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(&zkUrl) + configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(zkUrl) config.GetEnvInstance().SetDynamicConfiguration(configuration) chain, err := NewRouterChain(getConditionRouteUrl(applicationKey)) @@ -169,7 +168,7 @@ func TestRouterChainRoute(t *testing.T) { url := getConditionRouteUrl(applicationKey) assert.NotNil(t, url) - invokers := []protocol.Invoker{} + var invokers []protocol.Invoker dubboURL, _ := common.NewURL(fmt.Sprintf(dubboForamt, test1234IP, port20000)) invokers = append(invokers, protocol.NewBaseInvoker(dubboURL)) chain.SetInvokers(invokers) @@ -177,7 +176,7 @@ func TestRouterChainRoute(t *testing.T) { targetURL, _ := common.NewURL(fmt.Sprintf(consumerFormat, test1111IP)) inv := &invocation.RPCInvocation{} - finalInvokers := chain.Route(&targetURL, inv) + finalInvokers := chain.Route(targetURL, inv) assert.Equal(t, 1, len(finalInvokers)) } @@ -203,14 +202,14 @@ conditions: defer z.Close() zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, localIP, ts.Servers[0].Port)) - configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(&zkUrl) + configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(zkUrl) config.GetEnvInstance().SetDynamicConfiguration(configuration) chain, err := NewRouterChain(getConditionRouteUrl(applicationKey)) assert.Nil(t, err) assert.Equal(t, 2, len(chain.routers)) - invokers := []protocol.Invoker{} + var invokers []protocol.Invoker dubboURL, _ := common.NewURL(fmt.Sprintf(dubboForamt, test1234IP, port20000)) invokers = append(invokers, protocol.NewBaseInvoker(dubboURL)) chain.SetInvokers(invokers) @@ -218,7 +217,7 @@ conditions: targetURL, _ := common.NewURL(fmt.Sprintf(consumerFormat, test1111IP)) inv := &invocation.RPCInvocation{} - finalInvokers := chain.Route(&targetURL, inv) + finalInvokers := chain.Route(targetURL, inv) assert.Equal(t, 0, len(finalInvokers)) } @@ -229,7 +228,7 @@ func TestRouterChainRouteNoRoute(t *testing.T) { defer z.Close() zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, localIP, ts.Servers[0].Port)) - configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(&zkUrl) + configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(zkUrl) config.GetEnvInstance().SetDynamicConfiguration(configuration) chain, err := NewRouterChain(getConditionNoRouteUrl(applicationKey)) @@ -239,7 +238,7 @@ func TestRouterChainRouteNoRoute(t *testing.T) { url := getConditionRouteUrl(applicationKey) assert.NotNil(t, url) - invokers := []protocol.Invoker{} + var invokers []protocol.Invoker dubboURL, _ := common.NewURL(fmt.Sprintf(dubboForamt, test1234IP, port20000)) invokers = append(invokers, protocol.NewBaseInvoker(dubboURL)) chain.SetInvokers(invokers) @@ -247,7 +246,7 @@ func TestRouterChainRouteNoRoute(t *testing.T) { targetURL, _ := common.NewURL(fmt.Sprintf(consumerFormat, test1111IP)) inv := &invocation.RPCInvocation{} - finalInvokers := chain.Route(&targetURL, inv) + finalInvokers := chain.Route(targetURL, inv) assert.Equal(t, 0, len(finalInvokers)) } @@ -258,7 +257,7 @@ func getConditionNoRouteUrl(applicationKey string) *common.URL { 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 + return url } func getConditionRouteUrl(applicationKey string) *common.URL { @@ -267,12 +266,12 @@ func getConditionRouteUrl(applicationKey string) *common.URL { 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 + return url } func getRouteUrl(applicationKey string) *common.URL { url, _ := common.NewURL(fmt.Sprintf(anyUrlFormat, test0000IP)) url.AddParam(applicationField, applicationKey) url.AddParam(forceField, forceValue) - return &url + return url } diff --git a/cluster/router/condition/app_router_test.go b/cluster/router/condition/app_router_test.go index cce96b12c95a691e828d91ba3d0629ddb6421954..879abc5cc8b607ee9245ce632800b056ff740cc5 100644 --- a/cluster/router/condition/app_router_test.go +++ b/cluster/router/condition/app_router_test.go @@ -71,7 +71,7 @@ conditions: defer z.Close() zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, routerLocalIP, ts.Servers[0].Port)) - configuration, err := extension.GetConfigCenterFactory(routerZk).GetDynamicConfiguration(&zkUrl) + configuration, err := extension.GetConfigCenterFactory(routerZk).GetDynamicConfiguration(zkUrl) config.GetEnvInstance().SetDynamicConfiguration(configuration) assert.Nil(t, err) @@ -119,7 +119,7 @@ conditions: defer z.Close() zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, routerLocalIP, ts.Servers[0].Port)) - configuration, err := extension.GetConfigCenterFactory(routerZk).GetDynamicConfiguration(&zkUrl) + configuration, err := extension.GetConfigCenterFactory(routerZk).GetDynamicConfiguration(zkUrl) config.GetEnvInstance().SetDynamicConfiguration(configuration) assert.Nil(t, err) @@ -158,7 +158,7 @@ conditions: defer z.Close() zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, routerLocalIP, ts.Servers[0].Port)) - configuration, err := extension.GetConfigCenterFactory(routerZk).GetDynamicConfiguration(&zkUrl) + configuration, err := extension.GetConfigCenterFactory(routerZk).GetDynamicConfiguration(zkUrl) config.GetEnvInstance().SetDynamicConfiguration(configuration) assert.Nil(t, err) @@ -194,5 +194,5 @@ func getAppRouteURL(applicationKey string) *common.URL { url, _ := common.NewURL(fmt.Sprintf(conditionFormat, constant.ANYHOST_VALUE)) url.AddParam("application", applicationKey) url.AddParam("force", "true") - return &url + return url } diff --git a/cluster/router/condition/factory_test.go b/cluster/router/condition/factory_test.go index 8fdfae7404e25179350bd2d2279bb0f1a21169fc..c916588eeeef68b796c35ee6b3b175e8de859863 100644 --- a/cluster/router/condition/factory_test.go +++ b/cluster/router/condition/factory_test.go @@ -52,13 +52,13 @@ const ( ) type MockInvoker struct { - url common.URL + url *common.URL available bool destroyed bool successCount int } -func NewMockInvoker(url common.URL, successCount int) *MockInvoker { +func NewMockInvoker(url *common.URL, successCount int) *MockInvoker { return &MockInvoker{ url: url, available: true, @@ -67,7 +67,7 @@ func NewMockInvoker(url common.URL, successCount int) *MockInvoker { } } -func (bi *MockInvoker) GetUrl() common.URL { +func (bi *MockInvoker) GetUrl() *common.URL { return bi.url } @@ -75,20 +75,20 @@ func getRouteUrl(rule string) *common.URL { url, _ := common.NewURL(fmt.Sprintf(factoryUrlFormat, constant.ANYHOST_VALUE)) url.AddParam("rule", rule) url.AddParam("force", "true") - return &url + return url } func getRouteUrlWithForce(rule, force string) *common.URL { url, _ := common.NewURL(fmt.Sprintf(factoryUrlFormat, constant.ANYHOST_VALUE)) url.AddParam("rule", rule) url.AddParam("force", force) - return &url + return url } func getRouteUrlWithNoForce(rule string) *common.URL { url, _ := common.NewURL(fmt.Sprintf(factoryUrlFormat, constant.ANYHOST_VALUE)) url.AddParam("rule", rule) - return &url + return url } func (bi *MockInvoker) IsAvailable() bool { @@ -134,31 +134,31 @@ func TestRoute_matchWhen(t *testing.T) { rule := base64.URLEncoding.EncodeToString([]byte("=> host = 1.2.3.4")) router, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule)) cUrl, _ := common.NewURL(fmt.Sprintf(factoryDubboFormat, factory1111Ip)) - matchWhen := router.(*ConditionRouter).MatchWhen(&cUrl, inv) + 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().NewPriorityRouter(getRouteUrl(rule1)) - matchWhen1 := router1.(*ConditionRouter).MatchWhen(&cUrl, inv) + 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().NewPriorityRouter(getRouteUrl(rule2)) - matchWhen2 := router2.(*ConditionRouter).MatchWhen(&cUrl, inv) + 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().NewPriorityRouter(getRouteUrl(rule3)) - matchWhen3 := router3.(*ConditionRouter).MatchWhen(&cUrl, inv) + 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().NewPriorityRouter(getRouteUrl(rule4)) - matchWhen4 := router4.(*ConditionRouter).MatchWhen(&cUrl, inv) + 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().NewPriorityRouter(getRouteUrl(rule5)) - matchWhen5 := router5.(*ConditionRouter).MatchWhen(&cUrl, inv) + 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().NewPriorityRouter(getRouteUrl(rule6)) - matchWhen6 := router6.(*ConditionRouter).MatchWhen(&cUrl, inv) + matchWhen6 := router6.(*ConditionRouter).MatchWhen(cUrl, inv) assert.Equal(t, true, matchWhen6) } @@ -182,12 +182,12 @@ func TestRoute_matchFilter(t *testing.T) { router5, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule5)) router6, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule6)) cUrl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP)) - ret1 := router1.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &cUrl, &invocation.RPCInvocation{}) - ret2 := router2.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &cUrl, &invocation.RPCInvocation{}) - ret3 := router3.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &cUrl, &invocation.RPCInvocation{}) - ret4 := router4.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &cUrl, &invocation.RPCInvocation{}) - ret5 := router5.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &cUrl, &invocation.RPCInvocation{}) - ret6 := router6.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &cUrl, &invocation.RPCInvocation{}) + ret1 := router1.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), cUrl, &invocation.RPCInvocation{}) + ret2 := router2.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), cUrl, &invocation.RPCInvocation{}) + ret3 := router3.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), cUrl, &invocation.RPCInvocation{}) + ret4 := router4.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), cUrl, &invocation.RPCInvocation{}) + ret5 := router5.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), cUrl, &invocation.RPCInvocation{}) + ret6 := router6.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), cUrl, &invocation.RPCInvocation{}) assert.Equal(t, 1, len(ret1.ToArray())) assert.Equal(t, 0, len(ret2.ToArray())) assert.Equal(t, 0, len(ret3.ToArray())) @@ -202,20 +202,20 @@ func TestRoute_methodRoute(t *testing.T) { 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")) r, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule)) url, _ := common.NewURL("consumer://1.1.1.1/com.foo.BarService?methods=setFoo,getFoo,findFoo") - matchWhen := r.(*ConditionRouter).MatchWhen(&url, inv) + matchWhen := r.(*ConditionRouter).MatchWhen(url, inv) assert.Equal(t, true, matchWhen) url1, _ := common.NewURL(fmt.Sprintf(factoryConsumerMethodFormat, factory1111Ip)) - matchWhen = r.(*ConditionRouter).MatchWhen(&url1, inv) + matchWhen = r.(*ConditionRouter).MatchWhen(url1, inv) assert.Equal(t, true, matchWhen) 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().NewPriorityRouter(getRouteUrl(rule2)) - matchWhen = router2.(*ConditionRouter).MatchWhen(&url2, inv) + matchWhen = router2.(*ConditionRouter).MatchWhen(url2, inv) assert.Equal(t, false, matchWhen) 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().NewPriorityRouter(getRouteUrl(rule3)) - matchWhen = router3.(*ConditionRouter).MatchWhen(&url3, inv) + matchWhen = router3.(*ConditionRouter).MatchWhen(url3, inv) assert.Equal(t, true, matchWhen) } @@ -228,7 +228,7 @@ func TestRoute_ReturnFalse(t *testing.T) { rule := base64.URLEncoding.EncodeToString([]byte("host = " + localIP + " => false")) curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP)) r, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule)) - ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &curl, inv) + ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), curl, inv) assert.Equal(t, 0, len(ret.ToArray())) } @@ -240,7 +240,7 @@ func TestRoute_ReturnEmpty(t *testing.T) { rule := base64.URLEncoding.EncodeToString([]byte("host = " + localIP + " => ")) curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP)) r, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule)) - ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &curl, inv) + ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), curl, inv) assert.Equal(t, 0, len(ret.ToArray())) } @@ -256,7 +256,7 @@ func TestRoute_ReturnAll(t *testing.T) { rule := base64.URLEncoding.EncodeToString([]byte("host = " + localIP + " => " + " host = " + localIP)) curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP)) r, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule)) - ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &curl, inv) + ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), curl, inv) assert.Equal(t, len(invokers), len(ret.ToArray())) } @@ -273,7 +273,7 @@ func TestRoute_HostFilter(t *testing.T) { rule := base64.URLEncoding.EncodeToString([]byte("host = " + localIP + " => " + " host = " + localIP)) curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP)) r, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule)) - ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &curl, inv) + ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), curl, inv) assert.Equal(t, 2, len(ret.ToArray())) assert.Equal(t, invoker2, invokers[ret.ToArray()[0]]) assert.Equal(t, invoker3, invokers[ret.ToArray()[1]]) @@ -292,7 +292,7 @@ func TestRoute_Empty_HostFilter(t *testing.T) { rule := base64.URLEncoding.EncodeToString([]byte(" => " + " host = " + localIP)) curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP)) r, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule)) - ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &curl, inv) + ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), curl, inv) assert.Equal(t, 2, len(ret.ToArray())) assert.Equal(t, invoker2, invokers[ret.ToArray()[0]]) assert.Equal(t, invoker3, invokers[ret.ToArray()[1]]) @@ -311,7 +311,7 @@ func TestRoute_False_HostFilter(t *testing.T) { rule := base64.URLEncoding.EncodeToString([]byte("true => " + " host = " + localIP)) curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP)) r, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule)) - ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &curl, inv) + ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), curl, inv) assert.Equal(t, 2, len(ret.ToArray())) assert.Equal(t, invoker2, invokers[ret.ToArray()[0]]) assert.Equal(t, invoker3, invokers[ret.ToArray()[1]]) @@ -330,7 +330,7 @@ func TestRoute_Placeholder(t *testing.T) { rule := base64.URLEncoding.EncodeToString([]byte("host = " + localIP + " => " + " host = $host")) curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP)) r, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule)) - ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &curl, inv) + ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), curl, inv) assert.Equal(t, 2, len(ret.ToArray())) assert.Equal(t, invoker2, invokers[ret.ToArray()[0]]) assert.Equal(t, invoker3, invokers[ret.ToArray()[1]]) @@ -349,7 +349,7 @@ func TestRoute_NoForce(t *testing.T) { rule := base64.URLEncoding.EncodeToString([]byte(fmt.Sprintf(factoryHostIp1234Format, localIP))) curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP)) r, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrlWithNoForce(rule)) - ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &curl, inv) + ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), curl, inv) assert.Equal(t, len(invokers), len(ret.ToArray())) } @@ -366,7 +366,7 @@ func TestRoute_Force(t *testing.T) { rule := base64.URLEncoding.EncodeToString([]byte(fmt.Sprintf(factoryHostIp1234Format, localIP))) curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP)) r, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrlWithForce(rule, "true")) - fileredInvokers := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &curl, inv) + fileredInvokers := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), curl, inv) assert.Equal(t, 0, len(fileredInvokers.ToArray())) } diff --git a/cluster/router/condition/file.go b/cluster/router/condition/file.go index 996db7443faff88d3baa1a2363f98fa62623d121..a97d9cb83b9c176a353a3851c5590df91eb22730 100644 --- a/cluster/router/condition/file.go +++ b/cluster/router/condition/file.go @@ -39,7 +39,7 @@ import ( type FileConditionRouter struct { listenableRouter parseOnce sync.Once - url common.URL + url *common.URL } // NewFileConditionRouter Create file condition router instance with content ( from config file) @@ -60,11 +60,11 @@ func NewFileConditionRouter(content []byte) (*FileConditionRouter, error) { } // URL Return URL in file condition router n -func (f *FileConditionRouter) URL() common.URL { +func (f *FileConditionRouter) URL() *common.URL { f.parseOnce.Do(func() { routerRule := f.routerRule rule := parseCondition(routerRule.Conditions) - f.url = *common.NewURLWithOptions( + f.url = common.NewURLWithOptions( common.WithProtocol(constant.CONDITION_ROUTE_PROTOCOL), common.WithIp(constant.ANYHOST_VALUE), common.WithParams(url.Values{}), diff --git a/cluster/router/condition/listenable_router.go b/cluster/router/condition/listenable_router.go index 19e3a00bf6f592a14c867ae580946bd3b94f4bea..0b47310dbfe9987a593bc2d0d949a76f08052114 100644 --- a/cluster/router/condition/listenable_router.go +++ b/cluster/router/condition/listenable_router.go @@ -148,6 +148,6 @@ func (l *listenableRouter) Priority() int64 { } // URL Return URL in listenable router -func (l *listenableRouter) URL() common.URL { - return *l.url +func (l *listenableRouter) URL() *common.URL { + return l.url } diff --git a/cluster/router/condition/router.go b/cluster/router/condition/router.go index 48f2aae133e5c784570dc4b470766b431938efc4..2fc33072d33517810f0c9ab3b8351d7bdcfea8b4 100644 --- a/cluster/router/condition/router.go +++ b/cluster/router/condition/router.go @@ -138,8 +138,8 @@ func (c *ConditionRouter) Priority() int64 { } // URL Return URL in condition router -func (c *ConditionRouter) URL() common.URL { - return *c.url +func (c *ConditionRouter) URL() *common.URL { + return c.url } // Enabled Return is condition router is enabled @@ -173,7 +173,7 @@ func (c *ConditionRouter) Route(invokers *roaring.Bitmap, cache router.Cache, ur index := iter.Next() invoker := cache.GetInvokers()[index] invokerUrl := invoker.GetUrl() - isMatchThen := c.MatchThen(&invokerUrl, url) + isMatchThen := c.MatchThen(invokerUrl, url) if isMatchThen { result.Add(index) } diff --git a/cluster/router/condition/router_rule_test.go b/cluster/router/condition/router_rule_test.go index 369b14f08a6a650b36fe63a2d890c04fe7b892a5..192e5282f6f50c31b1106a5fc547a1616405a22a 100644 --- a/cluster/router/condition/router_rule_test.go +++ b/cluster/router/condition/router_rule_test.go @@ -80,5 +80,5 @@ conditions: func TestIsMatchGlobPattern(t *testing.T) { url, _ := common.NewURL("dubbo://localhost:8080/Foo?key=v*e") - assert.Equal(t, true, isMatchGlobalPattern("$key", "value", &url)) + assert.Equal(t, true, isMatchGlobalPattern("$key", "value", url)) } diff --git a/cluster/router/condition/router_test.go b/cluster/router/condition/router_test.go index c27a1d9552a331d7e67af0eb3d444c480758891e..3d33ca275828b31ed480926d486c5844dac771c6 100644 --- a/cluster/router/condition/router_test.go +++ b/cluster/router/condition/router_test.go @@ -59,7 +59,7 @@ func TestParseRule(t *testing.T) { func TestNewConditionRouter(t *testing.T) { url, _ := common.NewURL(`condition://0.0.0.0:?application=mock-app&category=routers&force=true&priority=1&router=condition&rule=YSAmIGMgPT4gYiAmIGQ%3D`) - router, err := NewConditionRouter(&url) + router, err := NewConditionRouter(url) assert.Nil(t, err) assert.Equal(t, true, router.Enabled()) assert.Equal(t, true, router.Force) @@ -73,16 +73,16 @@ func TestNewConditionRouter(t *testing.T) { assert.Error(t, err) url, _ = common.NewURL(`condition://0.0.0.0:?application=mock-app&category=routers&force=true&priority=1&router=condition&rule=YSAmT4gYiAmIGQ%3D`) - router, err = NewConditionRouter(&url) + router, err = NewConditionRouter(url) assert.Error(t, err) url, _ = common.NewURL(`condition://0.0.0.0:?application=mock-app&category=routers&force=true&router=condition&rule=YSAmIGMgPT4gYiAmIGQ%3D`) - router, err = NewConditionRouter(&url) + router, err = NewConditionRouter(url) assert.Nil(t, err) assert.Equal(t, int64(150), router.Priority()) url, _ = common.NewURL(`condition://0.0.0.0:?category=routers&force=true&interface=mock-service&router=condition&rule=YSAmIGMgPT4gYiAmIGQ%3D`) - router, err = NewConditionRouter(&url) + router, err = NewConditionRouter(url) assert.Nil(t, err) assert.Equal(t, int64(140), router.Priority()) } diff --git a/cluster/router/healthcheck/default_health_check_test.go b/cluster/router/healthcheck/default_health_check_test.go index 5d35ae8e486e3f7b29b2a68a3864ef806a1053c7..39827c5f050a1a5ac9524345b59e37ec23efb90f 100644 --- a/cluster/router/healthcheck/default_health_check_test.go +++ b/cluster/router/healthcheck/default_health_check_test.go @@ -43,7 +43,7 @@ const ( func TestDefaultHealthCheckerIsHealthy(t *testing.T) { defer protocol.CleanAllStatus() url, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1010IP)) - hc := NewDefaultHealthChecker(&url).(*DefaultHealthChecker) + hc := NewDefaultHealthChecker(url).(*DefaultHealthChecker) invoker := NewMockInvoker(url) healthy := hc.IsHealthy(invoker) assert.True(t, healthy) @@ -54,7 +54,7 @@ func TestDefaultHealthCheckerIsHealthy(t *testing.T) { for i := 0; i < 11; i++ { request(url, healthCheckMethodTest, 0, true, false) } - hc = NewDefaultHealthChecker(&url).(*DefaultHealthChecker) + hc = NewDefaultHealthChecker(url).(*DefaultHealthChecker) healthy = hc.IsHealthy(invoker) // the outgoing request is more than OUTSTANDING_REQUEST_COUNT_LIMIT, go to unhealthy assert.False(t, hc.IsHealthy(invoker)) @@ -65,7 +65,7 @@ func TestDefaultHealthCheckerIsHealthy(t *testing.T) { } url.SetParam(constant.SUCCESSIVE_FAILED_REQUEST_THRESHOLD_KEY, "10") url.SetParam(constant.OUTSTANDING_REQUEST_COUNT_LIMIT_KEY, "1000") - hc = NewDefaultHealthChecker(&url).(*DefaultHealthChecker) + hc = NewDefaultHealthChecker(url).(*DefaultHealthChecker) healthy = hc.IsHealthy(invoker) assert.False(t, hc.IsHealthy(invoker)) @@ -78,7 +78,7 @@ func TestDefaultHealthCheckerIsHealthy(t *testing.T) { func TestDefaultHealthCheckerGetCircuitBreakerSleepWindowTime(t *testing.T) { defer protocol.CleanAllStatus() url, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1010IP)) - defaultHc := NewDefaultHealthChecker(&url).(*DefaultHealthChecker) + defaultHc := NewDefaultHealthChecker(url).(*DefaultHealthChecker) // Increase the number of failed requests for i := 0; i < 100; i++ { request(url, healthCheckMethodTest, 1, false, false) @@ -88,7 +88,7 @@ func TestDefaultHealthCheckerGetCircuitBreakerSleepWindowTime(t *testing.T) { // Adjust the threshold size to 1000 url.SetParam(constant.SUCCESSIVE_FAILED_REQUEST_THRESHOLD_KEY, "1000") - sleepWindowTime = NewDefaultHealthChecker(&url).(*DefaultHealthChecker).getCircuitBreakerSleepWindowTime(protocol.GetURLStatus(url)) + sleepWindowTime = NewDefaultHealthChecker(url).(*DefaultHealthChecker).getCircuitBreakerSleepWindowTime(protocol.GetURLStatus(url)) assert.True(t, sleepWindowTime == 0) url1, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1011IP)) @@ -107,7 +107,7 @@ func TestDefaultHealthCheckerGetCircuitBreakerSleepWindowTime(t *testing.T) { func TestDefaultHealthCheckerGetCircuitBreakerTimeout(t *testing.T) { defer protocol.CleanAllStatus() url, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1010IP)) - defaultHc := NewDefaultHealthChecker(&url).(*DefaultHealthChecker) + defaultHc := NewDefaultHealthChecker(url).(*DefaultHealthChecker) timeout := defaultHc.getCircuitBreakerTimeout(protocol.GetURLStatus(url)) assert.True(t, timeout == 0) url1, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1011IP)) @@ -126,7 +126,7 @@ func TestDefaultHealthCheckerGetCircuitBreakerTimeout(t *testing.T) { func TestDefaultHealthCheckerIsCircuitBreakerTripped(t *testing.T) { defer protocol.CleanAllStatus() url, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1010IP)) - defaultHc := NewDefaultHealthChecker(&url).(*DefaultHealthChecker) + defaultHc := NewDefaultHealthChecker(url).(*DefaultHealthChecker) status := protocol.GetURLStatus(url) tripped := defaultHc.isCircuitBreakerTripped(status) assert.False(t, tripped) @@ -142,7 +142,7 @@ func TestDefaultHealthCheckerIsCircuitBreakerTripped(t *testing.T) { func TestNewDefaultHealthChecker(t *testing.T) { defer protocol.CleanAllStatus() url, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1010IP)) - defaultHc := NewDefaultHealthChecker(&url).(*DefaultHealthChecker) + 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)) @@ -150,13 +150,13 @@ func TestNewDefaultHealthChecker(t *testing.T) { 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) + nondefaultHc := NewDefaultHealthChecker(url1).(*DefaultHealthChecker) assert.NotNil(t, nondefaultHc) assert.Equal(t, nondefaultHc.outStandingRequestConutLimit, int32(10)) assert.Equal(t, nondefaultHc.requestSuccessiveFailureThreshold, int32(10)) } -func request(url common.URL, method string, elapsed int64, active, succeeded bool) { +func request(url *common.URL, method string, elapsed int64, active, succeeded bool) { protocol.BeginCount(url, method) if !active { protocol.EndCount(url, method, elapsed, succeeded) diff --git a/cluster/router/healthcheck/factory_test.go b/cluster/router/healthcheck/factory_test.go index e80fd4c4d38dbb1c0f2b14ba1e22971249bc54b6..1e736832cecf07d523960fce8eebcc9248cee0a9 100644 --- a/cluster/router/healthcheck/factory_test.go +++ b/cluster/router/healthcheck/factory_test.go @@ -33,18 +33,18 @@ import ( // nolint type MockInvoker struct { - url common.URL + url *common.URL } // nolint -func NewMockInvoker(url common.URL) *MockInvoker { +func NewMockInvoker(url *common.URL) *MockInvoker { return &MockInvoker{ url: url, } } // nolint -func (bi *MockInvoker) GetUrl() common.URL { +func (bi *MockInvoker) GetUrl() *common.URL { return bi.url } diff --git a/cluster/router/healthcheck/health_check_route.go b/cluster/router/healthcheck/health_check_route.go index 75ad189967ed75b9f6153640f49f29217543ede7..1a878af2127d2c5b979cfdb55ff1c1ec08463fe7 100644 --- a/cluster/router/healthcheck/health_check_route.go +++ b/cluster/router/healthcheck/health_check_route.go @@ -106,8 +106,8 @@ func (r *HealthCheckRouter) Priority() int64 { } // URL Return URL in router -func (r *HealthCheckRouter) URL() common.URL { - return *r.url +func (r *HealthCheckRouter) URL() *common.URL { + return r.url } // HealthyChecker returns the HealthChecker bound to this HealthCheckRouter diff --git a/cluster/router/healthcheck/health_check_route_test.go b/cluster/router/healthcheck/health_check_route_test.go index c321b56156b9ae272048f32ef50eb419add27b03..0730f105b7e010311576fc30adf94c8ad69b9614 100644 --- a/cluster/router/healthcheck/health_check_route_test.go +++ b/cluster/router/healthcheck/health_check_route_test.go @@ -54,7 +54,7 @@ func TestHealthCheckRouterRoute(t *testing.T) { url1, _ := common.NewURL(fmt.Sprintf(healthCheckRouteUrlFormat, healthCheckRoute1010IP)) url2, _ := common.NewURL(fmt.Sprintf(healthCheckRouteUrlFormat, healthCheckRoute1011IP)) url3, _ := common.NewURL(fmt.Sprintf(healthCheckRouteUrlFormat, healthCheckRoute1012IP)) - hcr, _ := NewHealthCheckRouter(&consumerURL) + hcr, _ := NewHealthCheckRouter(consumerURL) var invokers []protocol.Invoker invoker1 := NewMockInvoker(url1) @@ -62,14 +62,14 @@ func TestHealthCheckRouterRoute(t *testing.T) { invoker3 := NewMockInvoker(url3) invokers = append(invokers, invoker1, invoker2, invoker3) inv := invocation.NewRPCInvocation(healthCheckRouteMethodNameTest, nil, nil) - res := hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), &consumerURL, inv) + res := hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), consumerURL, inv) // now all invokers are healthy assert.True(t, len(res.ToArray()) == len(invokers)) for i := 0; i < 10; i++ { request(url1, healthCheckRouteMethodNameTest, 0, false, false) } - res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), &consumerURL, inv) + res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), consumerURL, inv) // invokers1 is unhealthy now assert.True(t, len(res.ToArray()) == 2 && !res.Contains(0)) @@ -78,7 +78,7 @@ func TestHealthCheckRouterRoute(t *testing.T) { request(url2, healthCheckRouteMethodNameTest, 0, false, false) } - res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), &consumerURL, inv) + res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), consumerURL, inv) // only invokers3 is healthy now assert.True(t, len(res.ToArray()) == 1 && !res.Contains(0) && !res.Contains(1)) @@ -88,24 +88,24 @@ func TestHealthCheckRouterRoute(t *testing.T) { request(url3, healthCheckRouteMethodNameTest, 0, false, false) } - res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), &consumerURL, inv) + res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), consumerURL, inv) // now all invokers are unhealthy, so downgraded to all assert.True(t, len(res.ToArray()) == 3) // reset the invoker1 successive failed count, so invoker1 go to healthy request(url1, healthCheckRouteMethodNameTest, 0, false, true) - res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), &consumerURL, inv) + res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), consumerURL, inv) assert.True(t, res.Contains(0)) for i := 0; i < 6; i++ { request(url1, healthCheckRouteMethodNameTest, 0, false, false) } // now all invokers are unhealthy, so downgraded to all again - res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), &consumerURL, inv) + res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), consumerURL, inv) assert.True(t, len(res.ToArray()) == 3) time.Sleep(time.Second * 2) // invoker1 go to healthy again after 2s - res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), &consumerURL, inv) + res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), consumerURL, inv) assert.True(t, res.Contains(0)) } @@ -113,12 +113,12 @@ func TestHealthCheckRouterRoute(t *testing.T) { func TestNewHealthCheckRouter(t *testing.T) { defer protocol.CleanAllStatus() url, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1010IP)) - hcr, _ := NewHealthCheckRouter(&url) + hcr, _ := NewHealthCheckRouter(url) h := hcr.(*HealthCheckRouter) assert.Nil(t, h.checker) url.SetParam(HEALTH_ROUTE_ENABLED_KEY, "true") - hcr, _ = NewHealthCheckRouter(&url) + hcr, _ = NewHealthCheckRouter(url) h = hcr.(*HealthCheckRouter) assert.NotNil(t, h.checker) @@ -130,7 +130,7 @@ func TestNewHealthCheckRouter(t *testing.T) { url.SetParam(constant.CIRCUIT_TRIPPED_TIMEOUT_FACTOR_KEY, "500") url.SetParam(constant.SUCCESSIVE_FAILED_REQUEST_THRESHOLD_KEY, "10") url.SetParam(constant.OUTSTANDING_REQUEST_COUNT_LIMIT_KEY, "1000") - hcr, _ = NewHealthCheckRouter(&url) + hcr, _ = NewHealthCheckRouter(url) h = hcr.(*HealthCheckRouter) dhc = h.checker.(*DefaultHealthChecker) assert.Equal(t, dhc.outStandingRequestConutLimit, int32(1000)) diff --git a/cluster/router/router.go b/cluster/router/router.go index ddca42a01d5d5b56a33b9145926c77a843ea9787..8a19dcf8cc2540ab0a30b8b6de8521e9759012ee 100644 --- a/cluster/router/router.go +++ b/cluster/router/router.go @@ -45,7 +45,7 @@ type router interface { Route(*roaring.Bitmap, Cache, *common.URL, protocol.Invocation) *roaring.Bitmap // URL Return URL in router - URL() common.URL + URL() *common.URL } // Router diff --git a/cluster/router/tag/factory_test.go b/cluster/router/tag/factory_test.go index ee195820c123e1fc67a2c27cd12aaa544650b615..b350bb2a915ce9abae98ba46bda346fba7ad6b5b 100644 --- a/cluster/router/tag/factory_test.go +++ b/cluster/router/tag/factory_test.go @@ -39,7 +39,7 @@ func TestTagRouterFactoryNewRouter(t *testing.T) { u1, err := common.NewURL(fmt.Sprintf(factoryFormat, factoryLocalIP)) assert.Nil(t, err) factory := NewTagRouterFactory() - tagRouter, e := factory.NewPriorityRouter(&u1) + tagRouter, e := factory.NewPriorityRouter(u1) assert.Nil(t, e) assert.NotNil(t, tagRouter) } diff --git a/cluster/router/tag/file.go b/cluster/router/tag/file.go index 0ee43116474905d17328364a40889baef0f8c0d4..94daf1508eb7b3f4d8a8cacdbd6ed634be6852da 100644 --- a/cluster/router/tag/file.go +++ b/cluster/router/tag/file.go @@ -52,13 +52,12 @@ func NewFileTagRouter(content []byte) (*FileTagRouter, error) { return nil, perrors.Errorf("yaml.Unmarshal() failed , error:%v", perrors.WithStack(err)) } fileRouter.routerRule = rule - url := fileRouter.URL() - fileRouter.router, err = NewTagRouter(&url) + fileRouter.router, err = NewTagRouter(fileRouter.URL()) return fileRouter, err } // URL Return URL in file tag router n -func (f *FileTagRouter) URL() common.URL { +func (f *FileTagRouter) URL() *common.URL { f.parseOnce.Do(func() { routerRule := f.routerRule f.url = common.NewURLWithOptions( @@ -68,7 +67,7 @@ func (f *FileTagRouter) URL() common.URL { common.WithParamsValue(constant.RouterPriority, strconv.Itoa(routerRule.Priority)), common.WithParamsValue(constant.ROUTER_KEY, constant.TAG_ROUTE_PROTOCOL)) }) - return *f.url + return f.url } // Priority Return Priority in listenable router diff --git a/cluster/router/tag/tag_router.go b/cluster/router/tag/tag_router.go index 9f92e83b210fd2bc04c30769f115601dcb253766..c7f53047c1e2beee4545a10302e9f307f06c33d8 100644 --- a/cluster/router/tag/tag_router.go +++ b/cluster/router/tag/tag_router.go @@ -194,8 +194,8 @@ func (c *tagRouter) Process(event *config_center.ConfigChangeEvent) { } // URL gets the url of tagRouter -func (c *tagRouter) URL() common.URL { - return *c.url +func (c *tagRouter) URL() *common.URL { + return c.url } // Priority gets the priority of tagRouter diff --git a/cluster/router/tag/tag_router_test.go b/cluster/router/tag/tag_router_test.go index 92611ac2c59538ea090763d91cb7c5a6ef44e8ee..3f7b979f3d52d51ab50c94ea32e87b5eb4f9591e 100644 --- a/cluster/router/tag/tag_router_test.go +++ b/cluster/router/tag/tag_router_test.go @@ -79,13 +79,13 @@ var ( // MockInvoker is only mock the Invoker to support test tagRouter type MockInvoker struct { - url common.URL + url *common.URL available bool destroyed bool successCount int } -func NewMockInvoker(url common.URL) *MockInvoker { +func NewMockInvoker(url *common.URL) *MockInvoker { return &MockInvoker{ url: url, available: true, @@ -94,7 +94,7 @@ func NewMockInvoker(url common.URL) *MockInvoker { } } -func (bi *MockInvoker) GetUrl() common.URL { +func (bi *MockInvoker) GetUrl() *common.URL { return bi.url } @@ -121,7 +121,7 @@ func (bi *MockInvoker) Destroy() { func TestTagRouterPriority(t *testing.T) { u1, err := common.NewURL(tagRouterTestUserConsumerTag) assert.Nil(t, err) - tagRouter, e := NewTagRouter(&u1) + tagRouter, e := NewTagRouter(u1) assert.Nil(t, e) p := tagRouter.Priority() assert.Equal(t, int64(0), p) @@ -130,7 +130,7 @@ func TestTagRouterPriority(t *testing.T) { func TestTagRouterRouteForce(t *testing.T) { u1, e1 := common.NewURL(tagRouterTestUserConsumerTag) assert.Nil(t, e1) - tagRouter, e := NewTagRouter(&u1) + tagRouter, e := NewTagRouter(u1) assert.Nil(t, e) u2, e2 := common.NewURL(tagRouterTestHangZhouUrl) @@ -146,23 +146,23 @@ func TestTagRouterRouteForce(t *testing.T) { invokers = append(invokers, inv2, inv3, inv4) inv := &invocation.RPCInvocation{} inv.SetAttachments(tagRouterTestDubboTag, tagRouterTestHangZhou) - invRst1 := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), &u1, inv) + invRst1 := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), u1, inv) assert.Equal(t, 1, len(invRst1.ToArray())) assert.Equal(t, tagRouterTestHangZhou, invokers[invRst1.ToArray()[0]].GetUrl().GetParam(tagRouterTestDubboTag, "")) inv.SetAttachments(tagRouterTestDubboTag, tagRouterTestGuangZhou) - invRst2 := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), &u1, inv) + invRst2 := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), u1, inv) assert.Equal(t, 0, len(invRst2.ToArray())) inv.SetAttachments(tagRouterTestDubboForceTag, tagRouterTestFalse) inv.SetAttachments(tagRouterTestDubboTag, tagRouterTestGuangZhou) - invRst3 := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), &u1, inv) + invRst3 := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), u1, inv) assert.Equal(t, 3, len(invRst3.ToArray())) } func TestTagRouterRouteNoForce(t *testing.T) { u1, e1 := common.NewURL(tagRouterTestUserConsumer) assert.Nil(t, e1) - tagRouter, e := NewTagRouter(&u1) + tagRouter, e := NewTagRouter(u1) assert.Nil(t, e) u2, e2 := common.NewURL(tagRouterTestHangZhouUrl) @@ -178,16 +178,16 @@ func TestTagRouterRouteNoForce(t *testing.T) { invokers = append(invokers, inv2, inv3, inv4) inv := &invocation.RPCInvocation{} inv.SetAttachments(tagRouterTestDubboTag, tagRouterTestHangZhou) - invRst := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), &u1, inv) + invRst := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), u1, inv) assert.Equal(t, 1, len(invRst.ToArray())) assert.Equal(t, tagRouterTestHangZhou, invokers[invRst.ToArray()[0]].GetUrl().GetParam(tagRouterTestDubboTag, "")) inv.SetAttachments(tagRouterTestDubboTag, tagRouterTestGuangZhou) inv.SetAttachments(tagRouterTestDubboForceTag, tagRouterTestTrue) - invRst1 := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), &u1, inv) + invRst1 := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), u1, inv) assert.Equal(t, 0, len(invRst1.ToArray())) inv.SetAttachments(tagRouterTestDubboForceTag, tagRouterTestFalse) - invRst2 := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), &u1, inv) + invRst2 := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), u1, inv) assert.Equal(t, 3, len(invRst2.ToArray())) } @@ -225,13 +225,13 @@ func TestRouteBeijingInvoker(t *testing.T) { invokers = append(invokers, inv2, inv3, inv4, inv5) url, _ := common.NewURL(tagRouterTestBeijingUrl) - tagRouter, _ := NewTagRouter(&url) + tagRouter, _ := NewTagRouter(url) rb := roaring.NewBitmap() rb.AddRange(0, uint64(len(invokers))) cache := setUpAddrCache(tagRouter, invokers) inv := &invocation.RPCInvocation{} - res := tagRouter.Route(rb, cache, &url, inv) + res := tagRouter.Route(rb, cache, url, inv) // inv4 and inv5 assert.Equal(t, []uint32{2, 3}, res.ToArray()) } @@ -292,7 +292,7 @@ tags: suite.NoError(err) zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, routerLocalIP, suite.testCluster.Servers[0].Port)) - configuration, err := extension.GetConfigCenterFactory(routerZk).GetDynamicConfiguration(&zkUrl) + configuration, err := extension.GetConfigCenterFactory(routerZk).GetDynamicConfiguration(zkUrl) config.GetEnvInstance().SetDynamicConfiguration(configuration) suite.Nil(err) @@ -301,11 +301,11 @@ tags: url, e1 := common.NewURL(tagRouterTestUserConsumerTag) suite.Nil(e1) - tagRouter, err := NewTagRouter(&url) + tagRouter, err := NewTagRouter(url) suite.Nil(err) suite.NotNil(tagRouter) suite.route = tagRouter - suite.url = &url + suite.url = url } func (suite *DynamicTagRouter) TearDownTest() { @@ -365,7 +365,7 @@ func (suite *DynamicTagRouter) TestDynamicTagRouterByNoTagAndAddressMatch() { func TestProcess(t *testing.T) { u1, err := common.NewURL(tagRouterTestUserConsumerTag) assert.Nil(t, err) - tagRouter, e := NewTagRouter(&u1) + tagRouter, e := NewTagRouter(u1) assert.Nil(t, e) assert.NotNil(t, tagRouter) diff --git a/common/node.go b/common/node.go index 4febd78536126c67bdc65fc09d4be47fb869ef5e..b9c1f39bf960b466276edf1e46bb7c1ecddd6f19 100644 --- a/common/node.go +++ b/common/node.go @@ -19,7 +19,7 @@ package common // Node use for process dubbo node type Node interface { - GetUrl() URL + GetUrl() *URL IsAvailable() bool Destroy() } diff --git a/common/proxy/proxy_factory.go b/common/proxy/proxy_factory.go index 117428cb253e1ad4a4ceee59aa620d7097b41a75..2e66c346b2c8ab6af0b1485f0ea867eb1af0bfc5 100644 --- a/common/proxy/proxy_factory.go +++ b/common/proxy/proxy_factory.go @@ -26,7 +26,7 @@ import ( type ProxyFactory interface { GetProxy(invoker protocol.Invoker, url *common.URL) *Proxy GetAsyncProxy(invoker protocol.Invoker, callBack interface{}, url *common.URL) *Proxy - GetInvoker(url common.URL) protocol.Invoker + GetInvoker(url *common.URL) protocol.Invoker } // Option will define a function of handling ProxyFactory diff --git a/common/proxy/proxy_factory/default.go b/common/proxy/proxy_factory/default.go index 752f3ea38193ca46a5c9dbcb8ec4b05811d19159..067c077294d9dfc1ade1cc2b1181b42f3ae4ba55 100644 --- a/common/proxy/proxy_factory/default.go +++ b/common/proxy/proxy_factory/default.go @@ -72,7 +72,7 @@ func (factory *DefaultProxyFactory) GetAsyncProxy(invoker protocol.Invoker, call } // GetInvoker gets a invoker -func (factory *DefaultProxyFactory) GetInvoker(url common.URL) protocol.Invoker { +func (factory *DefaultProxyFactory) GetInvoker(url *common.URL) protocol.Invoker { return &ProxyInvoker{ BaseInvoker: *protocol.NewBaseInvoker(url), } @@ -88,9 +88,8 @@ func (pi *ProxyInvoker) Invoke(ctx context.Context, invocation protocol.Invocati result := &protocol.RPCResult{} result.SetAttachments(invocation.Attachments()) - url := pi.GetUrl() //get providerUrl. The origin url may be is registry URL. - url = *getProviderURL(&url) + url := getProviderURL(pi.GetUrl()) methodName := invocation.MethodName() proto := url.Protocol diff --git a/common/proxy/proxy_factory/default_test.go b/common/proxy/proxy_factory/default_test.go index 99d5c020f4bfd0254ddddc65e78bcae2e252b6be..4002ab95849b79aef26c8d94822e731cd6f229e3 100644 --- a/common/proxy/proxy_factory/default_test.go +++ b/common/proxy/proxy_factory/default_test.go @@ -34,7 +34,7 @@ import ( func TestGetProxy(t *testing.T) { proxyFactory := NewDefaultProxyFactory() url := common.NewURLWithOptions() - proxy := proxyFactory.GetProxy(protocol.NewBaseInvoker(*url), url) + proxy := proxyFactory.GetProxy(protocol.NewBaseInvoker(url), url) assert.NotNil(t, proxy) } @@ -49,13 +49,13 @@ func TestGetAsyncProxy(t *testing.T) { proxyFactory := NewDefaultProxyFactory() url := common.NewURLWithOptions() async := &TestAsync{} - proxy := proxyFactory.GetAsyncProxy(protocol.NewBaseInvoker(*url), async.CallBack, url) + proxy := proxyFactory.GetAsyncProxy(protocol.NewBaseInvoker(url), async.CallBack, url) assert.NotNil(t, proxy) } func TestGetInvoker(t *testing.T) { proxyFactory := NewDefaultProxyFactory() url := common.NewURLWithOptions() - invoker := proxyFactory.GetInvoker(*url) + invoker := proxyFactory.GetInvoker(url) assert.True(t, invoker.IsAvailable()) } diff --git a/common/proxy/proxy_test.go b/common/proxy/proxy_test.go index 9f5eaadf7cb5967fb585e2df808b0194e6abe249..c6f659666180310887f2101966e59669df707e54 100644 --- a/common/proxy/proxy_test.go +++ b/common/proxy/proxy_test.go @@ -58,7 +58,7 @@ func (s *TestServiceInt) Reference() string { func TestProxyImplement(t *testing.T) { - invoker := protocol.NewBaseInvoker(common.URL{}) + invoker := protocol.NewBaseInvoker(&common.URL{}) p := NewProxy(invoker, nil, map[string]string{constant.ASYNC_KEY: "false"}) s := &TestService{} p.Implement(s) @@ -126,7 +126,7 @@ func TestProxyImplement(t *testing.T) { func TestProxyImplementForContext(t *testing.T) { invoker := &TestProxyInvoker{ - BaseInvoker: *protocol.NewBaseInvoker(common.URL{}), + BaseInvoker: *protocol.NewBaseInvoker(&common.URL{}), } p := NewProxy(invoker, nil, map[string]string{constant.ASYNC_KEY: "false"}) s := &TestService{} diff --git a/common/url.go b/common/url.go index 3a88001c5fb345aa004e5a3975df89cbec2c415a..d8f096bb48991e0697297010813bcb880a30d148 100644 --- a/common/url.go +++ b/common/url.go @@ -21,6 +21,7 @@ import ( "bytes" "encoding/base64" "fmt" + cm "github.com/Workiva/go-datastructures/common" "math" "net" "net/url" @@ -88,12 +89,25 @@ type baseUrl struct { PrimitiveURL string } -// URL is not thread-safe. +// noCopy may be embedded into structs which must not be copied +// after the first use. +// +// See https://golang.org/issues/8005#issuecomment-190753527 +// for details. +type noCopy struct{} + +// Lock is a no-op used by -copylocks checker from `go vet`. +func (*noCopy) Lock() {} +func (*noCopy) Unlock() {} + +// URL thread-safe. but this url should not be copied. // we fail to define this struct to be immutable object. // but, those method which will update the URL, including SetParam, SetParams // are only allowed to be invoked in creating URL instance // Please keep in mind that this struct is immutable after it has been created and initialized. type URL struct { + noCopy noCopy + baseUrl Path string // like /com.ikurento.dubbo.UserProvider3 Username string @@ -105,80 +119,80 @@ type URL struct { // Option accepts url // Option will define a function of handling URL -type option func(*URL) +type Option func(*URL) // WithUsername sets username for url -func WithUsername(username string) option { +func WithUsername(username string) Option { return func(url *URL) { url.Username = username } } // WithPassword sets password for url -func WithPassword(pwd string) option { +func WithPassword(pwd string) Option { return func(url *URL) { url.Password = pwd } } // WithMethods sets methods for url -func WithMethods(methods []string) option { +func WithMethods(methods []string) Option { return func(url *URL) { url.Methods = methods } } // WithParams sets params for url -func WithParams(params url.Values) option { +func WithParams(params url.Values) Option { return func(url *URL) { url.params = params } } // WithParamsValue sets params field for url -func WithParamsValue(key, val string) option { +func WithParamsValue(key, val string) Option { return func(url *URL) { url.SetParam(key, val) } } // WithProtocol sets protocol for url -func WithProtocol(proto string) option { +func WithProtocol(proto string) Option { return func(url *URL) { url.Protocol = proto } } // WithIp sets ip for url -func WithIp(ip string) option { +func WithIp(ip string) Option { return func(url *URL) { url.Ip = ip } } // WithPort sets port for url -func WithPort(port string) option { +func WithPort(port string) Option { return func(url *URL) { url.Port = port } } // WithPath sets path for url -func WithPath(path string) option { +func WithPath(path string) Option { return func(url *URL) { url.Path = "/" + strings.TrimPrefix(path, "/") } } // WithLocation sets location for url -func WithLocation(location string) option { +func WithLocation(location string) Option { return func(url *URL) { url.Location = location } } // WithToken sets token for url -func WithToken(token string) option { +func WithToken(token string) Option { return func(url *URL) { if len(token) > 0 { value := token @@ -196,33 +210,26 @@ func WithToken(token string) option { } // NewURLWithOptions will create a new url with options -func NewURLWithOptions(opts ...option) *URL { - url := &URL{} +func NewURLWithOptions(opts ...Option) *URL { + newUrl := &URL{} for _, opt := range opts { - opt(url) + opt(newUrl) } - url.Location = url.Ip + ":" + url.Port - return url + newUrl.Location = newUrl.Ip + ":" + newUrl.Port + return newUrl } // NewURL will create a new url // the urlString should not be empty -func NewURL(urlString string, opts ...option) (URL, error) { - var ( - err error - rawUrlString string - serviceUrl *url.URL - s = URL{baseUrl: baseUrl{}} - ) - - // new a null instance +func NewURL(urlString string, opts ...Option) (*URL, error) { + s := URL{baseUrl: baseUrl{}} if urlString == "" { - return s, nil + return &s, nil } - rawUrlString, err = url.QueryUnescape(urlString) + rawUrlString, err := url.QueryUnescape(urlString) if err != nil { - return s, perrors.Errorf("url.QueryUnescape(%s), error{%v}", urlString, err) + return &s, perrors.Errorf("url.QueryUnescape(%s), error{%v}", urlString, err) } // rawUrlString = "//" + rawUrlString @@ -233,14 +240,15 @@ func NewURL(urlString string, opts ...option) (URL, error) { } rawUrlString = t.Protocol + "://" + rawUrlString } - serviceUrl, err = url.Parse(rawUrlString) - if err != nil { - return s, perrors.Errorf("url.Parse(url string{%s}), error{%v}", rawUrlString, err) + + serviceUrl, urlParseErr := url.Parse(rawUrlString) + if urlParseErr != nil { + return &s, perrors.Errorf("url.Parse(url string{%s}), error{%v}", rawUrlString, err) } s.params, err = url.ParseQuery(serviceUrl.RawQuery) if err != nil { - return s, perrors.Errorf("url.ParseQuery(raw url string{%s}), error{%v}", serviceUrl.RawQuery, err) + return &s, perrors.Errorf("url.ParseQuery(raw url string{%s}), error{%v}", serviceUrl.RawQuery, err) } s.PrimitiveURL = urlString @@ -252,25 +260,29 @@ func NewURL(urlString string, opts ...option) (URL, error) { if strings.Contains(s.Location, ":") { s.Ip, s.Port, err = net.SplitHostPort(s.Location) if err != nil { - return s, perrors.Errorf("net.SplitHostPort(url.Host{%s}), error{%v}", s.Location, err) + return &s, perrors.Errorf("net.SplitHostPort(url.Host{%s}), error{%v}", s.Location, err) } } for _, opt := range opts { opt(&s) } - return s, nil + return &s, nil } // URLEqual judge @url and @c is equal or not. -func (c URL) URLEqual(url URL) bool { - c.Ip = "" - c.Port = "" - url.Ip = "" - url.Port = "" - cGroup := c.GetParam(constant.GROUP_KEY, "") - urlGroup := url.GetParam(constant.GROUP_KEY, "") - cKey := c.Key() - urlKey := url.Key() +func (c *URL) URLEqual(url *URL) bool { + tmpC := c.Clone() + tmpC.Ip = "" + tmpC.Port = "" + + tmpUrl := url.Clone() + tmpUrl.Ip = "" + tmpUrl.Port = "" + + cGroup := tmpC.GetParam(constant.GROUP_KEY, "") + urlGroup := tmpUrl.GetParam(constant.GROUP_KEY, "") + cKey := tmpC.Key() + urlKey := tmpUrl.Key() if cGroup == constant.ANY_VALUE { cKey = strings.Replace(cKey, "group=*", "group="+urlGroup, 1) @@ -284,12 +296,12 @@ func (c URL) URLEqual(url URL) bool { } // 2. if url contains enabled key, should be true, or * - if url.GetParam(constant.ENABLED_KEY, "true") != "true" && url.GetParam(constant.ENABLED_KEY, "") != constant.ANY_VALUE { + if tmpUrl.GetParam(constant.ENABLED_KEY, "true") != "true" && tmpUrl.GetParam(constant.ENABLED_KEY, "") != constant.ANY_VALUE { return false } // TODO :may need add interface key any value condition - return isMatchCategory(url.GetParam(constant.CATEGORY_KEY, constant.DEFAULT_CATEGORY), c.GetParam(constant.CATEGORY_KEY, constant.DEFAULT_CATEGORY)) + return isMatchCategory(tmpUrl.GetParam(constant.CATEGORY_KEY, constant.DEFAULT_CATEGORY), tmpC.GetParam(constant.CATEGORY_KEY, constant.DEFAULT_CATEGORY)) } func isMatchCategory(category1 string, category2 string) bool { @@ -304,31 +316,26 @@ func isMatchCategory(category1 string, category2 string) bool { } } -func (c URL) String() string { +func (c *URL) String() string { var buf strings.Builder if len(c.Username) == 0 && len(c.Password) == 0 { - buf.WriteString(fmt.Sprintf( - "%s://%s:%s%s?", - c.Protocol, c.Ip, c.Port, c.Path)) + buf.WriteString(fmt.Sprintf("%s://%s:%s%s?", c.Protocol, c.Ip, c.Port, c.Path)) } else { - buf.WriteString(fmt.Sprintf( - "%s://%s:%s@%s:%s%s?", - c.Protocol, c.Username, c.Password, c.Ip, c.Port, c.Path)) + buf.WriteString(fmt.Sprintf("%s://%s:%s@%s:%s%s?", c.Protocol, c.Username, c.Password, c.Ip, c.Port, c.Path)) } buf.WriteString(c.params.Encode()) return buf.String() } // Key gets key -func (c URL) Key() string { - buildString := fmt.Sprintf( - "%s://%s:%s@%s:%s/?interface=%s&group=%s&version=%s", +func (c *URL) Key() string { + buildString := fmt.Sprintf("%s://%s:%s@%s:%s/?interface=%s&group=%s&version=%s", c.Protocol, c.Username, c.Password, c.Ip, c.Port, c.Service(), c.GetParam(constant.GROUP_KEY, ""), c.GetParam(constant.VERSION_KEY, "")) return buildString } // ServiceKey gets a unique key of a service. -func (c URL) ServiceKey() string { +func (c *URL) ServiceKey() string { return ServiceKey(c.GetParam(constant.INTERFACE_KEY, strings.TrimPrefix(c.Path, "/")), c.GetParam(constant.GROUP_KEY, ""), c.GetParam(constant.VERSION_KEY, "")) } @@ -382,7 +389,7 @@ func (c *URL) EncodedServiceKey() string { } // Service gets service -func (c URL) Service() string { +func (c *URL) Service() string { service := c.GetParam(constant.INTERFACE_KEY, strings.TrimPrefix(c.Path, "/")) if service != "" { return service @@ -409,7 +416,6 @@ func (c *URL) AddParamAvoidNil(key string, value string) { if c.params == nil { c.params = url.Values{} } - c.params.Add(key, value) } @@ -433,7 +439,7 @@ func (c *URL) RangeParams(f func(key, value string) bool) { } // GetParam gets value by key -func (c URL) GetParam(s string, d string) string { +func (c *URL) GetParam(s string, d string) string { c.paramsLock.RLock() defer c.paramsLock.RUnlock() r := c.params.Get(s) @@ -444,19 +450,19 @@ func (c URL) GetParam(s string, d string) string { } // GetParams gets values -func (c URL) GetParams() url.Values { +func (c *URL) GetParams() url.Values { return c.params } // GetParamAndDecoded gets values and decode -func (c URL) GetParamAndDecoded(key string) (string, error) { +func (c *URL) GetParamAndDecoded(key string) (string, error) { ruleDec, err := base64.URLEncoding.DecodeString(c.GetParam(key, "")) value := string(ruleDec) return value, err } // GetRawParam gets raw param -func (c URL) GetRawParam(key string) string { +func (c *URL) GetRawParam(key string) string { switch key { case PROTOCOL: return c.Protocol @@ -476,7 +482,7 @@ func (c URL) GetRawParam(key string) string { } // GetParamBool judge whether @key exists or not -func (c URL) GetParamBool(key string, d bool) bool { +func (c *URL) GetParamBool(key string, d bool) bool { r, err := strconv.ParseBool(c.GetParam(key, "")) if err != nil { return d @@ -485,34 +491,34 @@ func (c URL) GetParamBool(key string, d bool) bool { } // GetParamInt gets int64 value by @key -func (c URL) GetParamInt(key string, d int64) int64 { +func (c *URL) GetParamInt(key string, d int64) int64 { r, err := strconv.ParseInt(c.GetParam(key, ""), 10, 64) - if err != nil { + if err != nil { return d } return r } // GetParamInt32 gets int32 value by @key -func (c URL) GetParamInt32(key string, d int32) int32 { +func (c *URL) GetParamInt32(key string, d int32) int32 { r, err := strconv.ParseInt(c.GetParam(key, ""), 10, 32) - if err != nil { + if err != nil { return d } return int32(r) } // GetParamByIntValue gets int value by @key -func (c URL) GetParamByIntValue(key string, d int) int { +func (c *URL) GetParamByIntValue(key string, d int) int { r, err := strconv.ParseInt(c.GetParam(key, ""), 10, 0) - if err != nil { + if err != nil { return d } return int(r) } // GetMethodParamInt gets int method param -func (c URL) GetMethodParamInt(method string, key string, d int64) int64 { +func (c *URL) GetMethodParamInt(method string, key string, d int64) int64 { r, err := strconv.ParseInt(c.GetParam("methods."+method+"."+key, ""), 10, 64) if err != nil { return d @@ -521,7 +527,7 @@ func (c URL) GetMethodParamInt(method string, key string, d int64) int64 { } // GetMethodParamIntValue gets int method param -func (c URL) GetMethodParamIntValue(method string, key string, d int) int { +func (c *URL) GetMethodParamIntValue(method string, key string, d int) int { r, err := strconv.ParseInt(c.GetParam("methods."+method+"."+key, ""), 10, 0) if err != nil { return d @@ -530,7 +536,7 @@ func (c URL) GetMethodParamIntValue(method string, key string, d int) int { } // GetMethodParamInt64 gets int64 method param -func (c URL) GetMethodParamInt64(method string, key string, d int64) int64 { +func (c *URL) GetMethodParamInt64(method string, key string, d int64) int64 { r := c.GetMethodParamInt(method, key, math.MinInt64) if r == math.MinInt64 { return c.GetParamInt(key, d) @@ -539,7 +545,7 @@ func (c URL) GetMethodParamInt64(method string, key string, d int64) int64 { } // GetMethodParam gets method param -func (c URL) GetMethodParam(method string, key string, d string) string { +func (c *URL) GetMethodParam(method string, key string, d string) string { r := c.GetParam("methods."+method+"."+key, "") if r == "" { r = d @@ -548,7 +554,7 @@ func (c URL) GetMethodParam(method string, key string, d string) string { } // GetMethodParamBool judge whether @method param exists or not -func (c URL) GetMethodParamBool(method string, key string, d bool) bool { +func (c *URL) GetMethodParamBool(method string, key string, d bool) bool { r := c.GetParamBool("methods."+method+"."+key, d) return r } @@ -564,7 +570,7 @@ func (c *URL) SetParams(m url.Values) { } // ToMap transfer URL to Map -func (c URL) ToMap() map[string]string { +func (c *URL) ToMap() map[string]string { paramsMap := make(map[string]string) c.RangeParams(func(key, value string) bool { @@ -668,6 +674,19 @@ func (c *URL) CloneExceptParams(excludeParams *gxset.HashSet) *URL { return newUrl } +func (c *URL) Compare(comp cm.Comparator) int { + a := c.String() + b := comp.(*URL).String() + switch { + case a > b: + return 1 + case a < b: + return -1 + default: + return 0 + } +} + // Copy url based on the reserved parameter's keys. func (c *URL) CloneWithParams(reserveParams []string) *URL { params := url.Values{} @@ -691,7 +710,7 @@ func (c *URL) CloneWithParams(reserveParams []string) *URL { } // IsEquals compares if two URLs equals with each other. Excludes are all parameter keys which should ignored. -func IsEquals(left URL, right URL, excludes ...string) bool { +func IsEquals(left *URL, right *URL, excludes ...string) bool { if left.Ip != right.Ip || left.Port != right.Port { return false } @@ -735,7 +754,7 @@ func mergeNormalParam(mergedUrl *URL, referenceUrl *URL, paramKeys []string) []f // URLSlice will be used to sort URL instance // Instances will be order by URL.String() -type URLSlice []URL +type URLSlice []*URL // nolint func (s URLSlice) Len() int { diff --git a/common/url_test.go b/common/url_test.go index 12020f4289904d22c0d64a6df1cea2903394a016..05377c19c93eb3c13021966e4b2684d4910ddaab 100644 --- a/common/url_test.go +++ b/common/url_test.go @@ -289,7 +289,7 @@ func TestMergeUrl(t *testing.T) { referenceUrl, _ := NewURL("mock1://127.0.0.1:1111", WithParams(referenceUrlParams), WithMethods([]string{"testMethod"})) serviceUrl, _ := NewURL("mock2://127.0.0.1:20000", WithParams(serviceUrlParams)) - mergedUrl := MergeUrl(&serviceUrl, &referenceUrl) + mergedUrl := MergeUrl(serviceUrl, referenceUrl) assert.Equal(t, "random", mergedUrl.GetParam(constant.CLUSTER_KEY, "")) assert.Equal(t, "1", mergedUrl.GetParam("test2", "")) assert.Equal(t, "1", mergedUrl.GetParam("test3", "")) diff --git a/config/config_center_config.go b/config/config_center_config.go index 0fc4007940d9b1ac2456c9b2d379493bb5d8edb0..752d9d45855c886a1d5122c6e7832196c7e9413b 100644 --- a/config/config_center_config.go +++ b/config/config_center_config.go @@ -91,7 +91,7 @@ type configCenter struct { // toURL will compatible with baseConfig.ConfigCenterConfig.Address and baseConfig.ConfigCenterConfig.RemoteRef before 1.6.0 // After 1.6.0 will not compatible, only baseConfig.ConfigCenterConfig.RemoteRef -func (b *configCenter) toURL(baseConfig BaseConfig) (common.URL, error) { +func (b *configCenter) toURL(baseConfig BaseConfig) (*common.URL, error) { if len(baseConfig.ConfigCenterConfig.Address) > 0 { return common.NewURL(baseConfig.ConfigCenterConfig.Address, common.WithProtocol(baseConfig.ConfigCenterConfig.Protocol), common.WithParams(baseConfig.ConfigCenterConfig.GetUrlMap())) @@ -101,7 +101,7 @@ func (b *configCenter) toURL(baseConfig BaseConfig) (common.URL, error) { rc, ok := baseConfig.GetRemoteConfig(remoteRef) if !ok { - return common.URL{}, perrors.New("Could not find out the remote ref config, name: " + remoteRef) + return nil, perrors.New("Could not find out the remote ref config, name: " + remoteRef) } newURL, err := rc.toURL() @@ -114,11 +114,11 @@ func (b *configCenter) toURL(baseConfig BaseConfig) (common.URL, error) { // startConfigCenter will start the config center. // it will prepare the environment func (b *configCenter) startConfigCenter(baseConfig BaseConfig) error { - url, err := b.toURL(baseConfig) + newUrl, err := b.toURL(baseConfig) if err != nil { return err } - if err = b.prepareEnvironment(baseConfig, &url); err != nil { + if err = b.prepareEnvironment(baseConfig, newUrl); err != nil { return perrors.WithMessagef(err, "start config center error!") } // c.fresh() diff --git a/config/config_loader.go b/config/config_loader.go index f2102249c6e835c62e69613388bdd0c3dc4c750a..ec591aad6526e5841656465e71465413d01ad5ba 100644 --- a/config/config_loader.go +++ b/config/config_loader.go @@ -216,7 +216,7 @@ func registerServiceInstance() { if url == nil { return } - instance, err := createInstance(*url) + instance, err := createInstance(url) if err != nil { panic(err) } @@ -240,7 +240,7 @@ func registerServiceInstance() { } // nolint -func createInstance(url common.URL) (registry.ServiceInstance, error) { +func createInstance(url *common.URL) (registry.ServiceInstance, error) { appConfig := GetApplicationConfig() port, err := strconv.ParseInt(url.Port, 10, 32) if err != nil { @@ -250,9 +250,6 @@ func createInstance(url common.URL) (registry.ServiceInstance, error) { host := url.Ip if len(host) == 0 { host = common.GetLocalIp() - if err != nil { - return nil, perrors.WithMessage(err, "could not get the local Ip") - } } // usually we will add more metadata @@ -272,7 +269,7 @@ func createInstance(url common.URL) (registry.ServiceInstance, error) { // selectMetadataServiceExportedURL get already be exported url func selectMetadataServiceExportedURL() *common.URL { - var selectedUrl common.URL + var selectedUrl *common.URL metaDataService, err := extension.GetMetadataService(GetApplicationConfig().MetadataType) if err != nil { logger.Warn(err) @@ -297,7 +294,7 @@ func selectMetadataServiceExportedURL() *common.URL { break } } - return &selectedUrl + return selectedUrl } func initRouter() { diff --git a/config/config_loader_test.go b/config/config_loader_test.go index 461e607c1e0ad2e9471770224c8eb6d5f3ee96f6..9b253030ff9b218f9756145c9bdefdf512a2e131 100644 --- a/config/config_loader_test.go +++ b/config/config_loader_test.go @@ -25,7 +25,6 @@ import ( ) import ( - cm "github.com/Workiva/go-datastructures/common" "github.com/Workiva/go-datastructures/slice/skip" gxset "github.com/dubbogo/gost/container/set" gxpage "github.com/dubbogo/gost/page" @@ -353,27 +352,27 @@ func (m *mockMetadataService) ServiceName() (string, error) { panic("implement me") } -func (m *mockMetadataService) ExportURL(url common.URL) (bool, error) { - return m.addURL(m.exportedServiceURLs, &url), nil +func (m *mockMetadataService) ExportURL(url *common.URL) (bool, error) { + return m.addURL(m.exportedServiceURLs, url), nil } -func (m *mockMetadataService) UnexportURL(url common.URL) error { +func (m *mockMetadataService) UnexportURL(*common.URL) error { panic("implement me") } -func (m *mockMetadataService) SubscribeURL(url common.URL) (bool, error) { +func (m *mockMetadataService) SubscribeURL(*common.URL) (bool, error) { panic("implement me") } -func (m *mockMetadataService) UnsubscribeURL(url common.URL) error { +func (m *mockMetadataService) UnsubscribeURL(*common.URL) error { panic("implement me") } -func (m *mockMetadataService) PublishServiceDefinition(url common.URL) error { +func (m *mockMetadataService) PublishServiceDefinition(*common.URL) error { return nil } -func (m *mockMetadataService) GetExportedURLs(serviceInterface string, group string, version string, protocol string) ([]interface{}, error) { +func (m *mockMetadataService) GetExportedURLs(string, string, string, string) ([]interface{}, error) { return ConvertURLArrToIntfArr(m.getAllService(m.exportedServiceURLs)), nil } @@ -381,19 +380,19 @@ func (m *mockMetadataService) MethodMapper() map[string]string { panic("implement me") } -func (m *mockMetadataService) GetSubscribedURLs() ([]common.URL, error) { +func (m *mockMetadataService) GetSubscribedURLs() ([]*common.URL, error) { panic("implement me") } -func (m *mockMetadataService) GetServiceDefinition(interfaceName string, group string, version string) (string, error) { +func (m *mockMetadataService) GetServiceDefinition(string, string, string) (string, error) { panic("implement me") } -func (m *mockMetadataService) GetServiceDefinitionByServiceKey(serviceKey string) (string, error) { +func (m *mockMetadataService) GetServiceDefinitionByServiceKey(string) (string, error) { panic("implement me") } -func (m *mockMetadataService) RefreshMetadata(exportedRevision string, subscribedRevision string) (bool, error) { +func (m *mockMetadataService) RefreshMetadata(string, string) (bool, error) { panic("implement me") } @@ -409,7 +408,7 @@ func (mts *mockMetadataService) addURL(targetMap *sync.Map, url *common.URL) boo logger.Debug(url.ServiceKey()) if urlSet, loaded = targetMap.LoadOrStore(url.ServiceKey(), skip.New(uint64(0))); loaded { mts.lock.RLock() - wantedUrl := urlSet.(*skip.SkipList).Get(Comparator(*url)) + wantedUrl := urlSet.(*skip.SkipList).Get(url) if len(wantedUrl) > 0 && wantedUrl[0] != nil { mts.lock.RUnlock() return false @@ -418,23 +417,23 @@ func (mts *mockMetadataService) addURL(targetMap *sync.Map, url *common.URL) boo } mts.lock.Lock() // double chk - wantedUrl := urlSet.(*skip.SkipList).Get(Comparator(*url)) + wantedUrl := urlSet.(*skip.SkipList).Get(url) if len(wantedUrl) > 0 && wantedUrl[0] != nil { mts.lock.Unlock() return false } - urlSet.(*skip.SkipList).Insert(Comparator(*url)) + urlSet.(*skip.SkipList).Insert(url) mts.lock.Unlock() return true } -func (m *mockMetadataService) getAllService(services *sync.Map) []common.URL { +func (m *mockMetadataService) getAllService(services *sync.Map) []*common.URL { // using skip list to dedup and sorting - res := make([]common.URL, 0) + var res []*common.URL services.Range(func(key, value interface{}) bool { urls := value.(*skip.SkipList) for i := uint64(0); i < urls.Len(); i++ { - url := common.URL(urls.ByPosition(i).(Comparator)) + url := urls.ByPosition(i).(*common.URL) if url.GetParam(constant.INTERFACE_KEY, url.Path) != constant.METADATA_SERVICE_NAME { res = append(res, url) } @@ -445,26 +444,10 @@ func (m *mockMetadataService) getAllService(services *sync.Map) []common.URL { return res } -type Comparator common.URL - -// Compare is defined as Comparator for skip list to compare the URL -func (c Comparator) Compare(comp cm.Comparator) int { - a := common.URL(c).String() - b := common.URL(comp.(Comparator)).String() - switch { - case a > b: - return 1 - case a < b: - return -1 - default: - return 0 - } -} - type mockServiceDiscoveryRegistry struct { } -func (mr *mockServiceDiscoveryRegistry) GetUrl() common.URL { +func (mr *mockServiceDiscoveryRegistry) GetUrl() *common.URL { panic("implement me") } @@ -476,11 +459,11 @@ func (mr *mockServiceDiscoveryRegistry) Destroy() { panic("implement me") } -func (mr *mockServiceDiscoveryRegistry) Register(url common.URL) error { +func (mr *mockServiceDiscoveryRegistry) Register(*common.URL) error { panic("implement me") } -func (mr *mockServiceDiscoveryRegistry) UnRegister(url common.URL) error { +func (mr *mockServiceDiscoveryRegistry) UnRegister(*common.URL) error { panic("implement me") } @@ -507,15 +490,15 @@ func (m *mockServiceDiscovery) Destroy() error { panic("implement me") } -func (m *mockServiceDiscovery) Register(instance registry.ServiceInstance) error { +func (m *mockServiceDiscovery) Register(registry.ServiceInstance) error { return nil } -func (m *mockServiceDiscovery) Update(instance registry.ServiceInstance) error { +func (m *mockServiceDiscovery) Update(registry.ServiceInstance) error { panic("implement me") } -func (m *mockServiceDiscovery) Unregister(instance registry.ServiceInstance) error { +func (m *mockServiceDiscovery) Unregister(registry.ServiceInstance) error { panic("implement me") } @@ -527,39 +510,39 @@ func (m *mockServiceDiscovery) GetServices() *gxset.HashSet { panic("implement me") } -func (m *mockServiceDiscovery) GetInstances(serviceName string) []registry.ServiceInstance { +func (m *mockServiceDiscovery) GetInstances(string) []registry.ServiceInstance { panic("implement me") } -func (m *mockServiceDiscovery) GetInstancesByPage(serviceName string, offset int, pageSize int) gxpage.Pager { +func (m *mockServiceDiscovery) GetInstancesByPage(string, int, int) gxpage.Pager { panic("implement me") } -func (m *mockServiceDiscovery) GetHealthyInstancesByPage(serviceName string, offset int, pageSize int, healthy bool) gxpage.Pager { +func (m *mockServiceDiscovery) GetHealthyInstancesByPage(string, int, int, bool) gxpage.Pager { panic("implement me") } -func (m *mockServiceDiscovery) GetRequestInstances(serviceNames []string, offset int, requestedSize int) map[string]gxpage.Pager { +func (m *mockServiceDiscovery) GetRequestInstances([]string, int, int) map[string]gxpage.Pager { panic("implement me") } -func (m *mockServiceDiscovery) AddListener(listener *registry.ServiceInstancesChangedListener) error { +func (m *mockServiceDiscovery) AddListener(*registry.ServiceInstancesChangedListener) error { panic("implement me") } -func (m *mockServiceDiscovery) DispatchEventByServiceName(serviceName string) error { +func (m *mockServiceDiscovery) DispatchEventByServiceName(string) error { panic("implement me") } -func (m *mockServiceDiscovery) DispatchEventForInstances(serviceName string, instances []registry.ServiceInstance) error { +func (m *mockServiceDiscovery) DispatchEventForInstances(string, []registry.ServiceInstance) error { panic("implement me") } -func (m *mockServiceDiscovery) DispatchEvent(event *registry.ServiceInstancesChangedEvent) error { +func (m *mockServiceDiscovery) DispatchEvent(*registry.ServiceInstancesChangedEvent) error { panic("implement me") } -func ConvertURLArrToIntfArr(urls []common.URL) []interface{} { +func ConvertURLArrToIntfArr(urls []*common.URL) []interface{} { if len(urls) == 0 { return []interface{}{} } diff --git a/config/instance/metadata_report.go b/config/instance/metadata_report.go index 8e833dd70bcc0db8e65cd8703f2bc1859432a887..68a197d3ddb4abfd8ab924749857a7f94a43e1d4 100644 --- a/config/instance/metadata_report.go +++ b/config/instance/metadata_report.go @@ -29,7 +29,7 @@ import ( var ( instance report.MetadataReport - reportUrl common.URL + reportUrl *common.URL once sync.Once ) @@ -41,18 +41,18 @@ func GetMetadataReportInstance(selectiveUrl ...*common.URL) report.MetadataRepor if len(selectiveUrl) > 0 { url = selectiveUrl[0] instance = extension.GetMetadataReportFactory(url.Protocol).CreateMetadataReport(url) - reportUrl = *url + reportUrl = url } }) return instance } // GetMetadataReportUrl will return the report instance url -func GetMetadataReportUrl() common.URL { +func GetMetadataReportUrl() *common.URL { return reportUrl } // SetMetadataReportUrl will only can be used by unit test to mock url -func SetMetadataReportUrl(url common.URL) { +func SetMetadataReportUrl(url *common.URL) { reportUrl = url } diff --git a/config/instance/metadata_report_test.go b/config/instance/metadata_report_test.go index d489af048055b362f2fa68a8963dd2cdf9632945..110903a41f577ef78b4d7abbcef17864fd6e281c 100644 --- a/config/instance/metadata_report_test.go +++ b/config/instance/metadata_report_test.go @@ -38,7 +38,7 @@ func TestGetMetadataReportInstance(t *testing.T) { return &mockMetadataReportFactory{} }) u, _ := common.NewURL("mock://127.0.0.1") - rpt := GetMetadataReportInstance(&u) + rpt := GetMetadataReportInstance(u) assert.NotNil(t, rpt) } @@ -60,7 +60,7 @@ func (m mockMetadataReport) StoreConsumerMetadata(*identifier.MetadataIdentifier panic("implement me") } -func (m mockMetadataReport) SaveServiceMetadata(*identifier.ServiceMetadataIdentifier, common.URL) error { +func (m mockMetadataReport) SaveServiceMetadata(*identifier.ServiceMetadataIdentifier, *common.URL) error { panic("implement me") } diff --git a/config/metadata_report_config.go b/config/metadata_report_config.go index 6d319e5ecb8007e06dcf790fff145bfab754df3d..24eba5ec8dc483966b8e63271b40cde9cbf54e3e 100644 --- a/config/metadata_report_config.go +++ b/config/metadata_report_config.go @@ -84,7 +84,7 @@ func (c *MetadataReportConfig) ToUrl() (*common.URL, error) { return nil, perrors.New("Invalid MetadataReportConfig.") } res.SetParam("metadata", res.Protocol) - return &res, nil + return res, nil } func (c *MetadataReportConfig) IsValid() bool { @@ -101,8 +101,8 @@ func startMetadataReport(metadataType string, metadataReportConfig *MetadataRepo return perrors.New("MetadataConfig remote ref can not be empty.") } - if url, err := metadataReportConfig.ToUrl(); err == nil { - instance.GetMetadataReportInstance(url) + if tmpUrl, err := metadataReportConfig.ToUrl(); err == nil { + instance.GetMetadataReportInstance(tmpUrl) } else { return perrors.Wrap(err, "Start MetadataReport failed.") } diff --git a/config/reference_config.go b/config/reference_config.go index cd10f89eb7773e16ed953623c6fb38dcb98b01b4..2e914ac9a718aaef93732fafa18f7d954cc0c5f6 100644 --- a/config/reference_config.go +++ b/config/reference_config.go @@ -114,13 +114,13 @@ func (c *ReferenceConfig) Refer(_ interface{}) { } if serviceUrl.Protocol == constant.REGISTRY_PROTOCOL { serviceUrl.SubURL = cfgURL - c.urls = append(c.urls, &serviceUrl) + c.urls = append(c.urls, serviceUrl) } else { if serviceUrl.Path == "" { serviceUrl.Path = "/" + c.id } // merge url need to do - newUrl := common.MergeUrl(&serviceUrl, cfgURL) + newUrl := common.MergeUrl(serviceUrl, cfgURL) c.urls = append(c.urls, newUrl) } } @@ -135,12 +135,12 @@ func (c *ReferenceConfig) Refer(_ interface{}) { } if len(c.urls) == 1 { - c.invoker = extension.GetProtocol(c.urls[0].Protocol).Refer(*c.urls[0]) + c.invoker = extension.GetProtocol(c.urls[0].Protocol).Refer(c.urls[0]) } else { invokers := make([]protocol.Invoker, 0, len(c.urls)) var regUrl *common.URL for _, u := range c.urls { - invokers = append(invokers, extension.GetProtocol(u.Protocol).Refer(*u)) + invokers = append(invokers, extension.GetProtocol(u.Protocol).Refer(u)) if u.Protocol == constant.REGISTRY_PROTOCOL { regUrl = u } diff --git a/config/reference_config_test.go b/config/reference_config_test.go index a4345ad13d4944b8fae0930930584fccbd0fb33c..0207e1ff24af022690e3773573ddd61ebad88e15 100644 --- a/config/reference_config_test.go +++ b/config/reference_config_test.go @@ -334,7 +334,7 @@ func newRegistryProtocol() protocol.Protocol { type mockRegistryProtocol struct{} -func (*mockRegistryProtocol) Refer(url common.URL) protocol.Invoker { +func (*mockRegistryProtocol) Refer(url *common.URL) protocol.Invoker { return protocol.NewBaseInvoker(url) } @@ -345,7 +345,7 @@ func (*mockRegistryProtocol) Export(invoker protocol.Invoker) protocol.Exporter if err != nil { panic(err) } - ok, err := metaDataService.ExportURL(*invoker.GetUrl().SubURL.Clone()) + ok, err := metaDataService.ExportURL(invoker.GetUrl().SubURL.Clone()) if err != nil { panic(err) } @@ -367,7 +367,7 @@ func getRegistryUrl(invoker protocol.Invoker) *common.URL { protocol := url.GetParam(constant.REGISTRY_KEY, "") url.Protocol = protocol } - return &url + return url } func (p *mockRegistryProtocol) GetRegistries() []registry.Registry { diff --git a/config/registry_config.go b/config/registry_config.go index 89566c428ed14f460c0f214358c9fa05d529ddb6..5aff45dc9f4dd20022255ada04cff78bbf295f3e 100644 --- a/config/registry_config.go +++ b/config/registry_config.go @@ -53,7 +53,7 @@ type RegistryConfig struct { //ZoneForce bool `yaml:"zoneForce" json:"zoneForce,omitempty" property:"zoneForce"` // Affects traffic distribution among registries, // useful when subscribe to multiple registries Take effect only when no preferred registry is specified. - Weight int64 `yaml:"weight" json:"params,omitempty" property:"weight"` + Weight int64 `yaml:"weight" json:"weight,omitempty" property:"weight"` Params map[string]string `yaml:"params" json:"params,omitempty" property:"params"` } @@ -114,7 +114,7 @@ func loadRegistries(targetRegistries string, registries map[string]*RegistryConf logger.Errorf("The registry id: %s url is invalid, error: %#v", k, err) panic(err) } else { - urls = append(urls, &url) + urls = append(urls, url) } } } diff --git a/config/remote_config.go b/config/remote_config.go index 0f0c3e5cb7991e19ea0ad722fc4d40da01c1fad7..61d4dce0cdc104d6f9710d1a1f3caa540edec076 100644 --- a/config/remote_config.go +++ b/config/remote_config.go @@ -63,9 +63,9 @@ func (rc *RemoteConfig) GetParam(key string, def string) string { return param } -func (rc *RemoteConfig) toURL() (common.URL, error) { +func (rc *RemoteConfig) toURL() (*common.URL, error) { if len(rc.Protocol) == 0 { - return common.URL{}, perrors.Errorf("Must provide protocol in RemoteConfig.") + return nil, perrors.Errorf("Must provide protocol in RemoteConfig.") } return common.NewURL(rc.Address, common.WithUsername(rc.Username), diff --git a/config/service_config.go b/config/service_config.go index 9a274436dd510ce18d2dda6f11dd6d5ef298f0be..b3febc68d6143b77c08c6fafc5cda55c6e00ac05 100644 --- a/config/service_config.go +++ b/config/service_config.go @@ -208,7 +208,7 @@ func (c *ServiceConfig) Export() error { for _, regUrl := range regUrls { regUrl.SubURL = ivkURL - invoker := proxyFactory.GetInvoker(*regUrl) + invoker := proxyFactory.GetInvoker(regUrl) exporter := c.cacheProtocol.Export(invoker) if exporter == nil { return perrors.New(fmt.Sprintf("Registry protocol new exporter error, registry is {%v}, url is {%v}", regUrl, ivkURL)) @@ -216,7 +216,7 @@ func (c *ServiceConfig) Export() error { c.exporters = append(c.exporters, exporter) } } else { - invoker := proxyFactory.GetInvoker(*ivkURL) + invoker := proxyFactory.GetInvoker(ivkURL) exporter := extension.GetProtocol(protocolwrapper.FILTER).Export(invoker) if exporter == nil { return perrors.New(fmt.Sprintf("Filter protocol without registry new exporter error, url is {%v}", ivkURL)) @@ -326,8 +326,7 @@ func (c *ServiceConfig) GetExportedUrls() []*common.URL { if c.exported.Load() { var urls []*common.URL for _, exporter := range c.exporters { - url := exporter.GetInvoker().GetUrl() - urls = append(urls, &url) + urls = append(urls, exporter.GetInvoker().GetUrl()) } return urls } diff --git a/config_center/apollo/impl.go b/config_center/apollo/impl.go index ac5328c27a95425333276be58e6dd614e23bb5ac..c69fc2f66b23cd877b447fc78084fb9197c253aa 100644 --- a/config_center/apollo/impl.go +++ b/config_center/apollo/impl.go @@ -109,11 +109,11 @@ func getNamespaceName(namespace string, configFileFormat agolloConstant.ConfigFi } func (c *apolloConfiguration) GetInternalProperty(key string, opts ...cc.Option) (string, error) { - config := agollo.GetConfig(c.appConf.NamespaceName) - if config == nil { + newConfig := agollo.GetConfig(c.appConf.NamespaceName) + if newConfig == nil { return "", perrors.New(fmt.Sprintf("nothing in namespace:%s ", key)) } - return config.GetStringValue(key, ""), nil + return newConfig.GetStringValue(key, ""), nil } func (c *apolloConfiguration) GetRule(key string, opts ...cc.Option) (string, error) { @@ -135,11 +135,11 @@ func (c *apolloConfiguration) GetProperties(key string, opts ...cc.Option) (stri * when group is not null, we are getting startup configs(config file) from Config Center, for example: * key=dubbo.propertie */ - config := agollo.GetConfig(key) - if config == nil { + tmpConfig := agollo.GetConfig(key) + if tmpConfig == nil { return "", perrors.New(fmt.Sprintf("nothing in namespace:%s ", key)) } - return config.GetContent(), nil + return tmpConfig.GetContent(), nil } func (c *apolloConfiguration) getAddressWithProtocolPrefix(url *common.URL) string { diff --git a/config_center/apollo/impl_test.go b/config_center/apollo/impl_test.go index 50c4e689de4542e1c595d0778e2dce69b1e7dda9..4720775c285f84bd4fe2146240feea87c8a20817 100644 --- a/config_center/apollo/impl_test.go +++ b/config_center/apollo/impl_test.go @@ -197,7 +197,7 @@ func initMockApollo(t *testing.T) *apolloConfiguration { apolloUrl := strings.ReplaceAll(apollo.URL, "http", "apollo") url, err := common.NewURL(apolloUrl, common.WithParams(c.ConfigCenterConfig.GetUrlMap())) assert.NoError(t, err) - configuration, err := newApolloConfiguration(&url) + configuration, err := newApolloConfiguration(url) assert.NoError(t, err) return configuration } diff --git a/config_center/configurator/override_test.go b/config_center/configurator/override_test.go index 8eccb5091272b033cf31b612dfb19bce6514ccce..bb9c36776337c5dde1c5b2dcc9dd59ee82067a02 100644 --- a/config_center/configurator/override_test.go +++ b/config_center/configurator/override_test.go @@ -40,36 +40,36 @@ const ( 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(defaults, &url) + 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) + configurator.Configure(providerUrl) assert.Equal(t, failfast, providerUrl.GetParam(constant.CLUSTER_KEY, "")) } 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(defaults, &url) + 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) + configurator.Configure(providerUrl) assert.Equal(t, failover, providerUrl.GetParam(constant.CLUSTER_KEY, "")) } 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(defaults, &url) + 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) + configurator.Configure(providerUrl) assert.Equal(t, failfast, providerUrl.GetParam(constant.CLUSTER_KEY, "")) } @@ -77,11 +77,11 @@ func TestConfigureVerison2p6WithIp(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(defaults, &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) + configurator.Configure(providerUrl) assert.Equal(t, failfast, providerUrl.GetParam(constant.CLUSTER_KEY, "")) } diff --git a/config_center/dynamic_configuration.go b/config_center/dynamic_configuration.go index cbf8e8cf031ed20d6e69c5a3d7556f22ad4dc223..69f84213e7ecd226331821a07fc9bcfc48cd735c 100644 --- a/config_center/dynamic_configuration.go +++ b/config_center/dynamic_configuration.go @@ -89,6 +89,6 @@ func WithTimeout(time time.Duration) Option { } // GetRuleKey The format is '{interfaceName}:[version]:[group]' -func GetRuleKey(url common.URL) string { +func GetRuleKey(url *common.URL) string { return url.ColonSeparatedKey() } diff --git a/config_center/file/impl.go b/config_center/file/impl.go index 9d8254026bf3740631798bb0906436029be15abd..f29a33d5e2519b54a5496f5ea03ff170020bb28c 100644 --- a/config_center/file/impl.go +++ b/config_center/file/impl.go @@ -113,9 +113,8 @@ func (fsdc *FileSystemDynamicConfiguration) AddListener(key string, listener con opt(tmpOpts) } - path := fsdc.GetPath(key, tmpOpts.Group) - - fsdc.cacheListener.AddListener(path, listener) + tmpPath := fsdc.GetPath(key, tmpOpts.Group) + fsdc.cacheListener.AddListener(tmpPath, listener) } // RemoveListener Remove listener @@ -126,9 +125,8 @@ func (fsdc *FileSystemDynamicConfiguration) RemoveListener(key string, listener opt(tmpOpts) } - path := fsdc.GetPath(key, tmpOpts.Group) - - fsdc.cacheListener.RemoveListener(path, listener) + tmpPath := fsdc.GetPath(key, tmpOpts.Group) + fsdc.cacheListener.RemoveListener(tmpPath, listener) } // GetProperties get properties file @@ -138,12 +136,11 @@ func (fsdc *FileSystemDynamicConfiguration) GetProperties(key string, opts ...co opt(tmpOpts) } - path := fsdc.GetPath(key, tmpOpts.Group) - file, err := ioutil.ReadFile(path) + tmpPath := fsdc.GetPath(key, tmpOpts.Group) + file, err := ioutil.ReadFile(tmpPath) if err != nil { return "", perrors.WithStack(err) } - return string(file), nil } @@ -160,16 +157,16 @@ func (fsdc *FileSystemDynamicConfiguration) GetInternalProperty(key string, opts // PublishConfig will publish the config with the (key, group, value) pair func (fsdc *FileSystemDynamicConfiguration) PublishConfig(key string, group string, value string) error { - path := fsdc.GetPath(key, group) - return fsdc.write2File(path, value) + tmpPath := fsdc.GetPath(key, group) + return fsdc.write2File(tmpPath, value) } // GetConfigKeysByGroup will return all keys with the group func (fsdc *FileSystemDynamicConfiguration) GetConfigKeysByGroup(group string) (*gxset.HashSet, error) { - path := fsdc.GetPath("", group) + tmpPath := fsdc.GetPath("", group) r := gxset.NewSet() - fileInfo, _ := ioutil.ReadDir(path) + fileInfo, _ := ioutil.ReadDir(tmpPath) for _, file := range fileInfo { // list file @@ -185,8 +182,8 @@ func (fsdc *FileSystemDynamicConfiguration) GetConfigKeysByGroup(group string) ( // RemoveConfig will remove the config whit hte (key, group) func (fsdc *FileSystemDynamicConfiguration) RemoveConfig(key string, group string) error { - path := fsdc.GetPath(key, group) - _, err := fsdc.deleteDelay(path) + tmpPath := fsdc.GetPath(key, group) + _, err := fsdc.deleteDelay(tmpPath) return err } @@ -261,9 +258,9 @@ func substr(s string, pos, length int) string { // This uses an OS-specific method for discovering the home directory. // An error is returned if a home directory cannot be detected. func Home() (string, error) { - user, err := user.Current() + currentUser, err := user.Current() if nil == err { - return user.HomeDir, nil + return currentUser.HomeDir, nil } // cross compile support @@ -299,9 +296,9 @@ func homeUnix() (string, error) { func homeWindows() (string, error) { drive := os.Getenv("HOMEDRIVE") - path := os.Getenv("HOMEPATH") - home := drive + path - if drive == "" || path == "" { + homePath := os.Getenv("HOMEPATH") + home := drive + homePath + if drive == "" || homePath == "" { home = os.Getenv("USERPROFILE") } if home == "" { diff --git a/config_center/file/impl_test.go b/config_center/file/impl_test.go index 58892953d556512a88689baa5110995091d75f7b..e912cb7078fe42b514ba510db6b7f871ab998ea9 100644 --- a/config_center/file/impl_test.go +++ b/config_center/file/impl_test.go @@ -42,7 +42,7 @@ func initFileData(t *testing.T) (*FileSystemDynamicConfiguration, error) { urlString := "registry://127.0.0.1:2181" regurl, err := common.NewURL(urlString) assert.NoError(t, err) - dc, err := extension.GetConfigCenterFactory("file").GetDynamicConfiguration(®url) + dc, err := extension.GetConfigCenterFactory("file").GetDynamicConfiguration(regurl) assert.NoError(t, err) return dc.(*FileSystemDynamicConfiguration), err diff --git a/config_center/nacos/client.go b/config_center/nacos/client.go index acfe2609ceb0fc62650b7b494b25084ea4df6946..f3942c023d6bc7b7c7afe09863283cbc315fdb1f 100644 --- a/config_center/nacos/client.go +++ b/config_center/nacos/client.go @@ -122,7 +122,7 @@ func ValidateNacosClient(container nacosClientFacade, opts ...option) error { return perrors.WithMessagef(nil, "newNacosClient(address:%+v)", url.PrimitiveURL) } -func newNacosClient(name string, nacosAddrs []string, timeout time.Duration, url common.URL) (*NacosClient, error) { +func newNacosClient(name string, nacosAddrs []string, timeout time.Duration, url *common.URL) (*NacosClient, error) { var ( err error n *NacosClient @@ -149,8 +149,8 @@ func newNacosClient(name string, nacosAddrs []string, timeout time.Duration, url return n, nil } -func initNacosConfigClient(nacosAddrs []string, timeout time.Duration, url common.URL) (config_client.IConfigClient, error) { - svrConfList := []nacosconst.ServerConfig{} +func initNacosConfigClient(nacosAddrs []string, timeout time.Duration, url *common.URL) (config_client.IConfigClient, error) { + var svrConfList []nacosconst.ServerConfig for _, nacosAddr := range nacosAddrs { split := strings.Split(nacosAddr, ":") port, err := strconv.ParseUint(split[1], 10, 64) diff --git a/config_center/nacos/client_test.go b/config_center/nacos/client_test.go index 01319f362b956a0a15be8d5d4dde2a8b2be57c89..2ce3e375557c69721611799d414b3db31d141fca 100644 --- a/config_center/nacos/client_test.go +++ b/config_center/nacos/client_test.go @@ -36,7 +36,7 @@ func TestNewNacosClient(t *testing.T) { nacosURL := strings.ReplaceAll(server.URL, "http", "registry") registryUrl, _ := common.NewURL(nacosURL) c := &nacosDynamicConfiguration{ - url: ®istryUrl, + url: registryUrl, done: make(chan struct{}), } err := ValidateNacosClient(c, WithNacosName(nacosClientName)) @@ -59,7 +59,7 @@ func TestSetNacosClient(t *testing.T) { nacosURL := "registry://" + server.Listener.Addr().String() registryUrl, _ := common.NewURL(nacosURL) c := &nacosDynamicConfiguration{ - url: ®istryUrl, + url: registryUrl, done: make(chan struct{}), } var client *NacosClient @@ -93,7 +93,7 @@ func TestNewNacosClient_connectError(t *testing.T) { registryUrl, err := common.NewURL(nacosURL) assert.NoError(t, err) c := &nacosDynamicConfiguration{ - url: ®istryUrl, + url: registryUrl, done: make(chan struct{}), } err = ValidateNacosClient(c, WithNacosName(nacosClientName)) diff --git a/config_center/nacos/impl.go b/config_center/nacos/impl.go index be94b9a2e356b797b580ef4861895259ca7a4315..7c67930026369e7e2b6c58fc57d05d3a9edb50cc 100644 --- a/config_center/nacos/impl.go +++ b/config_center/nacos/impl.go @@ -186,8 +186,8 @@ func (n *nacosDynamicConfiguration) GetDone() chan struct{} { } // GetUrl Get Url -func (n *nacosDynamicConfiguration) GetUrl() common.URL { - return *n.url +func (n *nacosDynamicConfiguration) GetUrl() *common.URL { + return n.url } // Destroy Destroy configuration instance diff --git a/config_center/nacos/impl_test.go b/config_center/nacos/impl_test.go index 88d200edc927c62967975dff28e19c03743125f0..40efa5f4f288d0eff6d9648481cb2a14bfdb3931 100644 --- a/config_center/nacos/impl_test.go +++ b/config_center/nacos/impl_test.go @@ -73,7 +73,7 @@ func initNacosData(t *testing.T) (*nacosDynamicConfiguration, error) { nacosURL := strings.ReplaceAll(server.URL, "http", "registry") regurl, _ := common.NewURL(nacosURL) factory := &nacosDynamicConfigurationFactory{} - nacosConfiguration, err := factory.GetDynamicConfiguration(®url) + nacosConfiguration, err := factory.GetDynamicConfiguration(regurl) assert.NoError(t, err) nacosConfiguration.SetParser(&parser.DefaultConfigurationParser{}) @@ -105,7 +105,7 @@ func TestNacosDynamicConfiguration_GetConfigKeysByGroup(t *testing.T) { nacosURL := strings.ReplaceAll(ts.URL, "http", "registry") regurl, _ := common.NewURL(nacosURL) - nacosConfiguration, err := newNacosDynamicConfiguration(®url) + nacosConfiguration, err := newNacosDynamicConfiguration(regurl) assert.NoError(t, err) nacosConfiguration.SetParser(&parser.DefaultConfigurationParser{}) diff --git a/config_center/parser/configuration_parser.go b/config_center/parser/configuration_parser.go index f794221f9cf3c689d52b32a57ab51f7908f17297..b104d3ddb6b2e10842b82a0498e039cb7e17ab12 100644 --- a/config_center/parser/configuration_parser.go +++ b/config_center/parser/configuration_parser.go @@ -144,14 +144,14 @@ func serviceItemToUrls(item ConfigItem, config ConfiguratorConfig) ([]*common.UR if err != nil { return nil, perrors.WithStack(err) } - urls = append(urls, &url) + urls = append(urls, url) } } else { url, err := common.NewURL(urlStr) if err != nil { return nil, perrors.WithStack(err) } - urls = append(urls, &url) + urls = append(urls, url) } } return urls, nil @@ -192,7 +192,7 @@ func appItemToUrls(item ConfigItem, config ConfiguratorConfig) ([]*common.URL, e if err != nil { return nil, perrors.WithStack(err) } - urls = append(urls, &url) + urls = append(urls, url) } } return urls, nil diff --git a/config_center/zookeeper/impl.go b/config_center/zookeeper/impl.go index 485abcb5f0403050f0ed4797d8cce408a23eed62..17812e917f533d28c052c7cda3411de44b9aa7b5 100644 --- a/config_center/zookeeper/impl.go +++ b/config_center/zookeeper/impl.go @@ -183,8 +183,8 @@ func (c *zookeeperDynamicConfiguration) Done() chan struct{} { return c.done } -func (c *zookeeperDynamicConfiguration) GetUrl() common.URL { - return *c.url +func (c *zookeeperDynamicConfiguration) GetUrl() *common.URL { + return c.url } func (c *zookeeperDynamicConfiguration) Destroy() { diff --git a/config_center/zookeeper/impl_test.go b/config_center/zookeeper/impl_test.go index ecc3527c486fdd2aa2bc6f4d2f2adab1147e495a..d4a9de41fd62d48ce4528056289839a38285c9a3 100644 --- a/config_center/zookeeper/impl_test.go +++ b/config_center/zookeeper/impl_test.go @@ -50,7 +50,7 @@ func initZkData(group string, t *testing.T) (*zk.TestCluster, *zookeeperDynamicC assert.NoError(t, err) regurl.AddParam(constant.REGISTRY_TIMEOUT_KEY, "15s") zkFactory := &zookeeperDynamicConfigurationFactory{} - reg, err := zkFactory.GetDynamicConfiguration(®url) + reg, err := zkFactory.GetDynamicConfiguration(regurl) zreg, ok := reg.(*zookeeperDynamicConfiguration) assert.True(t, ok) assert.NoError(t, err) diff --git a/filter/filter_impl/auth/consumer_sign.go b/filter/filter_impl/auth/consumer_sign.go index 945cf3e6e7e728042b5422174162dd5aded50361..823db82bfcb0bb165ef36bb9d141650df1e01432 100644 --- a/filter/filter_impl/auth/consumer_sign.go +++ b/filter/filter_impl/auth/consumer_sign.go @@ -42,8 +42,8 @@ func (csf *ConsumerSignFilter) Invoke(ctx context.Context, invoker protocol.Invo logger.Infof("invoking ConsumerSign filter.") url := invoker.GetUrl() - err := doAuthWork(&url, func(authenticator filter.Authenticator) error { - return authenticator.Sign(invocation, &url) + err := doAuthWork(url, func(authenticator filter.Authenticator) error { + return authenticator.Sign(invocation, url) }) if err != nil { panic(fmt.Sprintf("Sign for invocation %s # %s failed", url.ServiceKey(), invocation.MethodName())) diff --git a/filter/filter_impl/auth/default_authenticator_test.go b/filter/filter_impl/auth/default_authenticator_test.go index 8b0fb6b0e3de04ccb2c30d2c7e22c32af5733742..37c7e9d1837a183e72db1134506cc3f89611ac76 100644 --- a/filter/filter_impl/auth/default_authenticator_test.go +++ b/filter/filter_impl/auth/default_authenticator_test.go @@ -48,7 +48,7 @@ func TestDefaultAuthenticator_Authenticate(t *testing.T) { }{"YUYU", 1}} inv := invocation.NewRPCInvocation("test", parmas, nil) requestTime := strconv.Itoa(int(time.Now().Unix() * 1000)) - signature, _ := getSignature(&testurl, inv, secret, requestTime) + signature, _ := getSignature(testurl, inv, secret, requestTime) var authenticator = &DefaultAuthenticator{} @@ -58,7 +58,7 @@ func TestDefaultAuthenticator_Authenticate(t *testing.T) { constant.REQUEST_TIMESTAMP_KEY: requestTime, constant.AK_KEY: access, }) - err := authenticator.Authenticate(invcation, &testurl) + err := authenticator.Authenticate(invcation, testurl) assert.Nil(t, err) // modify the params invcation = invocation.NewRPCInvocation("test", parmas[:1], map[string]interface{}{ @@ -67,7 +67,7 @@ func TestDefaultAuthenticator_Authenticate(t *testing.T) { constant.REQUEST_TIMESTAMP_KEY: requestTime, constant.AK_KEY: access, }) - err = authenticator.Authenticate(invcation, &testurl) + err = authenticator.Authenticate(invcation, testurl) assert.NotNil(t, err) } @@ -79,7 +79,7 @@ func TestDefaultAuthenticator_Sign(t *testing.T) { testurl.SetParam(constant.SECRET_ACCESS_KEY_KEY, "skey") testurl.SetParam(constant.PARAMTER_SIGNATURE_ENABLE_KEY, "false") inv := invocation.NewRPCInvocation("test", []interface{}{"OK"}, nil) - _ = authenticator.Sign(inv, &testurl) + _ = authenticator.Sign(inv, testurl) assert.NotEqual(t, inv.AttachmentsByKey(constant.REQUEST_SIGNATURE_KEY, ""), "") assert.NotEqual(t, inv.AttachmentsByKey(constant.CONSUMER, ""), "") assert.NotEqual(t, inv.AttachmentsByKey(constant.REQUEST_TIMESTAMP_KEY, ""), "") @@ -124,7 +124,7 @@ func Test_getSignatureWithinParams(t *testing.T) { }) secret := "dubbo" current := strconv.Itoa(int(time.Now().Unix() * 1000)) - signature, _ := getSignature(&testurl, inv, secret, current) + signature, _ := getSignature(testurl, inv, secret, current) requestString := fmt.Sprintf(constant.SIGNATURE_STRING_FORMAT, testurl.ColonSeparatedKey(), inv.MethodName(), secret, current) s, _ := SignWithParams(inv.Arguments(), requestString, secret) @@ -138,7 +138,7 @@ func Test_getSignature(t *testing.T) { inv := invocation.NewRPCInvocation("test", []interface{}{"OK"}, nil) secret := "dubbo" current := strconv.Itoa(int(time.Now().Unix() * 1000)) - signature, _ := getSignature(&testurl, inv, secret, current) + signature, _ := getSignature(testurl, inv, secret, current) requestString := fmt.Sprintf(constant.SIGNATURE_STRING_FORMAT, testurl.ColonSeparatedKey(), inv.MethodName(), secret, current) s := Sign(requestString, secret) diff --git a/filter/filter_impl/auth/provider_auth.go b/filter/filter_impl/auth/provider_auth.go index d5f5db300d4e7c94978d5d52e32f741f7d27bb48..774fdb2fb8f69bc33fcbee36faae28f8f6e6d0cc 100644 --- a/filter/filter_impl/auth/provider_auth.go +++ b/filter/filter_impl/auth/provider_auth.go @@ -42,8 +42,8 @@ func (paf *ProviderAuthFilter) Invoke(ctx context.Context, invoker protocol.Invo logger.Infof("invoking providerAuth filter.") url := invoker.GetUrl() - err := doAuthWork(&url, func(authenticator filter.Authenticator) error { - return authenticator.Authenticate(invocation, &url) + err := doAuthWork(url, func(authenticator filter.Authenticator) error { + return authenticator.Authenticate(invocation, url) }) if err != nil { logger.Infof("auth the request: %v occur exception, cause: %s", invocation, err.Error()) diff --git a/filter/filter_impl/auth/provider_auth_test.go b/filter/filter_impl/auth/provider_auth_test.go index f6ebfcd7abb83a55b4a09c1ec2d6c71b88bf7727..dc130b59851ddb02572103b2e29361f9fc8f1c59 100644 --- a/filter/filter_impl/auth/provider_auth_test.go +++ b/filter/filter_impl/auth/provider_auth_test.go @@ -52,7 +52,7 @@ func TestProviderAuthFilter_Invoke(t *testing.T) { } inv := invocation.NewRPCInvocation("test", parmas, nil) requestTime := strconv.Itoa(int(time.Now().Unix() * 1000)) - signature, _ := getSignature(&url, inv, secret, requestTime) + signature, _ := getSignature(url, inv, secret, requestTime) inv = invocation.NewRPCInvocation("test", []interface{}{"OK"}, map[string]interface{}{ constant.REQUEST_SIGNATURE_KEY: signature, diff --git a/filter/filter_impl/echo_filter_test.go b/filter/filter_impl/echo_filter_test.go index b821a1a30cb8af7e957fac45beecd46067627f91..f2ec81a3e63a81c66ef08d482f111e8bae5774b8 100644 --- a/filter/filter_impl/echo_filter_test.go +++ b/filter/filter_impl/echo_filter_test.go @@ -34,10 +34,10 @@ import ( func TestEchoFilterInvoke(t *testing.T) { filter := GetFilter() - result := filter.Invoke(context.Background(), protocol.NewBaseInvoker(common.URL{}), invocation.NewRPCInvocation("$echo", []interface{}{"OK"}, nil)) + result := filter.Invoke(context.Background(), protocol.NewBaseInvoker(&common.URL{}), invocation.NewRPCInvocation("$echo", []interface{}{"OK"}, nil)) assert.Equal(t, "OK", result.Result()) - result = filter.Invoke(context.Background(), protocol.NewBaseInvoker(common.URL{}), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, nil)) + result = filter.Invoke(context.Background(), protocol.NewBaseInvoker(&common.URL{}), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, nil)) assert.Nil(t, result.Error()) assert.Nil(t, result.Result()) } diff --git a/filter/filter_impl/execute_limit_filter_test.go b/filter/filter_impl/execute_limit_filter_test.go index 953f5e1cc8f6ff3299dcac21c5cd2a41de08cdc1..2aebcaa8fa62278da3092d6359d2a01571be37d0 100644 --- a/filter/filter_impl/execute_limit_filter_test.go +++ b/filter/filter_impl/execute_limit_filter_test.go @@ -44,7 +44,7 @@ func TestExecuteLimitFilterInvokeIgnored(t *testing.T) { limitFilter := GetExecuteLimitFilter() - result := limitFilter.Invoke(context.Background(), protocol.NewBaseInvoker(*invokeUrl), invoc) + result := limitFilter.Invoke(context.Background(), protocol.NewBaseInvoker(invokeUrl), invoc) assert.NotNil(t, result) assert.Nil(t, result.Error()) } @@ -61,7 +61,7 @@ func TestExecuteLimitFilterInvokeConfigureError(t *testing.T) { limitFilter := GetExecuteLimitFilter() - result := limitFilter.Invoke(context.Background(), protocol.NewBaseInvoker(*invokeUrl), invoc) + result := limitFilter.Invoke(context.Background(), protocol.NewBaseInvoker(invokeUrl), invoc) assert.NotNil(t, result) assert.Nil(t, result.Error()) } @@ -78,7 +78,7 @@ func TestExecuteLimitFilterInvoke(t *testing.T) { limitFilter := GetExecuteLimitFilter() - result := limitFilter.Invoke(context.Background(), protocol.NewBaseInvoker(*invokeUrl), invoc) + result := limitFilter.Invoke(context.Background(), protocol.NewBaseInvoker(invokeUrl), invoc) assert.NotNil(t, result) assert.Nil(t, result.Error()) } diff --git a/filter/filter_impl/graceful_shutdown_filter_test.go b/filter/filter_impl/graceful_shutdown_filter_test.go index 220ef6f20857aa06bcc45d3ac0a9bd52b0d65af2..447a557ad5f508bf444ccae5dacb8a8559c933ea 100644 --- a/filter/filter_impl/graceful_shutdown_filter_test.go +++ b/filter/filter_impl/graceful_shutdown_filter_test.go @@ -54,7 +54,7 @@ func TestGenericFilterInvoke(t *testing.T) { assert.Equal(t, extension.GetRejectedExecutionHandler(constant.DEFAULT_KEY), shutdownFilter.getRejectHandler()) - result := shutdownFilter.Invoke(context.Background(), protocol.NewBaseInvoker(*invokeUrl), invoc) + result := shutdownFilter.Invoke(context.Background(), protocol.NewBaseInvoker(invokeUrl), invoc) assert.NotNil(t, result) assert.Nil(t, result.Error()) @@ -65,7 +65,7 @@ func TestGenericFilterInvoke(t *testing.T) { shutdownFilter.shutdownConfig = providerConfig.ShutdownConfig assert.True(t, shutdownFilter.rejectNewRequest()) - result = shutdownFilter.OnResponse(nil, nil, protocol.NewBaseInvoker(*invokeUrl), invoc) + result = shutdownFilter.OnResponse(nil, nil, protocol.NewBaseInvoker(invokeUrl), invoc) rejectHandler := &common2.OnlyLogRejectedExecutionHandler{} extension.SetRejectedExecutionHandler("mock", func() filter.RejectedExecutionHandler { diff --git a/filter/filter_impl/hystrix_filter_test.go b/filter/filter_impl/hystrix_filter_test.go index eebbae55565aa7072846d368403605002df0c61b..4973ce7f70353a70befec74f1bab9333b6b58fd1 100644 --- a/filter/filter_impl/hystrix_filter_test.go +++ b/filter/filter_impl/hystrix_filter_test.go @@ -18,6 +18,7 @@ package filter_impl import ( "context" + "fmt" "regexp" "testing" ) @@ -29,6 +30,8 @@ import ( ) import ( + "github.com/apache/dubbo-go/common" + "github.com/apache/dubbo-go/common/constant" "github.com/apache/dubbo-go/protocol" "github.com/apache/dubbo-go/protocol/invocation" ) @@ -147,7 +150,11 @@ func (iv *testMockFailInvoker) Invoke(_ context.Context, _ protocol.Invocation) func TestHystrixFilterInvokeSuccess(t *testing.T) { hf := &HystrixFilter{} - result := hf.Invoke(context.Background(), &testMockSuccessInvoker{}, &invocation.RPCInvocation{}) + testUrl, err := common.NewURL( + fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT)) + assert.NoError(t, err) + testInvoker := testMockSuccessInvoker{*protocol.NewBaseInvoker(testUrl)} + result := hf.Invoke(context.Background(), &testInvoker, &invocation.RPCInvocation{}) assert.NotNil(t, result) assert.NoError(t, result.Error()) assert.NotNil(t, result.Result()) @@ -155,7 +162,11 @@ func TestHystrixFilterInvokeSuccess(t *testing.T) { func TestHystrixFilterInvokeFail(t *testing.T) { hf := &HystrixFilter{} - result := hf.Invoke(context.Background(), &testMockFailInvoker{}, &invocation.RPCInvocation{}) + testUrl, err := common.NewURL( + fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT)) + assert.NoError(t, err) + testInvoker := testMockFailInvoker{*protocol.NewBaseInvoker(testUrl)} + result := hf.Invoke(context.Background(), &testInvoker, &invocation.RPCInvocation{}) assert.NotNil(t, result) assert.Error(t, result.Error()) } @@ -167,7 +178,11 @@ func TestHystricFilterInvokeCircuitBreak(t *testing.T) { resChan := make(chan protocol.Result, 50) for i := 0; i < 50; i++ { go func() { - result := hf.Invoke(context.Background(), &testMockFailInvoker{}, &invocation.RPCInvocation{}) + testUrl, err := common.NewURL( + fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT)) + assert.NoError(t, err) + testInvoker := testMockSuccessInvoker{*protocol.NewBaseInvoker(testUrl)} + result := hf.Invoke(context.Background(), &testInvoker, &invocation.RPCInvocation{}) resChan <- result }() } @@ -192,7 +207,11 @@ func TestHystricFilterInvokeCircuitBreakOmitException(t *testing.T) { resChan := make(chan protocol.Result, 50) for i := 0; i < 50; i++ { go func() { - result := hf.Invoke(context.Background(), &testMockFailInvoker{}, &invocation.RPCInvocation{}) + testUrl, err := common.NewURL( + fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT)) + assert.NoError(t, err) + testInvoker := testMockSuccessInvoker{*protocol.NewBaseInvoker(testUrl)} + result := hf.Invoke(context.Background(), &testInvoker, &invocation.RPCInvocation{}) resChan <- result }() } diff --git a/filter/filter_impl/sentinel_filter.go b/filter/filter_impl/sentinel_filter.go index 86d6460acd840fb85b821f50c81f944da4c1b926..aec814d70a5f1dfc9e6688b9731f725f43443b93 100644 --- a/filter/filter_impl/sentinel_filter.go +++ b/filter/filter_impl/sentinel_filter.go @@ -229,7 +229,7 @@ func getInterfaceGroupAndVersionEnabled() bool { return true } -func getColonSeparatedKey(url common.URL) string { +func getColonSeparatedKey(url *common.URL) string { return fmt.Sprintf("%s:%s:%s", url.Service(), url.GetParam(constant.GROUP_KEY, ""), diff --git a/filter/filter_impl/token_filter_test.go b/filter/filter_impl/token_filter_test.go index cd1bba3d4a830822c67f1e6157653d5477264c94..9ef8c98d6868c3d545fe963ab13eb3f27bb88cd0 100644 --- a/filter/filter_impl/token_filter_test.go +++ b/filter/filter_impl/token_filter_test.go @@ -43,7 +43,7 @@ func TestTokenFilterInvoke(t *testing.T) { attch := make(map[string]interface{}, 0) attch[constant.TOKEN_KEY] = "ori_key" result := filter.Invoke(context.Background(), - protocol.NewBaseInvoker(*url), + protocol.NewBaseInvoker(url), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch)) assert.Nil(t, result.Error()) @@ -56,7 +56,7 @@ func TestTokenFilterInvokeEmptyToken(t *testing.T) { testUrl := common.URL{} attch := make(map[string]interface{}, 0) attch[constant.TOKEN_KEY] = "ori_key" - result := filter.Invoke(context.Background(), protocol.NewBaseInvoker(testUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch)) + result := filter.Invoke(context.Background(), protocol.NewBaseInvoker(&testUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch)) assert.Nil(t, result.Error()) assert.Nil(t, result.Result()) } @@ -68,7 +68,7 @@ func TestTokenFilterInvokeEmptyAttach(t *testing.T) { common.WithParams(url.Values{}), common.WithParamsValue(constant.TOKEN_KEY, "ori_key")) attch := make(map[string]interface{}, 0) - result := filter.Invoke(context.Background(), protocol.NewBaseInvoker(*testUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch)) + result := filter.Invoke(context.Background(), protocol.NewBaseInvoker(testUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch)) assert.NotNil(t, result.Error()) } @@ -81,6 +81,6 @@ func TestTokenFilterInvokeNotEqual(t *testing.T) { attch := make(map[string]interface{}, 0) attch[constant.TOKEN_KEY] = "err_key" result := filter.Invoke(context.Background(), - protocol.NewBaseInvoker(*testUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch)) + protocol.NewBaseInvoker(testUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch)) assert.NotNil(t, result.Error()) } diff --git a/filter/filter_impl/tps/tps_limiter_method_service.go b/filter/filter_impl/tps/tps_limiter_method_service.go index 5761579a38a22500d54193a9564170cc0215cf0f..f0c276438beaa161a6f6b13bc95c1fd7f357e8b6 100644 --- a/filter/filter_impl/tps/tps_limiter_method_service.go +++ b/filter/filter_impl/tps/tps_limiter_method_service.go @@ -120,7 +120,7 @@ type MethodServiceTpsLimiterImpl struct { // The key point is how to keep thread-safe // This implementation use concurrent map + loadOrStore to make implementation thread-safe // You can image that even multiple threads create limiter, but only one could store the limiter into tpsState -func (limiter MethodServiceTpsLimiterImpl) IsAllowable(url common.URL, invocation protocol.Invocation) bool { +func (limiter MethodServiceTpsLimiterImpl) IsAllowable(url *common.URL, invocation protocol.Invocation) bool { methodConfigPrefix := "methods." + invocation.MethodName() + "." @@ -176,7 +176,7 @@ func (limiter MethodServiceTpsLimiterImpl) IsAllowable(url common.URL, invocatio // If we can convert the methodLevelConfig to int64, return; // Or, we will try to look up server-level configuration and then convert it to int64 func getLimitConfig(methodLevelConfig string, - url common.URL, + url *common.URL, invocation protocol.Invocation, configKey string, defaultVal string) int64 { diff --git a/filter/filter_impl/tps/tps_limiter_method_service_test.go b/filter/filter_impl/tps/tps_limiter_method_service_test.go index 61f28e442f4b76d18d7750aa58831c322f939207..7435d9b92ac8270de0244c8a257aec82f9acc9a1 100644 --- a/filter/filter_impl/tps/tps_limiter_method_service_test.go +++ b/filter/filter_impl/tps/tps_limiter_method_service_test.go @@ -57,7 +57,7 @@ func TestMethodServiceTpsLimiterImplIsAllowableOnlyServiceLevel(t *testing.T) { }) limiter := GetMethodServiceTpsLimiter() - result := limiter.IsAllowable(*invokeUrl, invoc) + result := limiter.IsAllowable(invokeUrl, invoc) assert.True(t, result) } @@ -73,7 +73,7 @@ func TestMethodServiceTpsLimiterImplIsAllowableNoConfig(t *testing.T) { common.WithParamsValue(constant.TPS_LIMIT_RATE_KEY, "")) limiter := GetMethodServiceTpsLimiter() - result := limiter.IsAllowable(*invokeUrl, invoc) + result := limiter.IsAllowable(invokeUrl, invoc) assert.True(t, result) } @@ -106,7 +106,7 @@ func TestMethodServiceTpsLimiterImplIsAllowableMethodLevelOverride(t *testing.T) }) limiter := GetMethodServiceTpsLimiter() - result := limiter.IsAllowable(*invokeUrl, invoc) + result := limiter.IsAllowable(invokeUrl, invoc) assert.True(t, result) } @@ -136,7 +136,7 @@ func TestMethodServiceTpsLimiterImplIsAllowableBothMethodAndService(t *testing.T }) limiter := GetMethodServiceTpsLimiter() - result := limiter.IsAllowable(*invokeUrl, invoc) + result := limiter.IsAllowable(invokeUrl, invoc) assert.True(t, result) } diff --git a/filter/filter_impl/tps/tps_limiter_mock.go b/filter/filter_impl/tps/tps_limiter_mock.go index b49084f28e7d4b62d64762170b6dfbbec4a4de96..34c279032713595066638095b5f4d2f6fa2c4aa4 100644 --- a/filter/filter_impl/tps/tps_limiter_mock.go +++ b/filter/filter_impl/tps/tps_limiter_mock.go @@ -58,7 +58,7 @@ func (m *MockTpsLimiter) EXPECT() *MockTpsLimiterMockRecorder { } // IsAllowable mocks base method -func (m *MockTpsLimiter) IsAllowable(arg0 common.URL, arg1 protocol.Invocation) bool { +func (m *MockTpsLimiter) IsAllowable(arg0 *common.URL, arg1 protocol.Invocation) bool { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "IsAllowable", arg0, arg1) ret0, _ := ret[0].(bool) diff --git a/filter/filter_impl/tps_limit_filter_test.go b/filter/filter_impl/tps_limit_filter_test.go index da0fc482ce559dad52947786823f604128857c30..88e778105081129463b68618804bd9204d2f7113 100644 --- a/filter/filter_impl/tps_limit_filter_test.go +++ b/filter/filter_impl/tps_limit_filter_test.go @@ -47,7 +47,7 @@ func TestTpsLimitFilterInvokeWithNoTpsLimiter(t *testing.T) { attch := make(map[string]interface{}, 0) result := tpsFilter.Invoke(context.Background(), - protocol.NewBaseInvoker(*invokeUrl), + protocol.NewBaseInvoker(invokeUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch)) assert.Nil(t, result.Error()) @@ -71,7 +71,7 @@ func TestGenericFilterInvokeWithDefaultTpsLimiter(t *testing.T) { attch := make(map[string]interface{}, 0) result := tpsFilter.Invoke(context.Background(), - protocol.NewBaseInvoker(*invokeUrl), + protocol.NewBaseInvoker(invokeUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch)) assert.Nil(t, result.Error()) @@ -102,7 +102,9 @@ func TestGenericFilterInvokeWithDefaultTpsLimiterNotAllow(t *testing.T) { attch := make(map[string]interface{}, 0) result := tpsFilter.Invoke(context.Background(), - protocol.NewBaseInvoker(*invokeUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch)) + protocol.NewBaseInvoker( + + invokeUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch)) assert.Nil(t, result.Error()) assert.Nil(t, result.Result()) } diff --git a/filter/handler/rejected_execution_handler_mock.go b/filter/handler/rejected_execution_handler_mock.go index bff54769cb007ed2fce5a7623c96edc370e63903..5f2f458f83d0ca2cdff68eec4d0f3d22cf4e3277 100644 --- a/filter/handler/rejected_execution_handler_mock.go +++ b/filter/handler/rejected_execution_handler_mock.go @@ -58,7 +58,7 @@ func (m *MockRejectedExecutionHandler) EXPECT() *MockRejectedExecutionHandlerMoc } // RejectedExecution mocks base method -func (m *MockRejectedExecutionHandler) RejectedExecution(url common.URL, invocation protocol.Invocation) protocol.Result { +func (m *MockRejectedExecutionHandler) RejectedExecution(url *common.URL, invocation protocol.Invocation) protocol.Result { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RejectedExecution", url, invocation) ret0, _ := ret[0].(protocol.Result) diff --git a/filter/handler/rejected_execution_handler_only_log.go b/filter/handler/rejected_execution_handler_only_log.go index 52ac1765f78172c0062de8884198e759b8d494ca..5242b5b49e8a12322821481d237d84710c15eafd 100644 --- a/filter/handler/rejected_execution_handler_only_log.go +++ b/filter/handler/rejected_execution_handler_only_log.go @@ -63,7 +63,7 @@ type OnlyLogRejectedExecutionHandler struct { } // RejectedExecution will do nothing, it only log the invocation. -func (handler *OnlyLogRejectedExecutionHandler) RejectedExecution(url common.URL, +func (handler *OnlyLogRejectedExecutionHandler) RejectedExecution(url *common.URL, _ protocol.Invocation) protocol.Result { logger.Errorf("The invocation was rejected. url: %s", url.String()) diff --git a/filter/handler/rejected_execution_handler_only_log_test.go b/filter/handler/rejected_execution_handler_only_log_test.go index 409f09f61bd958992749231fca045b54601fc627..7aa4aff936d6da1e46ed5a24609a0346e9d2edb4 100644 --- a/filter/handler/rejected_execution_handler_only_log_test.go +++ b/filter/handler/rejected_execution_handler_only_log_test.go @@ -31,5 +31,5 @@ func TestOnlyLogRejectedExecutionHandler_RejectedExecution(t *testing.T) { invokeUrl := common.NewURLWithOptions( common.WithParams(url.Values{}), common.WithParamsValue(constant.INTERFACE_KEY, "methodName")) - handler.RejectedExecution(*invokeUrl, nil) + handler.RejectedExecution(invokeUrl, nil) } diff --git a/filter/rejected_execution_handler.go b/filter/rejected_execution_handler.go index 3d1e1c1e641a836411ce0f71f97acf5d5a55f6d1..73ac3d3bbf37cbce5822e1955fb49f84bdf6d678 100644 --- a/filter/rejected_execution_handler.go +++ b/filter/rejected_execution_handler.go @@ -33,5 +33,5 @@ import ( type RejectedExecutionHandler interface { // RejectedExecution will be called if the invocation was rejected by some component. - RejectedExecution(url common.URL, invocation protocol.Invocation) protocol.Result + RejectedExecution(url *common.URL, invocation protocol.Invocation) protocol.Result } diff --git a/filter/tps_limiter.go b/filter/tps_limiter.go index 8385d7b5d84a420b54df6bf51e32a35d17e1b249..6f2466c0a40620b9f7dee358db681c4032c773fc 100644 --- a/filter/tps_limiter.go +++ b/filter/tps_limiter.go @@ -35,5 +35,5 @@ import ( */ type TpsLimiter interface { // IsAllowable will check whether this invocation should be enabled for further process - IsAllowable(common.URL, protocol.Invocation) bool + IsAllowable(*common.URL, protocol.Invocation) bool } diff --git a/metadata/definition/definition.go b/metadata/definition/definition.go index dbbc0c8f1685edf1a26ab1fe4ad091c501e76f5f..a0323137b70ff6ea34249b10e82d4f5cd84c9cb0 100644 --- a/metadata/definition/definition.go +++ b/metadata/definition/definition.go @@ -93,7 +93,7 @@ type TypeDefinition struct { } // BuildServiceDefinition can build service definition which will be used to describe a service -func BuildServiceDefinition(service common.Service, url common.URL) *ServiceDefinition { +func BuildServiceDefinition(service common.Service, url *common.URL) *ServiceDefinition { sd := &ServiceDefinition{} sd.CanonicalName = url.Service() diff --git a/metadata/identifier/service_metadata_identifier.go b/metadata/identifier/service_metadata_identifier.go index b9e65967e0f707a6efcc9f8ded2ce5dec4f058b8..3035cf3d720bd453baecb147c605f1bfc928d825 100644 --- a/metadata/identifier/service_metadata_identifier.go +++ b/metadata/identifier/service_metadata_identifier.go @@ -32,7 +32,7 @@ type ServiceMetadataIdentifier struct { // NewServiceMetadataIdentifier create instance. // The ServiceInterface is the @url.Service() // other parameters are read from @url -func NewServiceMetadataIdentifier(url common.URL) *ServiceMetadataIdentifier { +func NewServiceMetadataIdentifier(url *common.URL) *ServiceMetadataIdentifier { return &ServiceMetadataIdentifier{ BaseMetadataIdentifier: BaseMetadataIdentifier{ ServiceInterface: url.Service(), diff --git a/metadata/report/consul/report.go b/metadata/report/consul/report.go index eb2bdc25ecec596a8f89abb80856b8d6e7be70a4..e211f7fde4d462bd20603af54444036681a46f4d 100644 --- a/metadata/report/consul/report.go +++ b/metadata/report/consul/report.go @@ -61,7 +61,7 @@ func (m *consulMetadataReport) StoreConsumerMetadata(consumerMetadataIdentifier } // SaveServiceMetadata saves the metadata. -func (m *consulMetadataReport) SaveServiceMetadata(metadataIdentifier *identifier.ServiceMetadataIdentifier, url common.URL) error { +func (m *consulMetadataReport) SaveServiceMetadata(metadataIdentifier *identifier.ServiceMetadataIdentifier, url *common.URL) error { kv := &consul.KVPair{Key: metadataIdentifier.GetIdentifierKey(), Value: []byte(url.String())} _, err := m.client.KV().Put(kv, nil) return err diff --git a/metadata/report/consul/report_test.go b/metadata/report/consul/report_test.go index e07a7429f12bac0cfa4b2701d3e87ef25bcb077a..13d0c419bc0f0ff8426f73d4de5c85a346416770 100644 --- a/metadata/report/consul/report_test.go +++ b/metadata/report/consul/report_test.go @@ -100,7 +100,7 @@ func (suite *consulMetadataReportTestSuite) testStoreConsumerMetadata() { assert.NoError(suite.t, err) } -func (suite *consulMetadataReportTestSuite) testSaveServiceMetadata(url common.URL) { +func (suite *consulMetadataReportTestSuite) testSaveServiceMetadata(url *common.URL) { serviceMi := newServiceMetadataIdentifier("provider") err := suite.m.SaveServiceMetadata(serviceMi, url) assert.NoError(suite.t, err) @@ -119,7 +119,7 @@ func (suite *consulMetadataReportTestSuite) testGetExportedURLs() { assert.NoError(suite.t, err) } -func (suite *consulMetadataReportTestSuite) testSaveSubscribedData(url common.URL) { +func (suite *consulMetadataReportTestSuite) testSaveSubscribedData(url *common.URL) { subscribeMi := newSubscribeMetadataIdentifier("provider") urls := []string{url.String()} bytes, _ := json.Marshal(urls) @@ -152,10 +152,10 @@ func test1(t *testing.T) { suite := newConsulMetadataReportTestSuite(t, m) suite.testStoreProviderMetadata() suite.testStoreConsumerMetadata() - suite.testSaveServiceMetadata(*url) + suite.testSaveServiceMetadata(url) suite.testGetExportedURLs() suite.testRemoveServiceMetadata() - suite.testSaveSubscribedData(*url) + suite.testSaveSubscribedData(url) suite.testGetSubscribedURLs() suite.testGetServiceDefinition() } diff --git a/metadata/report/delegate/delegate_report.go b/metadata/report/delegate/delegate_report.go index cdd29ab2e483647ed90f37032e10d174f7583e39..836a8f9ef4aac23558e44c1c9c5adedd585d6da4 100644 --- a/metadata/report/delegate/delegate_report.go +++ b/metadata/report/delegate/delegate_report.go @@ -94,7 +94,7 @@ func (mrr *metadataReportRetry) startRetryTask() { // MetadataReport is a absolute delegate for MetadataReport type MetadataReport struct { - reportUrl common.URL + reportUrl *common.URL syncReport bool metadataReportRetry *metadataReportRetry @@ -215,7 +215,7 @@ func (mr *MetadataReport) StoreConsumerMetadata(identifier *identifier.MetadataI } // SaveServiceMetadata will delegate to call remote metadata's sdk to save service metadata -func (mr *MetadataReport) SaveServiceMetadata(identifier *identifier.ServiceMetadataIdentifier, url common.URL) error { +func (mr *MetadataReport) SaveServiceMetadata(identifier *identifier.ServiceMetadataIdentifier, url *common.URL) error { report := instance.GetMetadataReportInstance() if mr.syncReport { return report.SaveServiceMetadata(identifier, url) @@ -241,7 +241,7 @@ func (mr *MetadataReport) GetExportedURLs(identifier *identifier.ServiceMetadata } // SaveSubscribedData will delegate to call remote metadata's sdk to save subscribed data -func (mr *MetadataReport) SaveSubscribedData(identifier *identifier.SubscriberMetadataIdentifier, urls []common.URL) error { +func (mr *MetadataReport) SaveSubscribedData(identifier *identifier.SubscriberMetadataIdentifier, urls []*common.URL) error { urlStrList := make([]string, 0, len(urls)) for _, url := range urls { urlStrList = append(urlStrList, url.String()) @@ -260,13 +260,13 @@ func (mr *MetadataReport) SaveSubscribedData(identifier *identifier.SubscriberMe } // GetSubscribedURLs will delegate to call remote metadata's sdk to get subscribed urls -func (MetadataReport) GetSubscribedURLs(identifier *identifier.SubscriberMetadataIdentifier) ([]string, error) { +func (mr *MetadataReport) GetSubscribedURLs(identifier *identifier.SubscriberMetadataIdentifier) ([]string, error) { report := instance.GetMetadataReportInstance() return report.GetSubscribedURLs(identifier) } // GetServiceDefinition will delegate to call remote metadata's sdk to get service definitions -func (MetadataReport) GetServiceDefinition(identifier *identifier.MetadataIdentifier) (string, error) { +func (mr *MetadataReport) GetServiceDefinition(identifier *identifier.MetadataIdentifier) (string, error) { report := instance.GetMetadataReportInstance() return report.GetServiceDefinition(identifier) } diff --git a/metadata/report/etcd/report.go b/metadata/report/etcd/report.go index 097835c986962850d137255ec807b417de1484ad..1939b911822b6b5db3d41f999d4dcb4ca3fae1f2 100644 --- a/metadata/report/etcd/report.go +++ b/metadata/report/etcd/report.go @@ -63,7 +63,7 @@ func (e *etcdMetadataReport) StoreConsumerMetadata(consumerMetadataIdentifier *i // SaveServiceMetadata will store the metadata // metadata including the basic info of the server, service info, and other user custom info -func (e *etcdMetadataReport) SaveServiceMetadata(metadataIdentifier *identifier.ServiceMetadataIdentifier, url common.URL) error { +func (e *etcdMetadataReport) SaveServiceMetadata(metadataIdentifier *identifier.ServiceMetadataIdentifier, url *common.URL) error { key := e.getNodeKey(metadataIdentifier) return e.client.Create(key, url.String()) } diff --git a/metadata/report/etcd/report_test.go b/metadata/report/etcd/report_test.go index 5dd8780b48a741a8eb8735b059bc3617a100f63d..28c04869822b166f99d98e91ec6ec3b7fe6626cc 100644 --- a/metadata/report/etcd/report_test.go +++ b/metadata/report/etcd/report_test.go @@ -60,7 +60,7 @@ func TestEtcdMetadataReportFactory_CreateMetadataReport(t *testing.T) { t.Fatal(err) } metadataReportFactory := &etcdMetadataReportFactory{} - metadataReport := metadataReportFactory.CreateMetadataReport(&url) + metadataReport := metadataReportFactory.CreateMetadataReport(url) assert.NotNil(t, metadataReport) e.Close() } @@ -72,7 +72,7 @@ func TestEtcdMetadataReport_CRUD(t *testing.T) { t.Fatal(err) } metadataReportFactory := &etcdMetadataReportFactory{} - metadataReport := metadataReportFactory.CreateMetadataReport(&url) + metadataReport := metadataReportFactory.CreateMetadataReport(url) assert.NotNil(t, metadataReport) err = metadataReport.StoreConsumerMetadata(newMetadataIdentifier("consumer"), "consumer metadata") diff --git a/metadata/report/nacos/report.go b/metadata/report/nacos/report.go index d69913bd8fbb04da2d50770c1196917cb1efdaa5..42e9859c9fae70cc110dc45fca43dd95a5627d6e 100644 --- a/metadata/report/nacos/report.go +++ b/metadata/report/nacos/report.go @@ -69,7 +69,7 @@ func (n *nacosMetadataReport) StoreConsumerMetadata(consumerMetadataIdentifier * } // SaveServiceMetadata saves the metadata. -func (n *nacosMetadataReport) SaveServiceMetadata(metadataIdentifier *identifier.ServiceMetadataIdentifier, url common.URL) error { +func (n *nacosMetadataReport) SaveServiceMetadata(metadataIdentifier *identifier.ServiceMetadataIdentifier, url *common.URL) error { return n.storeMetadata(vo.ConfigParam{ DataId: metadataIdentifier.GetIdentifierKey(), Group: metadataIdentifier.Group, diff --git a/metadata/report/nacos/report_test.go b/metadata/report/nacos/report_test.go index be01eb22f7e95966c3bf816fdf648629b64380a3..b40b4380dbf8339277436b77d26d9ee3ab728a21 100644 --- a/metadata/report/nacos/report_test.go +++ b/metadata/report/nacos/report_test.go @@ -111,6 +111,6 @@ func TestNacosMetadataReportFactory_CreateMetadataReport(t *testing.T) { func newTestReport() report.MetadataReport { regurl, _ := common.NewURL("registry://console.nacos.io:80", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER))) - res := extension.GetMetadataReportFactory("nacos").CreateMetadataReport(®url) + res := extension.GetMetadataReportFactory("nacos").CreateMetadataReport(regurl) return res } diff --git a/metadata/report/report.go b/metadata/report/report.go index 62a9055e843297bd0d69ad94cb09ece64efda85f..dcb414209c1e6188dc195e9609f60124adaf2173 100644 --- a/metadata/report/report.go +++ b/metadata/report/report.go @@ -38,7 +38,7 @@ type MetadataReport interface { // SaveServiceMetadata saves the metadata. // Metadata includes the basic info of the server, // service info, and other user custom info. - SaveServiceMetadata(*identifier.ServiceMetadataIdentifier, common.URL) error + SaveServiceMetadata(*identifier.ServiceMetadataIdentifier, *common.URL) error // RemoveServiceMetadata removes the metadata. RemoveServiceMetadata(*identifier.ServiceMetadataIdentifier) error diff --git a/metadata/report/zookeeper/report.go b/metadata/report/zookeeper/report.go index 8f46bb023054ec27ca0dbff2c249dc0135af07cd..5d5e74007b9901276d7144bf0b052018e2f7e0a7 100644 --- a/metadata/report/zookeeper/report.go +++ b/metadata/report/zookeeper/report.go @@ -63,7 +63,7 @@ func (m *zookeeperMetadataReport) StoreConsumerMetadata(consumerMetadataIdentifi } // SaveServiceMetadata saves the metadata. -func (m *zookeeperMetadataReport) SaveServiceMetadata(metadataIdentifier *identifier.ServiceMetadataIdentifier, url common.URL) error { +func (m *zookeeperMetadataReport) SaveServiceMetadata(metadataIdentifier *identifier.ServiceMetadataIdentifier, url *common.URL) error { k := m.rootDir + metadataIdentifier.GetFilePathKey() return m.client.CreateWithValue(k, []byte(url.String())) } diff --git a/metadata/report/zookeeper/report_test.go b/metadata/report/zookeeper/report_test.go index a1e46e2e8d019c0415699ee409833b392a85b504..adedaaa6f4bd71511385085118f55538a5deb091 100644 --- a/metadata/report/zookeeper/report_test.go +++ b/metadata/report/zookeeper/report_test.go @@ -100,7 +100,7 @@ func (suite *zookeeperMetadataReportTestSuite) testStoreConsumerMetadata() { assert.NoError(suite.t, err) } -func (suite *zookeeperMetadataReportTestSuite) testSaveServiceMetadata(url common.URL) { +func (suite *zookeeperMetadataReportTestSuite) testSaveServiceMetadata(url *common.URL) { serviceMi := newServiceMetadataIdentifier("provider") err := suite.m.SaveServiceMetadata(serviceMi, url) assert.NoError(suite.t, err) @@ -119,7 +119,7 @@ func (suite *zookeeperMetadataReportTestSuite) testGetExportedURLs() { assert.NoError(suite.t, err) } -func (suite *zookeeperMetadataReportTestSuite) testSaveSubscribedData(url common.URL) { +func (suite *zookeeperMetadataReportTestSuite) testSaveSubscribedData(url *common.URL) { subscribeMi := newSubscribeMetadataIdentifier("provider") urls := []string{url.String()} bytes, _ := json.Marshal(urls) @@ -153,10 +153,10 @@ func test1(t *testing.T) { suite := newZookeeperMetadataReportTestSuite(t, m) suite.testStoreProviderMetadata() suite.testStoreConsumerMetadata() - suite.testSaveServiceMetadata(*url) + suite.testSaveServiceMetadata(url) suite.testGetExportedURLs() suite.testRemoveServiceMetadata() - suite.testSaveSubscribedData(*url) + suite.testSaveSubscribedData(url) suite.testGetSubscribedURLs() suite.testGetServiceDefinition() } diff --git a/metadata/service/exporter/configurable/exporter_test.go b/metadata/service/exporter/configurable/exporter_test.go index ceda2550e2e60ed2e587dabe92cca20831e708a6..2a5e646acdf86d2d9d339ae7ae377c7098b2e1b6 100644 --- a/metadata/service/exporter/configurable/exporter_test.go +++ b/metadata/service/exporter/configurable/exporter_test.go @@ -65,9 +65,9 @@ func TestConfigurableExporter(t *testing.T) { t.Run("configurableExporter", func(t *testing.T) { registryURL, _ := common.NewURL("service-discovery://localhost:12345") subURL, _ := common.NewURL("dubbo://localhost:20003") - registryURL.SubURL = &subURL + registryURL.SubURL = subURL assert.Equal(t, false, exported.IsExported()) - assert.NoError(t, exported.Export(®istryURL)) + assert.NoError(t, exported.Export(registryURL)) assert.Equal(t, true, exported.IsExported()) assert.Regexp(t, "dubbo://:20003/MetadataService*", exported.GetExportedURLs()[0].String()) exported.Unexport() diff --git a/metadata/service/inmemory/metadata_service_proxy_factory.go b/metadata/service/inmemory/metadata_service_proxy_factory.go index 1f8eeaa55f4a0240746508fee2ff088e3a653ca5..becd804f6741e27dda418a4ac9ce976755c634c4 100644 --- a/metadata/service/inmemory/metadata_service_proxy_factory.go +++ b/metadata/service/inmemory/metadata_service_proxy_factory.go @@ -50,7 +50,7 @@ func createProxy(ins registry.ServiceInstance) service.MetadataService { u := urls[0] p := extension.GetProtocol(u.Protocol) - invoker := p.Refer(*u) + invoker := p.Refer(u) return &MetadataServiceProxy{ invkr: invoker, } diff --git a/metadata/service/inmemory/metadata_service_proxy_factory_test.go b/metadata/service/inmemory/metadata_service_proxy_factory_test.go index 96020e1eb762442f946ccf8b368d6ebe9429d05e..f5e519cd5d2f83b85eaccf636e6771c18c74c277 100644 --- a/metadata/service/inmemory/metadata_service_proxy_factory_test.go +++ b/metadata/service/inmemory/metadata_service_proxy_factory_test.go @@ -66,11 +66,11 @@ func TestCreateProxy(t *testing.T) { type mockProtocol struct { } -func (m mockProtocol) Export(invoker protocol.Invoker) protocol.Exporter { +func (m mockProtocol) Export(protocol.Invoker) protocol.Exporter { panic("implement me") } -func (m mockProtocol) Refer(url common.URL) protocol.Invoker { +func (m mockProtocol) Refer(*common.URL) protocol.Invoker { return &mockInvoker{} } @@ -81,7 +81,7 @@ func (m mockProtocol) Destroy() { type mockInvoker struct { } -func (m *mockInvoker) GetUrl() common.URL { +func (m *mockInvoker) GetUrl() *common.URL { panic("implement me") } diff --git a/metadata/service/inmemory/service.go b/metadata/service/inmemory/service.go index 8269e691f1794fd9ac4b6091c157539e39ad7072..d9cbd5430527511acac1f7127b819d3832d80552 100644 --- a/metadata/service/inmemory/service.go +++ b/metadata/service/inmemory/service.go @@ -22,7 +22,6 @@ import ( ) import ( - cm "github.com/Workiva/go-datastructures/common" "github.com/Workiva/go-datastructures/slice/skip" ) @@ -75,23 +74,6 @@ func NewMetadataService() (service.MetadataService, error) { return metadataServiceInstance, nil } -// Comparator is defined as Comparator for skip list to compare the URL -type Comparator common.URL - -// Compare is defined as Comparator for skip list to compare the URL -func (c Comparator) Compare(comp cm.Comparator) int { - a := common.URL(c).String() - b := common.URL(comp.(Comparator)).String() - switch { - case a > b: - return 1 - case a < b: - return -1 - default: - return 0 - } -} - // addURL will add URL in memory func (mts *MetadataService) addURL(targetMap *sync.Map, url *common.URL) bool { var ( @@ -101,7 +83,7 @@ func (mts *MetadataService) addURL(targetMap *sync.Map, url *common.URL) bool { logger.Debug(url.ServiceKey()) if urlSet, loaded = targetMap.LoadOrStore(url.ServiceKey(), skip.New(uint64(0))); loaded { mts.lock.RLock() - wantedUrl := urlSet.(*skip.SkipList).Get(Comparator(*url)) + wantedUrl := urlSet.(*skip.SkipList).Get(url) if len(wantedUrl) > 0 && wantedUrl[0] != nil { mts.lock.RUnlock() return false @@ -110,12 +92,12 @@ func (mts *MetadataService) addURL(targetMap *sync.Map, url *common.URL) bool { } mts.lock.Lock() // double chk - wantedUrl := urlSet.(*skip.SkipList).Get(Comparator(*url)) + wantedUrl := urlSet.(*skip.SkipList).Get(url) if len(wantedUrl) > 0 && wantedUrl[0] != nil { mts.lock.Unlock() return false } - urlSet.(*skip.SkipList).Insert(Comparator(*url)) + urlSet.(*skip.SkipList).Insert(url) mts.lock.Unlock() return true } @@ -124,7 +106,7 @@ func (mts *MetadataService) addURL(targetMap *sync.Map, url *common.URL) bool { func (mts *MetadataService) removeURL(targetMap *sync.Map, url *common.URL) { if value, loaded := targetMap.Load(url.ServiceKey()); loaded { mts.lock.Lock() - value.(*skip.SkipList).Delete(Comparator(*url)) + value.(*skip.SkipList).Delete(url) mts.lock.Unlock() mts.lock.RLock() defer mts.lock.RUnlock() @@ -135,13 +117,13 @@ func (mts *MetadataService) removeURL(targetMap *sync.Map, url *common.URL) { } // getAllService can return all the exportedUrlString except for metadataService -func (mts *MetadataService) getAllService(services *sync.Map) []common.URL { +func (mts *MetadataService) getAllService(services *sync.Map) []*common.URL { // using skip list to dedup and sorting - res := make([]common.URL, 0) + var res []*common.URL services.Range(func(key, value interface{}) bool { urls := value.(*skip.SkipList) for i := uint64(0); i < urls.Len(); i++ { - url := common.URL(urls.ByPosition(i).(Comparator)) + url := urls.ByPosition(i).(*common.URL) if url.GetParam(constant.INTERFACE_KEY, url.Path) != constant.METADATA_SERVICE_NAME { res = append(res, url) } @@ -153,13 +135,13 @@ func (mts *MetadataService) getAllService(services *sync.Map) []common.URL { } // getSpecifiedService can return specified service url by serviceKey -func (mts *MetadataService) getSpecifiedService(services *sync.Map, serviceKey string, protocol string) []common.URL { - res := make([]common.URL, 0) +func (mts *MetadataService) getSpecifiedService(services *sync.Map, serviceKey string, protocol string) []*common.URL { + var res []*common.URL serviceList, loaded := services.Load(serviceKey) if loaded { urls := serviceList.(*skip.SkipList) for i := uint64(0); i < urls.Len(); i++ { - url := common.URL(urls.ByPosition(i).(Comparator)) + url := urls.ByPosition(i).(*common.URL) if len(protocol) == 0 || protocol == constant.ANY_VALUE || url.Protocol == protocol || url.GetParam(constant.PROTOCOL_KEY, "") == protocol { res = append(res, url) } @@ -170,34 +152,34 @@ func (mts *MetadataService) getSpecifiedService(services *sync.Map, serviceKey s } // ExportURL can store the in memory -func (mts *MetadataService) ExportURL(url common.URL) (bool, error) { - return mts.addURL(mts.exportedServiceURLs, &url), nil +func (mts *MetadataService) ExportURL(url *common.URL) (bool, error) { + return mts.addURL(mts.exportedServiceURLs, url), nil } // UnexportURL can remove the url store in memory -func (mts *MetadataService) UnexportURL(url common.URL) error { - mts.removeURL(mts.exportedServiceURLs, &url) +func (mts *MetadataService) UnexportURL(url *common.URL) error { + mts.removeURL(mts.exportedServiceURLs, url) return nil } // SubscribeURL can store the in memory -func (mts *MetadataService) SubscribeURL(url common.URL) (bool, error) { - return mts.addURL(mts.subscribedServiceURLs, &url), nil +func (mts *MetadataService) SubscribeURL(url *common.URL) (bool, error) { + return mts.addURL(mts.subscribedServiceURLs, url), nil } // UnsubscribeURL can remove the url store in memory -func (mts *MetadataService) UnsubscribeURL(url common.URL) error { - mts.removeURL(mts.subscribedServiceURLs, &url) +func (mts *MetadataService) UnsubscribeURL(url *common.URL) error { + mts.removeURL(mts.subscribedServiceURLs, url) return nil } // PublishServiceDefinition: publish url's service metadata info, and write into memory -func (mts *MetadataService) PublishServiceDefinition(url common.URL) error { +func (mts *MetadataService) PublishServiceDefinition(url *common.URL) error { interfaceName := url.GetParam(constant.INTERFACE_KEY, "") isGeneric := url.GetParamBool(constant.GENERIC_KEY, false) if len(interfaceName) > 0 && !isGeneric { - service := common.ServiceMap.GetService(url.Protocol, url.GetParam(constant.BEAN_NAME_KEY, url.Service())) - sd := definition.BuildServiceDefinition(*service, url) + tmpService := common.ServiceMap.GetService(url.Protocol, url.GetParam(constant.BEAN_NAME_KEY, url.Service())) + sd := definition.BuildServiceDefinition(*tmpService, url) data, err := sd.ToBytes() if err != nil { logger.Errorf("publishProvider getServiceDescriptor error. providerUrl:%v , error:%v ", url, err) @@ -221,7 +203,7 @@ func (mts *MetadataService) GetExportedURLs(serviceInterface string, group strin } // GetSubscribedURLs get all subscribedUrl -func (mts *MetadataService) GetSubscribedURLs() ([]common.URL, error) { +func (mts *MetadataService) GetSubscribedURLs() ([]*common.URL, error) { return mts.getAllService(mts.subscribedServiceURLs), nil } @@ -239,7 +221,7 @@ func (mts *MetadataService) GetServiceDefinitionByServiceKey(serviceKey string) } // RefreshMetadata will always return true because it will be implement by remote service -func (mts *MetadataService) RefreshMetadata(exportedRevision string, subscribedRevision string) (bool, error) { +func (mts *MetadataService) RefreshMetadata(string, string) (bool, error) { return true, nil } diff --git a/metadata/service/inmemory/service_proxy.go b/metadata/service/inmemory/service_proxy.go index e2b29686f49aeade5c61a46f464e6bf00165e70c..7e14293a6766492c1c1b02eef9429d1adeb539ae 100644 --- a/metadata/service/inmemory/service_proxy.go +++ b/metadata/service/inmemory/service_proxy.go @@ -88,34 +88,34 @@ func (m *MetadataServiceProxy) ServiceName() (string, error) { return "", nil } -func (m *MetadataServiceProxy) ExportURL(url common.URL) (bool, error) { +func (m *MetadataServiceProxy) ExportURL(url *common.URL) (bool, error) { logger.Error("you should never invoke this implementation") return false, nil } -func (m *MetadataServiceProxy) UnexportURL(url common.URL) error { +func (m *MetadataServiceProxy) UnexportURL(url *common.URL) error { logger.Error("you should never invoke this implementation") return nil } -func (m *MetadataServiceProxy) SubscribeURL(url common.URL) (bool, error) { +func (m *MetadataServiceProxy) SubscribeURL(url *common.URL) (bool, error) { logger.Error("you should never invoke this implementation") return false, nil } -func (m *MetadataServiceProxy) UnsubscribeURL(url common.URL) error { +func (m *MetadataServiceProxy) UnsubscribeURL(url *common.URL) error { logger.Error("you should never invoke this implementation") return nil } -func (m *MetadataServiceProxy) PublishServiceDefinition(url common.URL) error { +func (m *MetadataServiceProxy) PublishServiceDefinition(url *common.URL) error { logger.Error("you should never invoke this implementation") return nil } -func (m *MetadataServiceProxy) GetSubscribedURLs() ([]common.URL, error) { +func (m *MetadataServiceProxy) GetSubscribedURLs() ([]*common.URL, error) { logger.Error("you should never invoke this implementation") - return []common.URL{}, nil + return nil, nil } func (m *MetadataServiceProxy) GetServiceDefinition(interfaceName string, group string, version string) (string, error) { diff --git a/metadata/service/inmemory/service_proxy_test.go b/metadata/service/inmemory/service_proxy_test.go index 0d75517e418133ffbf3804ec96f061dda09b9e5e..f7fc8fd88e5f31804253dc996cb99b241a519d14 100644 --- a/metadata/service/inmemory/service_proxy_test.go +++ b/metadata/service/inmemory/service_proxy_test.go @@ -49,16 +49,16 @@ func TestMetadataServiceProxy_GetExportedURLs(t *testing.T) { func TestNewMetadataService(t *testing.T) { pxy := createPxy() pxy.ServiceName() - pxy.PublishServiceDefinition(common.URL{}) + pxy.PublishServiceDefinition(&common.URL{}) pxy.GetServiceDefinition(constant.ANY_VALUE, constant.ANY_VALUE, constant.ANY_VALUE) pxy.Version() pxy.GetSubscribedURLs() - pxy.UnsubscribeURL(common.URL{}) + pxy.UnsubscribeURL(&common.URL{}) pxy.GetServiceDefinitionByServiceKey("any") - pxy.ExportURL(common.URL{}) - pxy.SubscribeURL(common.URL{}) + pxy.ExportURL(&common.URL{}) + pxy.SubscribeURL(&common.URL{}) pxy.MethodMapper() - pxy.UnexportURL(common.URL{}) + pxy.UnexportURL(&common.URL{}) pxy.RefreshMetadata(constant.ANY_VALUE, constant.ANY_VALUE) } diff --git a/metadata/service/remote/service.go b/metadata/service/remote/service.go index ae83a69bef0af1614352c99c1e512a63770a0eff..d1b17e8cd6fdddec82bd9864b231731763c1cfd1 100644 --- a/metadata/service/remote/service.go +++ b/metadata/service/remote/service.go @@ -89,29 +89,29 @@ func (mts *MetadataService) setInMemoryMetadataService(metadata *inmemory.Metada } // ExportURL will be implemented by in memory service -func (mts *MetadataService) ExportURL(url common.URL) (bool, error) { +func (mts *MetadataService) ExportURL(url *common.URL) (bool, error) { return mts.inMemoryMetadataService.ExportURL(url) } // UnexportURL remove @url's metadata -func (mts *MetadataService) UnexportURL(url common.URL) error { +func (mts *MetadataService) UnexportURL(url *common.URL) error { smi := identifier.NewServiceMetadataIdentifier(url) smi.Revision = mts.exportedRevision.Load() return mts.delegateReport.RemoveServiceMetadata(smi) } // SubscribeURL will be implemented by in memory service -func (mts *MetadataService) SubscribeURL(url common.URL) (bool, error) { +func (mts *MetadataService) SubscribeURL(url *common.URL) (bool, error) { return mts.inMemoryMetadataService.SubscribeURL(url) } // UnsubscribeURL will be implemented by in memory service -func (mts *MetadataService) UnsubscribeURL(url common.URL) error { +func (mts *MetadataService) UnsubscribeURL(url *common.URL) error { return mts.UnsubscribeURL(url) } // PublishServiceDefinition will call remote metadata's StoreProviderMetadata to store url info and service definition -func (mts *MetadataService) PublishServiceDefinition(url common.URL) error { +func (mts *MetadataService) PublishServiceDefinition(url *common.URL) error { interfaceName := url.GetParam(constant.INTERFACE_KEY, "") isGeneric := url.GetParamBool(constant.GENERIC_KEY, false) if len(interfaceName) > 0 && !isGeneric { @@ -139,7 +139,7 @@ func (mts *MetadataService) GetExportedURLs(serviceInterface string, group strin } // GetSubscribedURLs will be implemented by in memory service -func (mts *MetadataService) GetSubscribedURLs() ([]common.URL, error) { +func (mts *MetadataService) GetSubscribedURLs() ([]*common.URL, error) { return mts.inMemoryMetadataService.GetSubscribedURLs() } diff --git a/metadata/service/remote/service_proxy.go b/metadata/service/remote/service_proxy.go index eaf7a02f4a0f3a8280835940bd8da720a0bde9f5..3199aa6dfff6f5e8b6036c44f452d16480b0380c 100644 --- a/metadata/service/remote/service_proxy.go +++ b/metadata/service/remote/service_proxy.go @@ -45,27 +45,27 @@ func (m *metadataServiceProxy) ServiceName() (string, error) { return m.serviceName, nil } -func (m *metadataServiceProxy) ExportURL(url common.URL) (bool, error) { +func (m *metadataServiceProxy) ExportURL(url *common.URL) (bool, error) { logger.Error("you should never invoke this implementation") return true, nil } -func (m *metadataServiceProxy) UnexportURL(url common.URL) error { +func (m *metadataServiceProxy) UnexportURL(url *common.URL) error { logger.Error("you should never invoke this implementation") return nil } -func (m *metadataServiceProxy) SubscribeURL(url common.URL) (bool, error) { +func (m *metadataServiceProxy) SubscribeURL(url *common.URL) (bool, error) { logger.Error("you should never invoke this implementation") return true, nil } -func (m *metadataServiceProxy) UnsubscribeURL(url common.URL) error { +func (m *metadataServiceProxy) UnsubscribeURL(url *common.URL) error { logger.Error("you should never invoke this implementation") return nil } -func (m *metadataServiceProxy) PublishServiceDefinition(url common.URL) error { +func (m *metadataServiceProxy) PublishServiceDefinition(url *common.URL) error { logger.Error("you should never invoke this implementation") return nil } @@ -85,7 +85,7 @@ func (m *metadataServiceProxy) GetExportedURLs(serviceInterface string, group st if err != nil { return []interface{}{}, nil } - res := make([]common.URL, 0, len(urls)) + var res []*common.URL for _, s := range urls { u, err := common.NewURL(s) if err != nil { @@ -101,9 +101,9 @@ func (m *metadataServiceProxy) MethodMapper() map[string]string { return map[string]string{} } -func (m *metadataServiceProxy) GetSubscribedURLs() ([]common.URL, error) { +func (m *metadataServiceProxy) GetSubscribedURLs() ([]*common.URL, error) { logger.Error("you should never invoke this implementation") - return []common.URL{}, nil + return nil, nil } func (m *metadataServiceProxy) GetServiceDefinition(interfaceName string, group string, version string) (string, error) { diff --git a/metadata/service/remote/service_proxy_test.go b/metadata/service/remote/service_proxy_test.go index c284bb22123e731f3b8905f70508856bc767ace6..8bccbb8bbb70d1533fa3dad78bab59e82ff2e5b3 100644 --- a/metadata/service/remote/service_proxy_test.go +++ b/metadata/service/remote/service_proxy_test.go @@ -55,15 +55,15 @@ func TestMetadataServiceProxy_GetServiceDefinition(t *testing.T) { func TestMetadataServiceProxy(t *testing.T) { pxy := createProxy() pxy.ServiceName() - pxy.PublishServiceDefinition(common.URL{}) + pxy.PublishServiceDefinition(&common.URL{}) pxy.Version() pxy.GetSubscribedURLs() - pxy.UnsubscribeURL(common.URL{}) + pxy.UnsubscribeURL(&common.URL{}) pxy.GetServiceDefinitionByServiceKey("any") - pxy.ExportURL(common.URL{}) - pxy.SubscribeURL(common.URL{}) + pxy.ExportURL(&common.URL{}) + pxy.SubscribeURL(&common.URL{}) pxy.MethodMapper() - pxy.UnexportURL(common.URL{}) + pxy.UnexportURL(&common.URL{}) pxy.Reference() pxy.RefreshMetadata(constant.ANY_VALUE, constant.ANY_VALUE) } @@ -89,7 +89,7 @@ func prepareTest() { return &mockMetadataReportFactory{} }) u, _ := common.NewURL("mock://localhost") - instance.GetMetadataReportInstance(&u) + instance.GetMetadataReportInstance(u) } type mockMetadataReportFactory struct { @@ -110,7 +110,7 @@ func (m mockMetadataReport) StoreConsumerMetadata(*identifier.MetadataIdentifier panic("implement me") } -func (m mockMetadataReport) SaveServiceMetadata(*identifier.ServiceMetadataIdentifier, common.URL) error { +func (m mockMetadataReport) SaveServiceMetadata(*identifier.ServiceMetadataIdentifier, *common.URL) error { return nil } diff --git a/metadata/service/remote/service_test.go b/metadata/service/remote/service_test.go index 734f0989ab06ef17caeef241cd067c678fb8b2ad..1cbe5eec0fb97dee1880a9580afa7ea0bd72ca44 100644 --- a/metadata/service/remote/service_test.go +++ b/metadata/service/remote/service_test.go @@ -39,7 +39,7 @@ import ( ) var ( - serviceMetadata = make(map[*identifier.ServiceMetadataIdentifier]common.URL, 4) + serviceMetadata = make(map[*identifier.ServiceMetadataIdentifier]*common.URL, 4) subscribedMetadata = make(map[*identifier.SubscriberMetadataIdentifier]string, 4) ) @@ -65,7 +65,7 @@ func (metadataReport) StoreConsumerMetadata(*identifier.MetadataIdentifier, stri return nil } -func (mr *metadataReport) SaveServiceMetadata(id *identifier.ServiceMetadataIdentifier, url common.URL) error { +func (mr *metadataReport) SaveServiceMetadata(id *identifier.ServiceMetadataIdentifier, url *common.URL) error { logger.Infof("SaveServiceMetadata , url is %v", url) serviceMetadata[id] = url return nil @@ -97,7 +97,7 @@ func TestMetadataService(t *testing.T) { extension.SetMetadataReportFactory("mock", getMetadataReportFactory) u, err := common.NewURL(fmt.Sprintf("mock://127.0.0.1:20000/?sync.report=true")) assert.NoError(t, err) - instance.GetMetadataReportInstance(&u) + instance.GetMetadataReportInstance(u) mts, err := newMetadataService() assert.NoError(t, err) mts.(*MetadataService).setInMemoryMetadataService(mockInmemoryProc(t)) diff --git a/metadata/service/service.go b/metadata/service/service.go index f6509d0a72eb26e488dfb4fdeef5f4bbfd6b1bea..1d90f8a516831adcae20163a3620dd765459310d 100644 --- a/metadata/service/service.go +++ b/metadata/service/service.go @@ -34,15 +34,15 @@ type MetadataService interface { // ServiceName will get the service's name in meta service , which is application name ServiceName() (string, error) // ExportURL will store the exported url in metadata - ExportURL(url common.URL) (bool, error) + ExportURL(url *common.URL) (bool, error) // UnexportURL will delete the exported url in metadata - UnexportURL(url common.URL) error + UnexportURL(url *common.URL) error // SubscribeURL will store the subscribed url in metadata - SubscribeURL(url common.URL) (bool, error) + SubscribeURL(url *common.URL) (bool, error) // UnsubscribeURL will delete the subscribed url in metadata - UnsubscribeURL(url common.URL) error + UnsubscribeURL(url *common.URL) error // PublishServiceDefinition will generate the target url's code info - PublishServiceDefinition(url common.URL) error + PublishServiceDefinition(url *common.URL) error // GetExportedURLs will get the target exported url in metadata // the url should be unique // due to dubbo-go only support return array []interface{} in RPCService, so we should declare the return type as []interface{} @@ -53,7 +53,7 @@ type MetadataService interface { // GetExportedURLs will get the target subscribed url in metadata // the url should be unique - GetSubscribedURLs() ([]common.URL, error) + GetSubscribedURLs() ([]*common.URL, error) // GetServiceDefinition will get the target service info store in metadata GetServiceDefinition(interfaceName string, group string, version string) (string, error) // GetServiceDefinition will get the target service info store in metadata by service key @@ -122,7 +122,7 @@ func getExportedServicesRevision(serviceInstance registry.ServiceInstance) strin return metaData[constant.EXPORTED_SERVICES_REVISION_PROPERTY_NAME] } -func ConvertURLArrToIntfArr(urls []common.URL) []interface{} { +func ConvertURLArrToIntfArr(urls []*common.URL) []interface{} { if len(urls) == 0 { return []interface{}{} } diff --git a/metrics/prometheus/reporter.go b/metrics/prometheus/reporter.go index bd1e7986ca709a4e10dfcad04d2380931308d568..810a13d87ce938a3b8a9d085f6d5ae6e3dc4c6ad 100644 --- a/metrics/prometheus/reporter.go +++ b/metrics/prometheus/reporter.go @@ -130,13 +130,13 @@ func newHistogramVec(side string) *prometheus.HistogramVec { } // whether this url represents the application received the request as server -func isProvider(url common.URL) bool { +func isProvider(url *common.URL) bool { role := url.GetParam(constant.ROLE_KEY, "") return strings.EqualFold(role, strconv.Itoa(common.PROVIDER)) } // whether this url represents the application sent then request as client -func isConsumer(url common.URL) bool { +func isConsumer(url *common.URL) bool { role := url.GetParam(constant.ROLE_KEY, "") return strings.EqualFold(role, strconv.Itoa(common.CONSUMER)) } diff --git a/protocol/dubbo/dubbo_invoker.go b/protocol/dubbo/dubbo_invoker.go index e72ca28299727d9865664036016671670f5935a0..acddfd6cd51733794fcf2e93f096d898de7ec1cd 100644 --- a/protocol/dubbo/dubbo_invoker.go +++ b/protocol/dubbo/dubbo_invoker.go @@ -66,7 +66,7 @@ type DubboInvoker struct { } // NewDubboInvoker constructor -func NewDubboInvoker(url common.URL, client *remoting.ExchangeClient) *DubboInvoker { +func NewDubboInvoker(url *common.URL, client *remoting.ExchangeClient) *DubboInvoker { requestTimeout := config.GetConsumerConfig().RequestTimeout requestTimeoutStr := url.GetParam(constant.TIMEOUT_KEY, config.GetConsumerConfig().Request_Timeout) diff --git a/protocol/dubbo/dubbo_invoker_test.go b/protocol/dubbo/dubbo_invoker_test.go index c80f412ff0337c56cc146ff710e491579c425b95..49d853ee2dba51600692724afae830ae3c2f00a0 100644 --- a/protocol/dubbo/dubbo_invoker_test.go +++ b/protocol/dubbo/dubbo_invoker_test.go @@ -93,7 +93,7 @@ func TestDubboInvokerInvoke(t *testing.T) { proto.Destroy() } -func InitTest(t *testing.T) (protocol.Protocol, common.URL) { +func InitTest(t *testing.T) (protocol.Protocol, *common.URL) { hessian.RegisterPOJO(&User{}) diff --git a/protocol/dubbo/dubbo_protocol.go b/protocol/dubbo/dubbo_protocol.go index 8dda52b6b9b79e5d20a730db52f9a376422ccd63..4f03b8aba061ea9b37b35d89142eb7bec80f3a97 100644 --- a/protocol/dubbo/dubbo_protocol.go +++ b/protocol/dubbo/dubbo_protocol.go @@ -90,7 +90,7 @@ func (dp *DubboProtocol) Export(invoker protocol.Invoker) protocol.Exporter { } // Refer create dubbo service reference. -func (dp *DubboProtocol) Refer(url common.URL) protocol.Invoker { +func (dp *DubboProtocol) Refer(url *common.URL) protocol.Invoker { exchangeClient := getExchangeClient(url) if exchangeClient == nil { logger.Warnf("can't dial the server: %+v", url.Location) @@ -115,7 +115,7 @@ func (dp *DubboProtocol) Destroy() { } } -func (dp *DubboProtocol) openServer(url common.URL) { +func (dp *DubboProtocol) openServer(url *common.URL) { _, ok := dp.serverMap[url.Location] if !ok { _, ok := dp.ExporterMap().Load(url.ServiceKey()) @@ -176,7 +176,7 @@ func doHandleRequest(rpcInvocation *invocation.RPCInvocation) protocol.RPCResult return result } -func getExchangeClient(url common.URL) *remoting.ExchangeClient { +func getExchangeClient(url *common.URL) *remoting.ExchangeClient { clientTmp, ok := exchangeClientMap.Load(url.Location) if !ok { var exchangeClientTmp *remoting.ExchangeClient diff --git a/protocol/dubbo/hessian2/hessian_dubbo_test.go b/protocol/dubbo/hessian2/hessian_dubbo_test.go index c3f19f04536484816e4b4f709f534dcbf4adb2b4..13dab92ba874fb5d746c5d57134592865cbfc7bd 100644 --- a/protocol/dubbo/hessian2/hessian_dubbo_test.go +++ b/protocol/dubbo/hessian2/hessian_dubbo_test.go @@ -223,7 +223,7 @@ func TestHessianCodec_ReadAttachments(t *testing.T) { type AttachTestObject struct { Id int32 - Name string `dubbo:name` + Name string `dubbo:"name"` } func (AttachTestObject) JavaClassName() string { diff --git a/protocol/grpc/client.go b/protocol/grpc/client.go index 9b31a8c626ab0cdec8404da6712d88376be28f2f..33f0a088dcd6800ce7376faa3d5e05ab5d62596d 100644 --- a/protocol/grpc/client.go +++ b/protocol/grpc/client.go @@ -90,7 +90,7 @@ type Client struct { } // NewClient creates a new gRPC client. -func NewClient(url common.URL) *Client { +func NewClient(url *common.URL) *Client { // if global trace instance was set , it means trace function enabled. If not , will return Nooptracer tracer := opentracing.GlobalTracer() dailOpts := make([]grpc.DialOption, 0, 4) @@ -117,7 +117,7 @@ func NewClient(url common.URL) *Client { } func getInvoker(impl interface{}, conn *grpc.ClientConn) interface{} { - in := []reflect.Value{} + var in []reflect.Value in = append(in, reflect.ValueOf(conn)) method := reflect.ValueOf(impl).MethodByName("GetDubboStub") res := method.Call(in) diff --git a/protocol/grpc/grpc_invoker.go b/protocol/grpc/grpc_invoker.go index 737e8c40a063b07e56d7c90f7de04670461ce103..02e7716115e6bb22f3de5a8c4d8a2131995e81c6 100644 --- a/protocol/grpc/grpc_invoker.go +++ b/protocol/grpc/grpc_invoker.go @@ -45,7 +45,7 @@ type GrpcInvoker struct { } // NewGrpcInvoker returns a Grpc invoker instance -func NewGrpcInvoker(url common.URL, client *Client) *GrpcInvoker { +func NewGrpcInvoker(url *common.URL, client *Client) *GrpcInvoker { return &GrpcInvoker{ BaseInvoker: *protocol.NewBaseInvoker(url), client: client, @@ -62,7 +62,7 @@ func (gi *GrpcInvoker) Invoke(ctx context.Context, invocation protocol.Invocatio result.Err = errNoReply } - in := []reflect.Value{} + var in []reflect.Value in = append(in, reflect.ValueOf(context.Background())) in = append(in, invocation.ParameterValues()...) diff --git a/protocol/grpc/grpc_protocol.go b/protocol/grpc/grpc_protocol.go index 396ff473f24f525c41bf117af9c12df3fbad1ebe..3ad124532f389d6df5ef746eaca26158b8c42790 100644 --- a/protocol/grpc/grpc_protocol.go +++ b/protocol/grpc/grpc_protocol.go @@ -67,7 +67,7 @@ func (gp *GrpcProtocol) Export(invoker protocol.Invoker) protocol.Exporter { return exporter } -func (gp *GrpcProtocol) openServer(url common.URL) { +func (gp *GrpcProtocol) openServer(url *common.URL) { _, ok := gp.serverMap[url.Location] if !ok { _, ok := gp.ExporterMap().Load(url.ServiceKey()) @@ -89,7 +89,7 @@ func (gp *GrpcProtocol) openServer(url common.URL) { } // Refer a remote gRPC service -func (gp *GrpcProtocol) Refer(url common.URL) protocol.Invoker { +func (gp *GrpcProtocol) Refer(url *common.URL) protocol.Invoker { invoker := NewGrpcInvoker(url, NewClient(url)) gp.SetInvokers(invoker) logger.Infof("Refer service: %s", url.String()) diff --git a/protocol/grpc/server.go b/protocol/grpc/server.go index 30bdf77e77e478763a5cc6b1e81f021dd3573bc4..e77e2babd0aba81cdcfe2288eeff69195decf9f4 100644 --- a/protocol/grpc/server.go +++ b/protocol/grpc/server.go @@ -63,7 +63,7 @@ func (s *Server) SetBufferSize(n int) { } // Start gRPC server with @url -func (s *Server) Start(url common.URL) { +func (s *Server) Start(url *common.URL) { var ( addr string err error diff --git a/protocol/invoker.go b/protocol/invoker.go index 91814e27e634a8be0a58bc6811bb68dd9861fd8d..5657b6b5b2c6d13e001bec2ba3ca7b4f02fc7e60 100644 --- a/protocol/invoker.go +++ b/protocol/invoker.go @@ -41,13 +41,13 @@ type Invoker interface { // BaseInvoker provides default invoker implement type BaseInvoker struct { - url common.URL + url *common.URL available bool destroyed bool } // NewBaseInvoker creates a new BaseInvoker -func NewBaseInvoker(url common.URL) *BaseInvoker { +func NewBaseInvoker(url *common.URL) *BaseInvoker { return &BaseInvoker{ url: url, available: true, @@ -56,7 +56,7 @@ func NewBaseInvoker(url common.URL) *BaseInvoker { } // GetUrl gets base invoker URL -func (bi *BaseInvoker) GetUrl() common.URL { +func (bi *BaseInvoker) GetUrl() *common.URL { return bi.url } diff --git a/protocol/jsonrpc/http.go b/protocol/jsonrpc/http.go index 2a2ddfeeeb52b865e96ccff69d2b39d8a671ed41..869617ea4eb512df6287d21e9d811145c1944e57 100644 --- a/protocol/jsonrpc/http.go +++ b/protocol/jsonrpc/http.go @@ -101,7 +101,7 @@ func NewHTTPClient(opt *HTTPOptions) *HTTPClient { } // NewRequest creates a new HTTP request with @service ,@method and @arguments. -func (c *HTTPClient) NewRequest(service common.URL, method string, args interface{}) *Request { +func (c *HTTPClient) NewRequest(service *common.URL, method string, args interface{}) *Request { return &Request{ ID: atomic.AddInt64(&c.ID, 1), @@ -115,7 +115,7 @@ func (c *HTTPClient) NewRequest(service common.URL, method string, args interfac } // Call makes a HTTP call with @ctx , @service ,@req and @rsp -func (c *HTTPClient) Call(ctx context.Context, service common.URL, req *Request, rsp interface{}) error { +func (c *HTTPClient) Call(ctx context.Context, service *common.URL, req *Request, rsp interface{}) error { // header httpHeader := http.Header{} httpHeader.Set("Content-Type", "application/json") diff --git a/protocol/jsonrpc/jsonrpc_invoker.go b/protocol/jsonrpc/jsonrpc_invoker.go index d84b980216ade6e569e68af31fc90e1ea16b3056..f10aaad824cea9c953cf994bd7349b57f6bfffa8 100644 --- a/protocol/jsonrpc/jsonrpc_invoker.go +++ b/protocol/jsonrpc/jsonrpc_invoker.go @@ -36,7 +36,7 @@ type JsonrpcInvoker struct { } // NewJsonrpcInvoker creates JSON RPC invoker with @url and @client -func NewJsonrpcInvoker(url common.URL, client *HTTPClient) *JsonrpcInvoker { +func NewJsonrpcInvoker(url *common.URL, client *HTTPClient) *JsonrpcInvoker { return &JsonrpcInvoker{ BaseInvoker: *protocol.NewBaseInvoker(url), client: client, diff --git a/protocol/jsonrpc/jsonrpc_protocol.go b/protocol/jsonrpc/jsonrpc_protocol.go index 1778d99d4078058dc43a630b89b9d256350da0f3..643bcde8cb41a3cb94e97b2d21df26894c574b28 100644 --- a/protocol/jsonrpc/jsonrpc_protocol.go +++ b/protocol/jsonrpc/jsonrpc_protocol.go @@ -75,7 +75,7 @@ func (jp *JsonrpcProtocol) Export(invoker protocol.Invoker) protocol.Exporter { } // Refer a remote JSON PRC service from registry -func (jp *JsonrpcProtocol) Refer(url common.URL) protocol.Invoker { +func (jp *JsonrpcProtocol) Refer(url *common.URL) protocol.Invoker { //default requestTimeout var requestTimeout = config.GetConsumerConfig().RequestTimeout @@ -106,7 +106,7 @@ func (jp *JsonrpcProtocol) Destroy() { } } -func (jp *JsonrpcProtocol) openServer(url common.URL) { +func (jp *JsonrpcProtocol) openServer(url *common.URL) { _, ok := jp.serverMap[url.Location] if !ok { _, loadOk := jp.ExporterMap().Load(strings.TrimPrefix(url.Path, "/")) diff --git a/protocol/jsonrpc/server.go b/protocol/jsonrpc/server.go index 9755a481fdba325887a1d16731cbbcb8e3943d8a..755aa7da79384842d5a3f3c4364fc991d84b47df 100644 --- a/protocol/jsonrpc/server.go +++ b/protocol/jsonrpc/server.go @@ -229,7 +229,7 @@ func accept(listener net.Listener, fn func(net.Conn)) error { } // Start JSON RPC server then ready for accept request. -func (s *Server) Start(url common.URL) { +func (s *Server) Start(url *common.URL) { listener, err := net.Listen("tcp", url.Location) if err != nil { logger.Errorf("jsonrpc server [%s] start failed: %v", url.Path, err) diff --git a/protocol/mock/mock_invoker.go b/protocol/mock/mock_invoker.go index 0c88b47e36122dc1a9bc9345d7e93f62cd76f13b..8a0973bd128a74677e8549793b6792e67b26b443 100644 --- a/protocol/mock/mock_invoker.go +++ b/protocol/mock/mock_invoker.go @@ -59,9 +59,9 @@ func (m *MockInvoker) EXPECT() *MockInvokerMockRecorder { } // GetUrl mocks base method -func (m *MockInvoker) GetUrl() common.URL { +func (m *MockInvoker) GetUrl() *common.URL { ret := m.ctrl.Call(m, "GetUrl") - ret0, _ := ret[0].(common.URL) + ret0, _ := ret[0].(*common.URL) return ret0 } diff --git a/protocol/protocol.go b/protocol/protocol.go index 6bed5ec4c2be82edda7a642eb342381c53387460..d03e70f1ea4acbd1277d4b968be9109fdde187a9 100644 --- a/protocol/protocol.go +++ b/protocol/protocol.go @@ -32,7 +32,7 @@ type Protocol interface { // Export service for remote invocation Export(invoker Invoker) Exporter // Refer a remote service - Refer(url common.URL) Invoker + Refer(url *common.URL) Invoker // Destroy will destroy all invoker and exporter, so it only is called once. Destroy() } @@ -89,7 +89,7 @@ func (bp *BaseProtocol) Export(invoker Invoker) Exporter { } // Refer is default refer implement. -func (bp *BaseProtocol) Refer(url common.URL) Invoker { +func (bp *BaseProtocol) Refer(url *common.URL) Invoker { return NewBaseInvoker(url) } diff --git a/protocol/protocolwrapper/mock_protocol_filter.go b/protocol/protocolwrapper/mock_protocol_filter.go index 2e9ffed06f03d196c91f6679df21538612bac405..18a4e1562107939e9c72090778422e0d8bb56a60 100644 --- a/protocol/protocolwrapper/mock_protocol_filter.go +++ b/protocol/protocolwrapper/mock_protocol_filter.go @@ -39,7 +39,7 @@ func (pfw *mockProtocolFilter) Export(invoker protocol.Invoker) protocol.Exporte } // Refer a mock remote service -func (pfw *mockProtocolFilter) Refer(url common.URL) protocol.Invoker { +func (pfw *mockProtocolFilter) Refer(url *common.URL) protocol.Invoker { return protocol.NewBaseInvoker(url) } diff --git a/protocol/protocolwrapper/protocol_filter_wrapper.go b/protocol/protocolwrapper/protocol_filter_wrapper.go index 4b2702b99f9793d4e567de65bd9555fb20381b1d..79d2cf7f55ee81db39ea28448fc66a8a7494d8d1 100644 --- a/protocol/protocolwrapper/protocol_filter_wrapper.go +++ b/protocol/protocolwrapper/protocol_filter_wrapper.go @@ -55,7 +55,7 @@ func (pfw *ProtocolFilterWrapper) Export(invoker protocol.Invoker) protocol.Expo } // Refer a remote service -func (pfw *ProtocolFilterWrapper) Refer(url common.URL) protocol.Invoker { +func (pfw *ProtocolFilterWrapper) Refer(url *common.URL) protocol.Invoker { if pfw.protocol == nil { pfw.protocol = extension.GetProtocol(url.Protocol) } @@ -101,7 +101,7 @@ type FilterInvoker struct { } // GetUrl is used to get url from FilterInvoker -func (fi *FilterInvoker) GetUrl() common.URL { +func (fi *FilterInvoker) GetUrl() *common.URL { return fi.invoker.GetUrl() } diff --git a/protocol/protocolwrapper/protocol_filter_wrapper_test.go b/protocol/protocolwrapper/protocol_filter_wrapper_test.go index b03ea7b9b66d926aff8851f88e1bd7434b254903..8f063f85521bbdcd3fa3891e7d09754fc9b58ac7 100644 --- a/protocol/protocolwrapper/protocol_filter_wrapper_test.go +++ b/protocol/protocolwrapper/protocol_filter_wrapper_test.go @@ -43,7 +43,7 @@ func TestProtocolFilterWrapperExport(t *testing.T) { u := common.NewURLWithOptions( common.WithParams(url.Values{}), common.WithParamsValue(constant.SERVICE_FILTER_KEY, "echo")) - exporter := filtProto.Export(protocol.NewBaseInvoker(*u)) + exporter := filtProto.Export(protocol.NewBaseInvoker(u)) _, ok := exporter.GetInvoker().(*FilterInvoker) assert.True(t, ok) } @@ -55,7 +55,7 @@ func TestProtocolFilterWrapperRefer(t *testing.T) { u := common.NewURLWithOptions( common.WithParams(url.Values{}), common.WithParamsValue(constant.REFERENCE_FILTER_KEY, "echo")) - invoker := filtProto.Refer(*u) + invoker := filtProto.Refer(u) _, ok := invoker.(*FilterInvoker) assert.True(t, ok) } diff --git a/protocol/rest/rest_invoker.go b/protocol/rest/rest_invoker.go index 691beeda4085f316075fe55b9328bc86d6328187..898890e41732d3c874c47cf3b88bba2e201d01d0 100644 --- a/protocol/rest/rest_invoker.go +++ b/protocol/rest/rest_invoker.go @@ -43,7 +43,7 @@ type RestInvoker struct { } // NewRestInvoker returns a RestInvoker -func NewRestInvoker(url common.URL, client *client.RestClient, restMethodConfig map[string]*config.RestMethodConfig) *RestInvoker { +func NewRestInvoker(url *common.URL, client *client.RestClient, restMethodConfig map[string]*config.RestMethodConfig) *RestInvoker { return &RestInvoker{ BaseInvoker: *protocol.NewBaseInvoker(url), client: *client, diff --git a/protocol/rest/rest_protocol.go b/protocol/rest/rest_protocol.go index 0cd26c240a7eb1b83a04ca2f57c332bbda994967..05e119b0540b5f887d53d006e41d3083d1c46de4 100644 --- a/protocol/rest/rest_protocol.go +++ b/protocol/rest/rest_protocol.go @@ -86,7 +86,7 @@ func (rp *RestProtocol) Export(invoker protocol.Invoker) protocol.Exporter { } // Refer create rest service reference -func (rp *RestProtocol) Refer(url common.URL) protocol.Invoker { +func (rp *RestProtocol) Refer(url *common.URL) protocol.Invoker { // create rest_invoker var requestTimeout = config.GetConsumerConfig().RequestTimeout requestTimeoutStr := url.GetParam(constant.TIMEOUT_KEY, config.GetConsumerConfig().Request_Timeout) @@ -107,7 +107,7 @@ func (rp *RestProtocol) Refer(url common.URL) protocol.Invoker { } // nolint -func (rp *RestProtocol) getServer(url common.URL, serverType string) server.RestServer { +func (rp *RestProtocol) getServer(url *common.URL, serverType string) server.RestServer { restServer, ok := rp.serverMap[url.Location] if ok { return restServer @@ -149,8 +149,8 @@ func (rp *RestProtocol) getClient(restOptions client.RestOptions, clientType str func (rp *RestProtocol) Destroy() { // destroy rest_server rp.BaseProtocol.Destroy() - for key, server := range rp.serverMap { - server.Destroy() + for key, tmpServer := range rp.serverMap { + tmpServer.Destroy() delete(rp.serverMap, key) } for key := range rp.clientMap { diff --git a/protocol/rest/server/rest_server.go b/protocol/rest/server/rest_server.go index d9542bb8760cd2ddb7b839ebc6761dab75ae9c30..5ef04ff336cadccddbcc952b272c2ba91507f4fb 100644 --- a/protocol/rest/server/rest_server.go +++ b/protocol/rest/server/rest_server.go @@ -43,7 +43,7 @@ const parseParameterErrorStr = "An error occurred while parsing parameters on th // RestServer user can implement this server interface type RestServer interface { // Start rest server - Start(url common.URL) + Start(url *common.URL) // Deploy a http api Deploy(restMethodConfig *rest_config.RestMethodConfig, routeFunc func(request RestServerRequest, response RestServerResponse)) // UnDeploy a http api diff --git a/protocol/rest/server/server_impl/go_restful_server.go b/protocol/rest/server/server_impl/go_restful_server.go index 6fb9ee8daa7383580b9144ea25954f8ead974dcc..e4b2e266415f0de6ba248f4c6ea5ea33fe988c9a 100644 --- a/protocol/rest/server/server_impl/go_restful_server.go +++ b/protocol/rest/server/server_impl/go_restful_server.go @@ -59,7 +59,7 @@ func NewGoRestfulServer() server.RestServer { // Start go-restful server // It will add all go-restful filters -func (grs *GoRestfulServer) Start(url common.URL) { +func (grs *GoRestfulServer) Start(url *common.URL) { container := restful.NewContainer() for _, filter := range filterSlice { container.Filter(filter) diff --git a/protocol/rpc_status.go b/protocol/rpc_status.go index 978534ea8b98ddd76f68619155ff90fe5e031ac1..8d443e84f06b89ed708e080285aee3b054ea02e6 100644 --- a/protocol/rpc_status.go +++ b/protocol/rpc_status.go @@ -97,7 +97,7 @@ func (rpc *RPCStatus) GetSuccessiveRequestFailureCount() int32 { } // GetURLStatus get URL RPC status. -func GetURLStatus(url common.URL) *RPCStatus { +func GetURLStatus(url *common.URL) *RPCStatus { rpcStatus, found := serviceStatistic.Load(url.Key()) if !found { rpcStatus, _ = serviceStatistic.LoadOrStore(url.Key(), &RPCStatus{}) @@ -106,7 +106,7 @@ func GetURLStatus(url common.URL) *RPCStatus { } // GetMethodStatus get method RPC status. -func GetMethodStatus(url common.URL, methodName string) *RPCStatus { +func GetMethodStatus(url *common.URL, methodName string) *RPCStatus { identifier := url.Key() methodMap, found := methodStatistics.Load(identifier) if !found { @@ -124,13 +124,13 @@ func GetMethodStatus(url common.URL, methodName string) *RPCStatus { } // BeginCount gets begin count. -func BeginCount(url common.URL, methodName string) { +func BeginCount(url *common.URL, methodName string) { beginCount0(GetURLStatus(url)) beginCount0(GetMethodStatus(url, methodName)) } // EndCount gets end count. -func EndCount(url common.URL, methodName string, elapsed int64, succeeded bool) { +func EndCount(url *common.URL, methodName string, elapsed int64, succeeded bool) { endCount0(GetURLStatus(url), elapsed, succeeded) endCount0(GetMethodStatus(url, methodName), elapsed, succeeded) } diff --git a/protocol/rpc_status_test.go b/protocol/rpc_status_test.go index cc12753cf25007ab6d1010836b203aee22d78ca9..6fd449ce77fada15b32cba936691b51d3c8218ed 100644 --- a/protocol/rpc_status_test.go +++ b/protocol/rpc_status_test.go @@ -79,7 +79,7 @@ func TestGetUrlStatus(t *testing.T) { assert.Equal(t, int32(0), status.total) } -func TestbeginCount0(t *testing.T) { +func TestBeginCount0(t *testing.T) { defer CleanAllStatus() url, _ := common.NewURL(mockCommonDubboUrl) @@ -142,7 +142,7 @@ func TestAll(t *testing.T) { } -func request(url common.URL, method string, elapsed int64, active, succeeded bool) { +func request(url *common.URL, method string, elapsed int64, active, succeeded bool) { BeginCount(url, method) if !active { EndCount(url, method, elapsed, succeeded) diff --git a/registry/base_registry.go b/registry/base_registry.go index d6f5ceb91b1b46135d2da36418ac69fa71f53d48..a6693be3a862eb208afc216840910c323b8e826f 100644 --- a/registry/base_registry.go +++ b/registry/base_registry.go @@ -99,8 +99,8 @@ type BaseRegistry struct { birth int64 // time of file birth, seconds since Epoch; 0 if unknown wg sync.WaitGroup // wg+done for zk restart done chan struct{} - cltLock sync.RWMutex //ctl lock is a lock for services map - services map[string]common.URL // service name + protocol -> service config, for store the service registered + cltLock sync.RWMutex //ctl lock is a lock for services map + services map[string]*common.URL // service name + protocol -> service config, for store the service registered } // InitBaseRegistry for init some local variables and set BaseRegistry's subclass to it @@ -108,14 +108,14 @@ func (r *BaseRegistry) InitBaseRegistry(url *common.URL, facadeRegistry FacadeBa r.URL = url r.birth = time.Now().UnixNano() r.done = make(chan struct{}) - r.services = make(map[string]common.URL) + r.services = make(map[string]*common.URL) r.facadeBasedRegistry = facadeRegistry return r } // GetUrl for get registry's url -func (r *BaseRegistry) GetUrl() common.URL { - return *r.URL +func (r *BaseRegistry) GetUrl() *common.URL { + return r.URL } // Destroy for graceful down @@ -132,7 +132,7 @@ func (r *BaseRegistry) Destroy() { } // Register implement interface registry to register -func (r *BaseRegistry) Register(conf common.URL) error { +func (r *BaseRegistry) Register(conf *common.URL) error { var ( ok bool err error @@ -160,11 +160,11 @@ func (r *BaseRegistry) Register(conf common.URL) error { } // UnRegister implement interface registry to unregister -func (r *BaseRegistry) UnRegister(conf common.URL) error { +func (r *BaseRegistry) UnRegister(conf *common.URL) error { var ( ok bool err error - oldURL common.URL + oldURL *common.URL ) func() { @@ -197,7 +197,7 @@ func (r *BaseRegistry) UnRegister(conf common.URL) error { } // service is for getting service path stored in url -func (r *BaseRegistry) service(c common.URL) string { +func (r *BaseRegistry) service(c *common.URL) string { return url.QueryEscape(c.Service()) } @@ -205,7 +205,7 @@ func (r *BaseRegistry) service(c common.URL) string { func (r *BaseRegistry) RestartCallBack() bool { // copy r.services - services := make([]common.URL, 0, len(r.services)) + services := make([]*common.URL, 0, len(r.services)) for _, confIf := range r.services { services = append(services, confIf) } @@ -230,16 +230,16 @@ func (r *BaseRegistry) RestartCallBack() bool { } // register for register url to registry, include init params -func (r *BaseRegistry) register(c common.URL) error { +func (r *BaseRegistry) register(c *common.URL) error { return r.processURL(c, r.facadeBasedRegistry.DoRegister, r.createPath) } // unregister for unregister url to registry, include init params -func (r *BaseRegistry) unregister(c common.URL) error { +func (r *BaseRegistry) unregister(c *common.URL) error { return r.processURL(c, r.facadeBasedRegistry.DoUnregister, nil) } -func (r *BaseRegistry) processURL(c common.URL, f func(string, string) error, cpf createPathFunc) error { +func (r *BaseRegistry) processURL(c *common.URL, f func(string, string) error, cpf createPathFunc) error { if f == nil { panic(" Must provide a `function(string, string) error` to process URL. ") } @@ -291,7 +291,7 @@ func (r *BaseRegistry) createPath(dubboPath string) error { } // providerRegistry for provider role do -func (r *BaseRegistry) providerRegistry(c common.URL, params url.Values, f createPathFunc) (string, string, error) { +func (r *BaseRegistry) providerRegistry(c *common.URL, params url.Values, f createPathFunc) (string, string, error) { var ( dubboPath string rawURL string @@ -342,7 +342,7 @@ func (r *BaseRegistry) providerRegistry(c common.URL, params url.Values, f creat } // consumerRegistry for consumer role do -func (r *BaseRegistry) consumerRegistry(c common.URL, params url.Values, f createPathFunc) (string, string, error) { +func (r *BaseRegistry) consumerRegistry(c *common.URL, params url.Values, f createPathFunc) (string, string, error) { var ( dubboPath string rawURL string diff --git a/registry/consul/listener.go b/registry/consul/listener.go index b1598345032bddd7358c2263e5fd71b3d4e5545d..0d665afe5a8425bd91a02b74cfa451405974e21a 100644 --- a/registry/consul/listener.go +++ b/registry/consul/listener.go @@ -39,17 +39,17 @@ import ( // registry. type consulListener struct { // Registry url. - registryUrl common.URL + registryUrl *common.URL // Consumer url. - consumerUrl common.URL + consumerUrl *common.URL // Consul watcher. plan *watch.Plan // Most recent service urls return by // watcher. - urls []common.URL + urls []*common.URL // All service information changes will // be wrapped into ServiceEvent, and be @@ -78,7 +78,7 @@ type consulListener struct { wg sync.WaitGroup } -func newConsulListener(registryUrl common.URL, consumerUrl common.URL) (*consulListener, error) { +func newConsulListener(registryUrl *common.URL, consumerUrl *common.URL) (*consulListener, error) { params := make(map[string]interface{}, 8) params["type"] = "service" params["service"] = consumerUrl.Service() @@ -93,7 +93,7 @@ func newConsulListener(registryUrl common.URL, consumerUrl common.URL) (*consulL registryUrl: registryUrl, consumerUrl: consumerUrl, plan: plan, - urls: make([]common.URL, 0, 8), + urls: make([]*common.URL, 0, 8), eventCh: make(chan *registry.ServiceEvent, 32), errCh: make(chan error, 32), done: make(chan struct{}), @@ -142,7 +142,7 @@ func (l *consulListener) run() { func (l *consulListener) handler(idx uint64, raw interface{}) { var ( service *consul.ServiceEntry - url common.URL + url *common.URL ok bool err error ) @@ -153,7 +153,7 @@ func (l *consulListener) handler(idx uint64, raw interface{}) { l.errCh <- err return } - newUrls := make([]common.URL, 0, 8) + newUrls := make([]*common.URL, 0, 8) events := make([]*registry.ServiceEvent, 0, 8) for _, service = range services { diff --git a/registry/consul/registry.go b/registry/consul/registry.go index b92e335fdb69f82210d2977789902eb6123201b8..0b7ba9758952b072d579ae9424e2c385e59a4378 100644 --- a/registry/consul/registry.go +++ b/registry/consul/registry.go @@ -76,7 +76,7 @@ func newConsulRegistry(url *common.URL) (registry.Registry, error) { // Register register @url // it delegate the job to register() method -func (r *consulRegistry) Register(url common.URL) error { +func (r *consulRegistry) Register(url *common.URL) error { var err error role, _ := strconv.Atoi(r.URL.GetParam(constant.ROLE_KEY, "")) @@ -90,7 +90,7 @@ func (r *consulRegistry) Register(url common.URL) error { } // register actually register the @url -func (r *consulRegistry) register(url common.URL) error { +func (r *consulRegistry) register(url *common.URL) error { service, err := buildService(url) if err != nil { return err @@ -100,7 +100,7 @@ func (r *consulRegistry) register(url common.URL) error { // UnRegister unregister the @url // it delegate the job to unregister() method -func (r *consulRegistry) UnRegister(url common.URL) error { +func (r *consulRegistry) UnRegister(url *common.URL) error { var err error role, _ := strconv.Atoi(r.URL.GetParam(constant.ROLE_KEY, "")) @@ -114,7 +114,7 @@ func (r *consulRegistry) UnRegister(url common.URL) error { } // unregister actually unregister the @url -func (r *consulRegistry) unregister(url common.URL) error { +func (r *consulRegistry) unregister(url *common.URL) error { return r.client.Agent().ServiceDeregister(buildId(url)) } @@ -141,7 +141,7 @@ func (r *consulRegistry) subscribe(url *common.URL, notifyListener registry.Noti return } - listener, err := r.getListener(*url) + listener, err := r.getListener(url) if err != nil { if !r.IsAvailable() { logger.Warnf("event listener game over.") @@ -166,14 +166,14 @@ func (r *consulRegistry) subscribe(url *common.URL, notifyListener registry.Noti } } -func (r *consulRegistry) getListener(url common.URL) (registry.Listener, error) { - listener, err := newConsulListener(*r.URL, url) +func (r *consulRegistry) getListener(url *common.URL) (registry.Listener, error) { + listener, err := newConsulListener(r.URL, url) return listener, err } // GetUrl get registry URL of consul registry center -func (r *consulRegistry) GetUrl() common.URL { - return *r.URL +func (r *consulRegistry) GetUrl() *common.URL { + return r.URL } // IsAvailable checks consul registry center whether is available @@ -197,7 +197,7 @@ func (r *consulRegistry) Destroy() { } done <- struct{}{} }() - if err := r.UnRegister(*r.URL); err != nil { + if err := r.UnRegister(r.URL); err != nil { logger.Errorf("consul registry unregister with err: %s", err.Error()) } }() diff --git a/registry/consul/service_discovery_test.go b/registry/consul/service_discovery_test.go index ed7220f2de3140d4e97ea48acac1f53d29953208..2169857ee8f79a92322234a0b17a4d7122a0d975 100644 --- a/registry/consul/service_discovery_test.go +++ b/registry/consul/service_discovery_test.go @@ -44,7 +44,6 @@ var ( consulCheckPassInterval = 17000 consulDeregisterCriticalServiceAfter = "20s" consulWatchTimeout = 60000 - registryURL = common.URL{} ) func TestConsulServiceDiscovery_newConsulServiceDiscovery(t *testing.T) { @@ -173,7 +172,7 @@ func prepareData() { } } -func prepareService() (registry.ServiceInstance, common.URL) { +func prepareService() (registry.ServiceInstance, *common.URL) { id := "id" registryUrl, _ := common.NewURL(protocol + "://" + providerHost + ":" + strconv.Itoa(providerPort) + "/" + service + "?anyhost=true&" + @@ -200,19 +199,19 @@ type MockEventDispatcher struct { } // AddEventListener do nothing -func (m *MockEventDispatcher) AddEventListener(listener observer.EventListener) { +func (m *MockEventDispatcher) AddEventListener(observer.EventListener) { } // AddEventListeners do nothing -func (m *MockEventDispatcher) AddEventListeners(listenersSlice []observer.EventListener) { +func (m *MockEventDispatcher) AddEventListeners([]observer.EventListener) { } // RemoveEventListener do nothing -func (m *MockEventDispatcher) RemoveEventListener(listener observer.EventListener) { +func (m *MockEventDispatcher) RemoveEventListener(observer.EventListener) { } // RemoveEventListeners do nothing -func (m *MockEventDispatcher) RemoveEventListeners(listenersSlice []observer.EventListener) { +func (m *MockEventDispatcher) RemoveEventListeners([]observer.EventListener) { } // GetAllEventListeners return empty list diff --git a/registry/consul/utils.go b/registry/consul/utils.go index f5babf69d5970a495f8f0c23a254fe4b2a9ffbee..468dafb338e8413c66d00da974c860708a2e2210 100644 --- a/registry/consul/utils.go +++ b/registry/consul/utils.go @@ -33,12 +33,12 @@ import ( "github.com/apache/dubbo-go/common" ) -func buildId(url common.URL) string { +func buildId(url *common.URL) string { t := md5.Sum([]byte(url.String())) return hex.EncodeToString(t[:]) } -func buildService(url common.URL) (*consul.AgentServiceRegistration, error) { +func buildService(url *common.URL) (*consul.AgentServiceRegistration, error) { var err error // id @@ -93,19 +93,19 @@ func buildService(url common.URL) (*consul.AgentServiceRegistration, error) { return service, nil } -func retrieveURL(service *consul.ServiceEntry) (common.URL, error) { +func retrieveURL(service *consul.ServiceEntry) (*common.URL, error) { url, ok := service.Service.Meta["url"] if !ok { - return common.URL{}, perrors.New("retrieve url fails with no url key in service meta") + return nil, perrors.New("retrieve url fails with no url key in service meta") } url1, err := common.NewURL(url) if err != nil { - return common.URL{}, perrors.WithStack(err) + return nil, perrors.WithStack(err) } return url1, nil } -func in(url common.URL, urls []common.URL) bool { +func in(url *common.URL, urls []*common.URL) bool { for _, url1 := range urls { if url.URLEqual(url1) { return true diff --git a/registry/consul/utils_test.go b/registry/consul/utils_test.go index 0e5bffe457b9e3317ff056c51e4f5a9633a429e6..d78c534e931f9aa3e0220bb08aa29222220ce619 100644 --- a/registry/consul/utils_test.go +++ b/registry/consul/utils_test.go @@ -63,8 +63,8 @@ func newConsumerRegistryUrl(host string, port int) *common.URL { ) } -func newProviderUrl(host string, port int, service string, protocol string) common.URL { - return *common.NewURLWithOptions( +func newProviderUrl(host string, port int, service string, protocol string) *common.URL { + return common.NewURLWithOptions( common.WithIp(host), common.WithPort(strconv.Itoa(port)), common.WithPath(service), @@ -72,8 +72,8 @@ func newProviderUrl(host string, port int, service string, protocol string) comm ) } -func newConsumerUrl(host string, port int, service string, protocol string) common.URL { - return *common.NewURLWithOptions( +func newConsumerUrl(host string, port int, service string, protocol string) *common.URL { + return common.NewURLWithOptions( common.WithIp(host), common.WithPort(strconv.Itoa(port)), common.WithPath(service), @@ -130,8 +130,8 @@ type consulRegistryTestSuite struct { providerRegistry registry.Registry consumerRegistry *consulRegistry listener registry.Listener - providerUrl common.URL - consumerUrl common.URL + providerUrl *common.URL + consumerUrl *common.URL } func newConsulRegistryTestSuite(t *testing.T) *consulRegistryTestSuite { diff --git a/registry/directory/directory.go b/registry/directory/directory.go index 6f9c4fc889ddfd4b9949cc3115310e122678310e..e6ae0f3bb9004f8b933d420cdd2e7561f8232b48 100644 --- a/registry/directory/directory.go +++ b/registry/directory/directory.go @@ -149,7 +149,7 @@ func (dir *RegistryDirectory) refreshInvokers(events ...*registry.ServiceEvent) // eventMatched checks if a cached invoker appears in the incoming invoker list, if no, then it is safe to remove. func (dir *RegistryDirectory) eventMatched(key string, events []*registry.ServiceEvent) bool { for _, event := range events { - if dir.invokerCacheKey(&event.Service) == key { + if dir.invokerCacheKey(event.Service) == key { return true } } @@ -207,7 +207,7 @@ func (dir *RegistryDirectory) configRouters() { // convertUrl processes override:// and router:// func (dir *RegistryDirectory) convertUrl(res *registry.ServiceEvent) *common.URL { - ret := &res.Service + ret := res.Service if ret.Protocol == constant.OVERRIDE_PROTOCOL || // 1.for override url in 2.6.x ret.GetParam(constant.CATEGORY_KEY, constant.DEFAULT_CATEGORY) == constant.CONFIGURATORS_CATEGORY { dir.configurators = append(dir.configurators, extension.GetDefaultConfigurator(ret)) @@ -296,19 +296,19 @@ func (dir *RegistryDirectory) cacheInvoker(url *common.URL) protocol.Invoker { dir.overrideUrl(newUrl) if cacheInvoker, ok := dir.cacheInvokersMap.Load(newUrl.Key()); !ok { logger.Debugf("service will be added in cache invokers: invokers url is %s!", newUrl) - newInvoker := extension.GetProtocol(protocolwrapper.FILTER).Refer(*newUrl) + newInvoker := extension.GetProtocol(protocolwrapper.FILTER).Refer(newUrl) if newInvoker != nil { dir.cacheInvokersMap.Store(newUrl.Key(), newInvoker) } } else { // if cached invoker has the same URL with the new URL, then no need to re-refer, and no need to destroy // the old invoker. - if common.IsEquals(*newUrl, cacheInvoker.(protocol.Invoker).GetUrl()) { + if common.IsEquals(newUrl, cacheInvoker.(protocol.Invoker).GetUrl()) { return nil } logger.Debugf("service will be updated in cache invokers: new invoker url is %s, old invoker url is %s", newUrl, cacheInvoker.(protocol.Invoker).GetUrl()) - newInvoker := extension.GetProtocol(protocolwrapper.FILTER).Refer(*newUrl) + newInvoker := extension.GetProtocol(protocolwrapper.FILTER).Refer(newUrl) if newInvoker != nil { dir.cacheInvokersMap.Store(newUrl.Key(), newInvoker) return cacheInvoker.(protocol.Invoker) diff --git a/registry/directory/directory_test.go b/registry/directory/directory_test.go index f2b2f8edd2d46950d2e74733b1d869e0de282ec0..dde944d62410cee6429dbbc408eb364a354f1613 100644 --- a/registry/directory/directory_test.go +++ b/registry/directory/directory_test.go @@ -72,7 +72,7 @@ func TestSubscribe(t *testing.T) { func TestSubscribe_InvalidUrl(t *testing.T) { url, _ := common.NewURL("mock://127.0.0.1:1111") mockRegistry, _ := registry.NewMockRegistry(&common.URL{}) - _, err := NewRegistryDirectory(&url, mockRegistry) + _, err := NewRegistryDirectory(url, mockRegistry) assert.Error(t, err) } @@ -83,9 +83,9 @@ func TestSubscribe_Group(t *testing.T) { regurl, _ := common.NewURL("mock://127.0.0.1:1111") suburl, _ := common.NewURL("dubbo://127.0.0.1:20000") suburl.SetParam(constant.CLUSTER_KEY, "mock") - regurl.SubURL = &suburl + regurl.SubURL = suburl mockRegistry, _ := registry.NewMockRegistry(&common.URL{}) - dir, _ := NewRegistryDirectory(®url, mockRegistry) + dir, _ := NewRegistryDirectory(regurl, mockRegistry) go dir.(*RegistryDirectory).subscribe(common.NewURLWithOptions(common.WithPath("testservice"))) //for group1 @@ -93,7 +93,7 @@ func TestSubscribe_Group(t *testing.T) { urlmap.Set(constant.GROUP_KEY, "group1") urlmap.Set(constant.CLUSTER_KEY, "failover") //to test merge url for i := 0; i < 3; i++ { - mockRegistry.(*registry.MockRegistry).MockEvent(®istry.ServiceEvent{Action: remoting.EventTypeAdd, Service: *common.NewURLWithOptions(common.WithPath("TEST"+strconv.FormatInt(int64(i), 10)), common.WithProtocol("dubbo"), + mockRegistry.(*registry.MockRegistry).MockEvent(®istry.ServiceEvent{Action: remoting.EventTypeAdd, Service: common.NewURLWithOptions(common.WithPath("TEST"+strconv.FormatInt(int64(i), 10)), common.WithProtocol("dubbo"), common.WithParams(urlmap))}) } //for group2 @@ -101,7 +101,7 @@ func TestSubscribe_Group(t *testing.T) { urlmap2.Set(constant.GROUP_KEY, "group2") urlmap2.Set(constant.CLUSTER_KEY, "failover") //to test merge url for i := 0; i < 3; i++ { - mockRegistry.(*registry.MockRegistry).MockEvent(®istry.ServiceEvent{Action: remoting.EventTypeAdd, Service: *common.NewURLWithOptions(common.WithPath("TEST"+strconv.FormatInt(int64(i), 10)), common.WithProtocol("dubbo"), + mockRegistry.(*registry.MockRegistry).MockEvent(®istry.ServiceEvent{Action: remoting.EventTypeAdd, Service: common.NewURLWithOptions(common.WithPath("TEST"+strconv.FormatInt(int64(i), 10)), common.WithProtocol("dubbo"), common.WithParams(urlmap2))}) } @@ -202,17 +202,17 @@ func normalRegistryDir(noMockEvent ...bool) (*RegistryDirectory, *registry.MockR common.WithParamsValue(constant.GROUP_KEY, "group"), common.WithParamsValue(constant.VERSION_KEY, "1.0.0"), ) - url.SubURL = &suburl + url.SubURL = suburl mockRegistry, _ := registry.NewMockRegistry(&common.URL{}) - dir, _ := NewRegistryDirectory(&url, mockRegistry) + dir, _ := NewRegistryDirectory(url, mockRegistry) - go dir.(*RegistryDirectory).subscribe(&suburl) + go dir.(*RegistryDirectory).subscribe(suburl) if len(noMockEvent) == 0 { for i := 0; i < 3; i++ { mockRegistry.(*registry.MockRegistry).MockEvent( ®istry.ServiceEvent{ Action: remoting.EventTypeAdd, - Service: *common.NewURLWithOptions( + Service: common.NewURLWithOptions( common.WithPath("TEST"+strconv.FormatInt(int64(i), 10)), common.WithProtocol("dubbo"), ), diff --git a/registry/etcdv3/listener.go b/registry/etcdv3/listener.go index 436b6eca5b0dfb8514cbc21a47032490f7b1c21f..4bc387cafaa3c64539efb29a181a2198fbe8a30f 100644 --- a/registry/etcdv3/listener.go +++ b/registry/etcdv3/listener.go @@ -64,7 +64,7 @@ func (l *dataListener) DataChange(eventType remoting.Event) bool { } for _, v := range l.interestedURL { - if serviceURL.URLEqual(*v) { + if serviceURL.URLEqual(v) { l.listener.Process( &config_center.ConfigChangeEvent{ Key: eventType.Path, @@ -113,7 +113,7 @@ func (l *configurationListener) Next() (*registry.ServiceEvent, error) { } continue } - return ®istry.ServiceEvent{Action: e.ConfigType, Service: e.Value.(common.URL)}, nil + return ®istry.ServiceEvent{Action: e.ConfigType, Service: e.Value.(*common.URL)}, nil } } } diff --git a/registry/etcdv3/listener_test.go b/registry/etcdv3/listener_test.go index 1cf06d17dcd4c92afc5221dab404e9d180c03e6c..ff7f63f614c6c43564dc10e412a833449b3bea8a 100644 --- a/registry/etcdv3/listener_test.go +++ b/registry/etcdv3/listener_test.go @@ -80,7 +80,7 @@ func (suite *RegistryTestSuite) TestDataChange() { listener := NewRegistryDataListener(&MockDataListener{}) url, _ := common.NewURL("jsonrpc%3A%2F%2F127.0.0.1%3A20001%2Fcom.ikurento.user.UserProvider%3Fanyhost%3Dtrue%26app.version%3D0.0.1%26application%3DBDTService%26category%3Dproviders%26cluster%3Dfailover%26dubbo%3Ddubbo-provider-golang-2.6.0%26environment%3Ddev%26group%3D%26interface%3Dcom.ikurento.user.UserProvider%26ip%3D10.32.20.124%26loadbalance%3Drandom%26methods.GetUser.loadbalance%3Drandom%26methods.GetUser.retries%3D1%26methods.GetUser.weight%3D0%26module%3Ddubbogo%2Buser-info%2Bserver%26name%3DBDTService%26organization%3Dikurento.com%26owner%3DZX%26pid%3D74500%26retries%3D0%26service.filter%3Decho%26side%3Dprovider%26timestamp%3D1560155407%26version%3D%26warmup%3D100") - listener.AddInterestedURL(&url) + listener.AddInterestedURL(url) if !listener.DataChange(remoting.Event{Path: "/dubbo/com.ikurento.user.UserProvider/providers/jsonrpc%3A%2F%2F127.0.0.1%3A20001%2Fcom.ikurento.user.UserProvider%3Fanyhost%3Dtrue%26app.version%3D0.0.1%26application%3DBDTService%26category%3Dproviders%26cluster%3Dfailover%26dubbo%3Ddubbo-provider-golang-2.6.0%26environment%3Ddev%26group%3D%26interface%3Dcom.ikurento.user.UserProvider%26ip%3D10.32.20.124%26loadbalance%3Drandom%26methods.GetUser.loadbalance%3Drandom%26methods.GetUser.retries%3D1%26methods.GetUser.weight%3D0%26module%3Ddubbogo%2Buser-info%2Bserver%26name%3DBDTService%26organization%3Dikurento.com%26owner%3DZX%26pid%3D74500%26retries%3D0%26service.filter%3Decho%26side%3Dprovider%26timestamp%3D1560155407%26version%3D%26warmup%3D100"}) { t.Fatal("data change not ok") } diff --git a/registry/etcdv3/registry_test.go b/registry/etcdv3/registry_test.go index 164fe9ca61793614e3d9d2f77f49cdfaebdd7317..d94eff656dbc4f46e4b34c8c50b20396b335c073 100644 --- a/registry/etcdv3/registry_test.go +++ b/registry/etcdv3/registry_test.go @@ -39,7 +39,7 @@ func initRegistry(t *testing.T) *etcdV3Registry { t.Fatal(err) } - reg, err := newETCDV3Registry(®url) + reg, err := newETCDV3Registry(regurl) if err != nil { t.Fatal(err) } @@ -86,7 +86,7 @@ func (suite *RegistryTestSuite) TestSubscribe() { err = reg2.Register(url) assert.NoError(t, err) - listener, err := reg2.DoSubscribe(&url) + listener, err := reg2.DoSubscribe(url) if err != nil { t.Fatal(err) } @@ -104,7 +104,7 @@ func (suite *RegistryTestSuite) TestConsumerDestroy() { url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithMethods([]string{"GetUser", "AddUser"})) reg := initRegistry(t) - _, err := reg.DoSubscribe(&url) + _, err := reg.DoSubscribe(url) if err != nil { t.Fatal(err) } diff --git a/registry/event.go b/registry/event.go index 39fb00c740ef2e70e2cd6768fa4a4bb3226f832c..c93415841b1d144a462e7cf71713882e0bcdd8c6 100644 --- a/registry/event.go +++ b/registry/event.go @@ -40,7 +40,7 @@ func init() { // ServiceEvent includes create, update, delete event type ServiceEvent struct { Action remoting.EventType - Service common.URL + Service *common.URL } // String return the description of event diff --git a/registry/event/metadata_service_url_params_customizer_test.go b/registry/event/metadata_service_url_params_customizer_test.go index 98ae2df883f590f4c3e4b379bb5a0fcbe46d946c..c041232b7836986db034da9c61acabc64050757e 100644 --- a/registry/event/metadata_service_url_params_customizer_test.go +++ b/registry/event/metadata_service_url_params_customizer_test.go @@ -70,27 +70,27 @@ func (m *mockMetadataService) ServiceName() (string, error) { panic("implement me") } -func (m *mockMetadataService) ExportURL(url common.URL) (bool, error) { +func (m *mockMetadataService) ExportURL(*common.URL) (bool, error) { panic("implement me") } -func (m *mockMetadataService) UnexportURL(url common.URL) error { +func (m *mockMetadataService) UnexportURL(*common.URL) error { panic("implement me") } -func (m *mockMetadataService) SubscribeURL(url common.URL) (bool, error) { +func (m *mockMetadataService) SubscribeURL(*common.URL) (bool, error) { panic("implement me") } -func (m *mockMetadataService) UnsubscribeURL(url common.URL) error { +func (m *mockMetadataService) UnsubscribeURL(*common.URL) error { panic("implement me") } -func (m *mockMetadataService) PublishServiceDefinition(url common.URL) error { +func (m *mockMetadataService) PublishServiceDefinition(*common.URL) error { panic("implement me") } -func (m *mockMetadataService) GetExportedURLs(serviceInterface string, group string, version string, protocol string) ([]interface{}, error) { +func (m *mockMetadataService) GetExportedURLs(string, string, string, string) ([]interface{}, error) { return m.urls, nil } @@ -98,8 +98,8 @@ func (m *mockMetadataService) MethodMapper() map[string]string { panic("implement me") } -func (m *mockMetadataService) GetSubscribedURLs() ([]common.URL, error) { - res := make([]common.URL, 0, len(m.urls)) +func (m *mockMetadataService) GetSubscribedURLs() ([]*common.URL, error) { + var res []*common.URL for _, ui := range m.urls { u, _ := common.NewURL(ui.(string)) res = append(res, u) @@ -107,15 +107,15 @@ func (m *mockMetadataService) GetSubscribedURLs() ([]common.URL, error) { return res, nil } -func (m *mockMetadataService) GetServiceDefinition(interfaceName string, group string, version string) (string, error) { +func (m *mockMetadataService) GetServiceDefinition(string, string, string) (string, error) { panic("implement me") } -func (m *mockMetadataService) GetServiceDefinitionByServiceKey(serviceKey string) (string, error) { +func (m *mockMetadataService) GetServiceDefinitionByServiceKey(string) (string, error) { panic("implement me") } -func (m *mockMetadataService) RefreshMetadata(exportedRevision string, subscribedRevision string) (bool, error) { +func (m *mockMetadataService) RefreshMetadata(string, string) (bool, error) { panic("implement me") } diff --git a/registry/file/service_discovery.go b/registry/file/service_discovery.go index 59c5cf9a89140be537e4f08816e8a080a7f6a6fc..254c12688f47282343e0004dac86844ba51a3eb2 100644 --- a/registry/file/service_discovery.go +++ b/registry/file/service_discovery.go @@ -70,7 +70,7 @@ func newFileSystemServiceDiscovery(name string) (registry.ServiceDiscovery, erro p := path.Join(rp, ".dubbo", constant.REGISTRY_KEY) url, _ := common.NewURL("") url.AddParamAvoidNil(file.CONFIG_CENTER_DIR_PARAM_NAME, p) - c, err := fdcf.GetDynamicConfiguration(&url) + c, err := fdcf.GetDynamicConfiguration(url) if err != nil { return nil, perrors.WithStack(err) } diff --git a/registry/kubernetes/listener.go b/registry/kubernetes/listener.go index 24c8d81614c7dd323e4f23ec7de5d28b24eecb70..e20b7c7e7d2f72349f7ec268bbb3b09f135dc6ed 100644 --- a/registry/kubernetes/listener.go +++ b/registry/kubernetes/listener.go @@ -65,7 +65,7 @@ func (l *dataListener) DataChange(eventType remoting.Event) bool { } for _, v := range l.interestedURL { - if serviceURL.URLEqual(*v) { + if serviceURL.URLEqual(v) { l.listener.Process( &config_center.ConfigChangeEvent{ Key: eventType.Path, @@ -114,7 +114,7 @@ func (l *configurationListener) Next() (*registry.ServiceEvent, error) { } continue } - return ®istry.ServiceEvent{Action: e.ConfigType, Service: e.Value.(common.URL)}, nil + return ®istry.ServiceEvent{Action: e.ConfigType, Service: e.Value.(*common.URL)}, nil } } } diff --git a/registry/kubernetes/listener_test.go b/registry/kubernetes/listener_test.go index ccaaf80907f9eb3d4956758374f518c66fa613d5..f1d8ff41761a841aa2bec888336756854ff16874 100644 --- a/registry/kubernetes/listener_test.go +++ b/registry/kubernetes/listener_test.go @@ -166,7 +166,7 @@ var clientPodJsonData = `{ func Test_DataChange(t *testing.T) { listener := NewRegistryDataListener(&MockDataListener{}) url, _ := common.NewURL("jsonrpc%3A%2F%2F127.0.0.1%3A20001%2Fcom.ikurento.user.UserProvider%3Fanyhost%3Dtrue%26app.version%3D0.0.1%26application%3DBDTService%26category%3Dproviders%26cluster%3Dfailover%26dubbo%3Ddubbo-provider-golang-2.6.0%26environment%3Ddev%26group%3D%26interface%3Dcom.ikurento.user.UserProvider%26ip%3D10.32.20.124%26loadbalance%3Drandom%26methods.GetUser.loadbalance%3Drandom%26methods.GetUser.retries%3D1%26methods.GetUser.weight%3D0%26module%3Ddubbogo%2Buser-info%2Bserver%26name%3DBDTService%26organization%3Dikurento.com%26owner%3DZX%26pid%3D74500%26retries%3D0%26service.filter%3Decho%26side%3Dprovider%26timestamp%3D1560155407%26version%3D%26warmup%3D100") - listener.AddInterestedURL(&url) + listener.AddInterestedURL(url) int := listener.DataChange(remoting.Event{Path: "/dubbo/com.ikurento.user.UserProvider/providers/jsonrpc%3A%2F%2F127.0.0.1%3A20001%2Fcom.ikurento.user.UserProvider%3Fanyhost%3Dtrue%26app.version%3D0.0.1%26application%3DBDTService%26category%3Dproviders%26cluster%3Dfailover%26dubbo%3Ddubbo-provider-golang-2.6.0%26environment%3Ddev%26group%3D%26interface%3Dcom.ikurento.user.UserProvider%26ip%3D10.32.20.124%26loadbalance%3Drandom%26methods.GetUser.loadbalance%3Drandom%26methods.GetUser.retries%3D1%26methods.GetUser.weight%3D0%26module%3Ddubbogo%2Buser-info%2Bserver%26name%3DBDTService%26organization%3Dikurento.com%26owner%3DZX%26pid%3D74500%26retries%3D0%26service.filter%3Decho%26side%3Dprovider%26timestamp%3D1560155407%26version%3D%26warmup%3D100"}) assert.Equal(t, true, int) } @@ -179,7 +179,7 @@ func TestDataChange(t *testing.T) { listener := NewRegistryDataListener(&MockDataListener{}) url, _ := common.NewURL("jsonrpc%3A%2F%2F127.0.0.1%3A20001%2Fcom.ikurento.user.UserProvider%3Fanyhost%3Dtrue%26app.version%3D0.0.1%26application%3DBDTService%26category%3Dproviders%26cluster%3Dfailover%26dubbo%3Ddubbo-provider-golang-2.6.0%26environment%3Ddev%26group%3D%26interface%3Dcom.ikurento.user.UserProvider%26ip%3D10.32.20.124%26loadbalance%3Drandom%26methods.GetUser.loadbalance%3Drandom%26methods.GetUser.retries%3D1%26methods.GetUser.weight%3D0%26module%3Ddubbogo%2Buser-info%2Bserver%26name%3DBDTService%26organization%3Dikurento.com%26owner%3DZX%26pid%3D74500%26retries%3D0%26service.filter%3Decho%26side%3Dprovider%26timestamp%3D1560155407%26version%3D%26warmup%3D100") - listener.AddInterestedURL(&url) + listener.AddInterestedURL(url) if !listener.DataChange(remoting.Event{Path: "/dubbo/com.ikurento.user.UserProvider/providers/jsonrpc%3A%2F%2F127.0.0.1%3A20001%2Fcom.ikurento.user.UserProvider%3Fanyhost%3Dtrue%26app.version%3D0.0.1%26application%3DBDTService%26category%3Dproviders%26cluster%3Dfailover%26dubbo%3Ddubbo-provider-golang-2.6.0%26environment%3Ddev%26group%3D%26interface%3Dcom.ikurento.user.UserProvider%26ip%3D10.32.20.124%26loadbalance%3Drandom%26methods.GetUser.loadbalance%3Drandom%26methods.GetUser.retries%3D1%26methods.GetUser.weight%3D0%26module%3Ddubbogo%2Buser-info%2Bserver%26name%3DBDTService%26organization%3Dikurento.com%26owner%3DZX%26pid%3D74500%26retries%3D0%26service.filter%3Decho%26side%3Dprovider%26timestamp%3D1560155407%26version%3D%26warmup%3D100"}) { t.Fatal("data change not ok") } diff --git a/registry/kubernetes/registry_test.go b/registry/kubernetes/registry_test.go index 347dadcd2c462e3a1caf9829b051a665ec61e8e3..9fb409a222be914cad5b64e7ff3aab9bc97a6f33 100644 --- a/registry/kubernetes/registry_test.go +++ b/registry/kubernetes/registry_test.go @@ -231,7 +231,7 @@ func getTestRegistry(t *testing.T) *kubernetesRegistry { if err != nil { t.Fatal(err) } - out, err := newMockKubernetesRegistry(®url, pl) + out, err := newMockKubernetesRegistry(regurl, pl) if err != nil { t.Fatal(err) } @@ -268,7 +268,7 @@ func TestSubscribe(t *testing.T) { t.Fatal(err) } - listener, err := r.DoSubscribe(&url) + listener, err := r.DoSubscribe(url) if err != nil { t.Fatal(err) } @@ -301,7 +301,7 @@ func TestConsumerDestroy(t *testing.T) { common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithMethods([]string{"GetUser", "AddUser"})) - _, err := r.DoSubscribe(&url) + _, err := r.DoSubscribe(url) if err != nil { t.Fatal(err) } @@ -336,7 +336,7 @@ func TestNewRegistry(t *testing.T) { if err != nil { t.Fatal(err) } - _, err = newKubernetesRegistry(®Url) + _, err = newKubernetesRegistry(regUrl) if err == nil { t.Fatal("not in cluster, should be a err") } diff --git a/registry/mock_registry.go b/registry/mock_registry.go index 10561d0f49e995c94c93fa0463fc0b0421ff6e20..18c87ee3ace79d98c0d0faa6e915dd64d2fe5362 100644 --- a/registry/mock_registry.go +++ b/registry/mock_registry.go @@ -47,12 +47,12 @@ func NewMockRegistry(url *common.URL) (Registry, error) { } // Register is used as a mock registry -func (*MockRegistry) Register(url common.URL) error { +func (*MockRegistry) Register(url *common.URL) error { return nil } // nolint -func (r *MockRegistry) UnRegister(conf common.URL) error { +func (r *MockRegistry) UnRegister(conf *common.URL) error { return nil } @@ -68,8 +68,8 @@ func (r *MockRegistry) IsAvailable() bool { } // nolint -func (r *MockRegistry) GetUrl() common.URL { - return common.URL{} +func (r *MockRegistry) GetUrl() *common.URL { + return nil } func (r *MockRegistry) subscribe(*common.URL) (Listener, error) { diff --git a/registry/nacos/listener.go b/registry/nacos/listener.go index cf6a73d38fbefc1ecb6a80e4911bb0d8fb13a6f6..7f27326d6d7b1000688cb03cd6406ea53745a119 100644 --- a/registry/nacos/listener.go +++ b/registry/nacos/listener.go @@ -43,7 +43,7 @@ import ( type nacosListener struct { namingClient naming_client.INamingClient - listenUrl common.URL + listenUrl *common.URL events chan *config_center.ConfigChangeEvent instanceMap map[string]model.Instance cacheLock sync.Mutex @@ -52,7 +52,7 @@ type nacosListener struct { } // NewRegistryDataListener creates a data listener for nacos -func NewNacosListener(url common.URL, namingClient naming_client.INamingClient) (*nacosListener, error) { +func NewNacosListener(url *common.URL, namingClient naming_client.INamingClient) (*nacosListener, error) { listener := &nacosListener{ namingClient: namingClient, listenUrl: url, events: make(chan *config_center.ConfigChangeEvent, 32), @@ -154,25 +154,25 @@ func (nl *nacosListener) Callback(services []model.SubscribeService, err error) for i := range addInstances { newUrl := generateUrl(addInstances[i]) if newUrl != nil { - nl.process(&config_center.ConfigChangeEvent{Value: *newUrl, ConfigType: remoting.EventTypeAdd}) + nl.process(&config_center.ConfigChangeEvent{Value: newUrl, ConfigType: remoting.EventTypeAdd}) } } for i := range delInstances { newUrl := generateUrl(delInstances[i]) if newUrl != nil { - nl.process(&config_center.ConfigChangeEvent{Value: *newUrl, ConfigType: remoting.EventTypeDel}) + nl.process(&config_center.ConfigChangeEvent{Value: newUrl, ConfigType: remoting.EventTypeDel}) } } for i := range updateInstances { newUrl := generateUrl(updateInstances[i]) if newUrl != nil { - nl.process(&config_center.ConfigChangeEvent{Value: *newUrl, ConfigType: remoting.EventTypeUpdate}) + nl.process(&config_center.ConfigChangeEvent{Value: newUrl, ConfigType: remoting.EventTypeUpdate}) } } } -func getSubscribeName(url common.URL) string { +func getSubscribeName(url *common.URL) string { var buffer bytes.Buffer buffer.Write([]byte(common.DubboNodes[common.PROVIDER])) @@ -210,7 +210,7 @@ func (nl *nacosListener) Next() (*registry.ServiceEvent, error) { case e := <-nl.events: logger.Debugf("got nacos event %s", e) - return ®istry.ServiceEvent{Action: e.ConfigType, Service: e.Value.(common.URL)}, nil + return ®istry.ServiceEvent{Action: e.ConfigType, Service: e.Value.(*common.URL)}, nil } } } diff --git a/registry/nacos/registry.go b/registry/nacos/registry.go index 51428864fbe45aac6257d7fc1f68abcf53f638f1..ae2345e6d5c90fcfc5c4dfb5b4da07bcf1b6f43e 100644 --- a/registry/nacos/registry.go +++ b/registry/nacos/registry.go @@ -58,16 +58,16 @@ func init() { type nacosRegistry struct { *common.URL namingClient naming_client.INamingClient - registryUrls []common.URL + registryUrls []*common.URL } -func getCategory(url common.URL) string { +func getCategory(url *common.URL) string { role, _ := strconv.Atoi(url.GetParam(constant.ROLE_KEY, strconv.Itoa(constant.NACOS_DEFAULT_ROLETYPE))) category := common.DubboNodes[role] return category } -func getServiceName(url common.URL) string { +func getServiceName(url *common.URL) string { var buffer bytes.Buffer buffer.Write([]byte(getCategory(url))) @@ -77,7 +77,7 @@ func getServiceName(url common.URL) string { return buffer.String() } -func appendParam(target *bytes.Buffer, url common.URL, key string) { +func appendParam(target *bytes.Buffer, url *common.URL, key string) { value := url.GetParam(key, "") if strings.TrimSpace(value) != "" { target.Write([]byte(constant.NACOS_SERVICE_NAME_SEPARATOR)) @@ -85,7 +85,7 @@ func appendParam(target *bytes.Buffer, url common.URL, key string) { } } -func createRegisterParam(url common.URL, serviceName string) vo.RegisterInstanceParam { +func createRegisterParam(url *common.URL, serviceName string) vo.RegisterInstanceParam { category := getCategory(url) params := make(map[string]string) @@ -118,7 +118,7 @@ func createRegisterParam(url common.URL, serviceName string) vo.RegisterInstance } // Register will register the service @url to its nacos registry center -func (nr *nacosRegistry) Register(url common.URL) error { +func (nr *nacosRegistry) Register(url *common.URL) error { serviceName := getServiceName(url) param := createRegisterParam(url, serviceName) isRegistry, err := nr.namingClient.RegisterInstance(param) @@ -132,7 +132,7 @@ func (nr *nacosRegistry) Register(url common.URL) error { return nil } -func createDeregisterParam(url common.URL, serviceName string) vo.DeregisterInstanceParam { +func createDeregisterParam(url *common.URL, serviceName string) vo.DeregisterInstanceParam { if len(url.Ip) == 0 { url.Ip = localIP } @@ -148,7 +148,7 @@ func createDeregisterParam(url common.URL, serviceName string) vo.DeregisterInst } } -func (nr *nacosRegistry) DeRegister(url common.URL) error { +func (nr *nacosRegistry) DeRegister(url *common.URL) error { serviceName := getServiceName(url) param := createDeregisterParam(url, serviceName) isDeRegistry, err := nr.namingClient.DeregisterInstance(param) @@ -162,12 +162,12 @@ func (nr *nacosRegistry) DeRegister(url common.URL) error { } // UnRegister -func (nr *nacosRegistry) UnRegister(conf common.URL) error { +func (nr *nacosRegistry) UnRegister(conf *common.URL) error { return perrors.New("UnRegister is not support in nacosRegistry") } func (nr *nacosRegistry) subscribe(conf *common.URL) (registry.Listener, error) { - return NewNacosListener(*conf, nr.namingClient) + return NewNacosListener(conf, nr.namingClient) } // subscribe from registry @@ -202,7 +202,6 @@ func (nr *nacosRegistry) Subscribe(url *common.URL, notifyListener registry.Noti } } - return nil } // UnSubscribe : @@ -211,8 +210,8 @@ func (nr *nacosRegistry) UnSubscribe(url *common.URL, notifyListener registry.No } // GetUrl gets its registration URL -func (nr *nacosRegistry) GetUrl() common.URL { - return *nr.URL +func (nr *nacosRegistry) GetUrl() *common.URL { + return nr.URL } // IsAvailable determines nacos registry center whether it is available @@ -243,12 +242,12 @@ func newNacosRegistry(url *common.URL) (registry.Registry, error) { if err != nil { return &nacosRegistry{}, err } - registry := &nacosRegistry{ + tmpRegistry := &nacosRegistry{ URL: url, namingClient: client, - registryUrls: []common.URL{}, + registryUrls: []*common.URL{}, } - return registry, nil + return tmpRegistry, nil } // getNacosConfig will return the nacos config diff --git a/registry/nacos/registry_test.go b/registry/nacos/registry_test.go index d0311b200b27081c60bc97b2307a54774ca977bd..43a6da79d13c0964162f60f45ed64a854d0e3a2c 100644 --- a/registry/nacos/registry_test.go +++ b/registry/nacos/registry_test.go @@ -44,7 +44,7 @@ func TestNacosRegistry_Register(t *testing.T) { urlMap.Set(constant.CLUSTER_KEY, "mock") testUrl, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParams(urlMap), common.WithMethods([]string{"GetUser", "AddUser"})) - reg, err := newNacosRegistry(®url) + reg, err := newNacosRegistry(regurl) assert.Nil(t, err) if err != nil { t.Errorf("new nacos registry error:%s \n", err.Error()) @@ -74,7 +74,7 @@ func TestNacosRegistry_Subscribe(t *testing.T) { urlMap.Set(constant.NACOS_PATH_KEY, "") testUrl, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParams(urlMap), common.WithMethods([]string{"GetUser", "AddUser"})) - reg, _ := newNacosRegistry(®url) + reg, _ := newNacosRegistry(regurl) err := reg.Register(testUrl) assert.Nil(t, err) if err != nil { @@ -83,8 +83,8 @@ func TestNacosRegistry_Subscribe(t *testing.T) { } regurl.SetParam(constant.ROLE_KEY, strconv.Itoa(common.CONSUMER)) - reg2, _ := newNacosRegistry(®url) - listener, err := reg2.(*nacosRegistry).subscribe(&testUrl) + reg2, _ := newNacosRegistry(regurl) + listener, err := reg2.(*nacosRegistry).subscribe(testUrl) assert.Nil(t, err) if err != nil { t.Errorf("subscribe error:%s \n", err.Error()) @@ -113,7 +113,7 @@ func TestNacosRegistry_Subscribe_del(t *testing.T) { url1, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParams(urlMap), common.WithMethods([]string{"GetUser", "AddUser"})) url2, _ := common.NewURL("dubbo://127.0.0.2:20000/com.ikurento.user.UserProvider", common.WithParams(urlMap), common.WithMethods([]string{"GetUser", "AddUser"})) - reg, _ := newNacosRegistry(®url) + reg, _ := newNacosRegistry(regurl) err := reg.Register(url1) assert.Nil(t, err) if err != nil { @@ -128,8 +128,8 @@ func TestNacosRegistry_Subscribe_del(t *testing.T) { } regurl.SetParam(constant.ROLE_KEY, strconv.Itoa(common.CONSUMER)) - reg2, _ := newNacosRegistry(®url) - listener, err := reg2.(*nacosRegistry).subscribe(&url1) + reg2, _ := newNacosRegistry(regurl) + listener, err := reg2.(*nacosRegistry).subscribe(url1) assert.Nil(t, err) if err != nil { t.Errorf("subscribe error:%s \n", err.Error()) @@ -177,8 +177,8 @@ func TestNacosListener_Close(t *testing.T) { urlMap.Set(constant.CLUSTER_KEY, "mock") urlMap.Set(constant.NACOS_PATH_KEY, "") url1, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider2", common.WithParams(urlMap), common.WithMethods([]string{"GetUser", "AddUser"})) - reg, _ := newNacosRegistry(®url) - listener, err := reg.(*nacosRegistry).subscribe(&url1) + reg, _ := newNacosRegistry(regurl) + listener, err := reg.(*nacosRegistry).subscribe(url1) assert.Nil(t, err) if err != nil { t.Errorf("subscribe error:%s \n", err.Error()) diff --git a/registry/protocol/protocol.go b/registry/protocol/protocol.go index 69a31ef2f2897013cf67ed6ae320c7550c5fe912..e3af9ba97270c0c5981d1998c3db415f53a69ee7 100644 --- a/registry/protocol/protocol.go +++ b/registry/protocol/protocol.go @@ -130,31 +130,30 @@ func (proto *registryProtocol) GetRegistries() []registry.Registry { } // Refer provider service from registry center -func (proto *registryProtocol) Refer(url common.URL) protocol.Invoker { +func (proto *registryProtocol) Refer(url *common.URL) protocol.Invoker { var registryUrl = url var serviceUrl = registryUrl.SubURL if registryUrl.Protocol == constant.REGISTRY_PROTOCOL { - protocol := registryUrl.GetParam(constant.REGISTRY_KEY, "") - registryUrl.Protocol = protocol + registryUrl.Protocol = registryUrl.GetParam(constant.REGISTRY_KEY, "") } var reg registry.Registry if regI, loaded := proto.registries.Load(registryUrl.Key()); !loaded { - reg = getRegistry(®istryUrl) + reg = getRegistry(registryUrl) proto.registries.Store(registryUrl.Key(), reg) } else { reg = regI.(registry.Registry) } // new registry directory for store service url from registry - directory, err := extension.GetDefaultRegistryDirectory(®istryUrl, reg) + directory, err := extension.GetDefaultRegistryDirectory(registryUrl, reg) if err != nil { logger.Errorf("consumer service %v create registry directory error, error message is %s, and will return nil invoker!", serviceUrl.String(), err.Error()) return nil } - err = reg.Register(*serviceUrl) + err = reg.Register(serviceUrl) if err != nil { logger.Errorf("consumer service %v register registry %v error, error message is %s", serviceUrl.String(), registryUrl.String(), err.Error()) @@ -194,7 +193,7 @@ func (proto *registryProtocol) Export(invoker protocol.Invoker) protocol.Exporte } registeredProviderUrl := getUrlToRegistry(providerUrl, registryUrl) - err := reg.Register(*registeredProviderUrl) + err := reg.Register(registeredProviderUrl) if err != nil { logger.Errorf("provider service %v register registry %v error, error message is %s", providerUrl.Key(), registryUrl.Key(), err.Error()) @@ -247,8 +246,8 @@ func (nl *overrideSubscribeListener) Notify(events ...*registry.ServiceEvent) { } event := events[0] - if isMatched(&(event.Service), nl.url) && event.Action == remoting.EventTypeAdd { - nl.configurator = extension.GetDefaultConfigurator(&(event.Service)) + if isMatched(event.Service, nl.url) && event.Action == remoting.EventTypeAdd { + nl.configurator = extension.GetDefaultConfigurator(event.Service) nl.doOverrideIfNecessary() } } @@ -275,9 +274,9 @@ func (nl *overrideSubscribeListener) doOverrideIfNecessary() { } if currentUrl.String() != providerUrl.String() { - newRegUrl := nl.originInvoker.GetUrl() - setProviderUrl(&newRegUrl, providerUrl) - nl.protocol.reExport(nl.originInvoker, &newRegUrl) + newRegUrl := nl.originInvoker.GetUrl().Clone() + setProviderUrl(newRegUrl, providerUrl) + nl.protocol.reExport(nl.originInvoker, newRegUrl) } } } @@ -369,10 +368,9 @@ func getRegistryUrl(invoker protocol.Invoker) *common.URL { url := invoker.GetUrl() // if the protocol == registry, set protocol the registry value in url.params if url.Protocol == constant.REGISTRY_PROTOCOL { - protocol := url.GetParam(constant.REGISTRY_KEY, "") - url.Protocol = protocol + url.Protocol = url.GetParam(constant.REGISTRY_KEY, "") } - return &url + return url } func getProviderUrl(invoker protocol.Invoker) *common.URL { @@ -401,7 +399,7 @@ type wrappedInvoker struct { func newWrappedInvoker(invoker protocol.Invoker, url *common.URL) *wrappedInvoker { return &wrappedInvoker{ invoker: invoker, - BaseInvoker: *protocol.NewBaseInvoker(*url), + BaseInvoker: *protocol.NewBaseInvoker(url), } } diff --git a/registry/protocol/protocol_test.go b/registry/protocol/protocol_test.go index 2d6e0248fddb88bfa5ce19546fb7aed703b0fd3c..0fca55221d54c50645bf253c52ec10725f757db3 100644 --- a/registry/protocol/protocol_test.go +++ b/registry/protocol/protocol_test.go @@ -59,7 +59,7 @@ func referNormal(t *testing.T, regProtocol *registryProtocol) { common.WithParamsValue(constant.CLUSTER_KEY, "mock"), ) - url.SubURL = &suburl + url.SubURL = suburl invoker := regProtocol.Refer(url) assert.IsType(t, &protocol.BaseInvoker{}, invoker) @@ -84,7 +84,7 @@ func TestMultiRegRefer(t *testing.T) { common.WithParamsValue(constant.CLUSTER_KEY, "mock"), ) - url2.SubURL = &suburl2 + url2.SubURL = suburl2 regProtocol.Refer(url2) var count int @@ -105,7 +105,7 @@ func TestOneRegRefer(t *testing.T) { common.WithParamsValue(constant.CLUSTER_KEY, "mock"), ) - url2.SubURL = &suburl2 + url2.SubURL = suburl2 regProtocol.Refer(url2) var count int @@ -128,13 +128,13 @@ func exporterNormal(t *testing.T, regProtocol *registryProtocol) *common.URL { common.WithParamsValue(constant.VERSION_KEY, "1.0.0"), ) - url.SubURL = &suburl + url.SubURL = suburl invoker := protocol.NewBaseInvoker(url) exporter := regProtocol.Export(invoker) assert.IsType(t, &protocol.BaseExporter{}, exporter) assert.Equal(t, exporter.GetInvoker().GetUrl().String(), suburl.String()) - return &url + return url } func TestExporter(t *testing.T) { @@ -153,7 +153,7 @@ func TestMultiRegAndMultiProtoExporter(t *testing.T) { common.WithParamsValue(constant.CLUSTER_KEY, "mock"), ) - url2.SubURL = &suburl2 + url2.SubURL = suburl2 invoker2 := protocol.NewBaseInvoker(url2) regProtocol.Export(invoker2) @@ -184,7 +184,7 @@ func TestOneRegAndProtoExporter(t *testing.T) { common.WithParamsValue(constant.VERSION_KEY, "1.0.0"), ) - url2.SubURL = &suburl2 + url2.SubURL = suburl2 invoker2 := protocol.NewBaseInvoker(url2) regProtocol.Export(invoker2) @@ -253,7 +253,7 @@ func TestExportWithOverrideListener(t *testing.T) { func TestExportWithServiceConfig(t *testing.T) { extension.SetDefaultConfigurator(configurator.NewMockConfigurator) ccUrl, _ := common.NewURL("mock://127.0.0.1:1111") - dc, _ := (&config_center.MockDynamicConfigurationFactory{}).GetDynamicConfiguration(&ccUrl) + dc, _ := (&config_center.MockDynamicConfigurationFactory{}).GetDynamicConfiguration(ccUrl) common_cfg.GetEnvInstance().SetDynamicConfiguration(dc) regProtocol := newRegistryProtocol() url := exporterNormal(t, regProtocol) @@ -265,6 +265,7 @@ func TestExportWithServiceConfig(t *testing.T) { newUrl := url.SubURL.Clone() newUrl.SetParam(constant.CLUSTER_KEY, "mock1") + v2, _ := regProtocol.bounds.Load(getCacheKey(newUrl)) assert.NotNil(t, v2) } @@ -272,7 +273,7 @@ func TestExportWithServiceConfig(t *testing.T) { func TestExportWithApplicationConfig(t *testing.T) { extension.SetDefaultConfigurator(configurator.NewMockConfigurator) ccUrl, _ := common.NewURL("mock://127.0.0.1:1111") - dc, _ := (&config_center.MockDynamicConfigurationFactory{}).GetDynamicConfiguration(&ccUrl) + dc, _ := (&config_center.MockDynamicConfigurationFactory{}).GetDynamicConfiguration(ccUrl) common_cfg.GetEnvInstance().SetDynamicConfiguration(dc) regProtocol := newRegistryProtocol() url := exporterNormal(t, regProtocol) @@ -290,7 +291,7 @@ func TestExportWithApplicationConfig(t *testing.T) { func TestGetProviderUrlWithHideKey(t *testing.T) { url, _ := common.NewURL("dubbo://127.0.0.1:1111?a=a1&b=b1&.c=c1&.d=d1&e=e1&protocol=registry") - providerUrl := getUrlToRegistry(&url, &url) + providerUrl := getUrlToRegistry(url, url) assert.NotContains(t, providerUrl.GetParams(), ".c") assert.NotContains(t, providerUrl.GetParams(), ".d") assert.Contains(t, providerUrl.GetParams(), "a") diff --git a/registry/registry.go b/registry/registry.go index 2225d2c1fc6d465bfbf27cd9622d7296e4596d8f..73940fa12acd195bd24c05b4ef22af70b92fc659 100644 --- a/registry/registry.go +++ b/registry/registry.go @@ -34,7 +34,7 @@ type Registry interface { // Register is used for service provider calling, register services // to registry. And it is also used for service consumer calling, register // services cared about, for dubbo's admin monitoring. - Register(url common.URL) error + Register(url *common.URL) error // UnRegister is required to support the contract: // 1. If it is the persistent stored data of dynamic=false, the @@ -43,7 +43,7 @@ type Registry interface { // 2. Unregister according to the full url match. // url Registration information, is not allowed to be empty, e.g: // dubbo://10.20.153.10/org.apache.dubbo.foo.BarService?version=1.0.0&application=kylin - UnRegister(url common.URL) error + UnRegister(url *common.URL) error // Subscribe is required to support the contract: // When creating new registry extension, pls select one of the diff --git a/registry/servicediscovery/instance/random/random_service_instance_selector.go b/registry/servicediscovery/instance/random/random_service_instance_selector.go index 3f8f30dc8e9e91f9c75f8ff0611c98bb2f0c7b85..7e4e0eefbbe7f9ce39ee5da1e9f6a9d8ad61c737 100644 --- a/registry/servicediscovery/instance/random/random_service_instance_selector.go +++ b/registry/servicediscovery/instance/random/random_service_instance_selector.go @@ -41,7 +41,7 @@ func NewRandomServiceInstanceSelector() instance.ServiceInstanceSelector { return &RandomServiceInstanceSelector{} } -func (r *RandomServiceInstanceSelector) Select(url common.URL, serviceInstances []registry.ServiceInstance) registry.ServiceInstance { +func (r *RandomServiceInstanceSelector) Select(url *common.URL, serviceInstances []registry.ServiceInstance) registry.ServiceInstance { if len(serviceInstances) == 0 { return nil } diff --git a/registry/servicediscovery/instance/random/random_service_instance_selector_test.go b/registry/servicediscovery/instance/random/random_service_instance_selector_test.go index cddeb42c904131cdc6a62e5142de850410a3ec5a..c53c058be912ba6fd2a66e42883914fdf1d60eb1 100644 --- a/registry/servicediscovery/instance/random/random_service_instance_selector_test.go +++ b/registry/servicediscovery/instance/random/random_service_instance_selector_test.go @@ -52,5 +52,5 @@ func TestRandomServiceInstanceSelector_Select(t *testing.T) { Metadata: nil, }, } - assert.NotNil(t, selector.Select(common.URL{}, serviceInstances)) + assert.NotNil(t, selector.Select(&common.URL{}, serviceInstances)) } diff --git a/registry/servicediscovery/instance/service_instance_selector.go b/registry/servicediscovery/instance/service_instance_selector.go index 82fb3458be2838e9a5780e95be71aa89039b664f..5690ab6c9013d82b1a6ee87797dd7e424e5c07b6 100644 --- a/registry/servicediscovery/instance/service_instance_selector.go +++ b/registry/servicediscovery/instance/service_instance_selector.go @@ -24,5 +24,5 @@ import ( type ServiceInstanceSelector interface { //Select an instance of ServiceInstance by the specified ServiceInstance service instances - Select(url common.URL, serviceInstances []registry.ServiceInstance) registry.ServiceInstance + Select(url *common.URL, serviceInstances []registry.ServiceInstance) registry.ServiceInstance } diff --git a/registry/servicediscovery/service_discovery_registry.go b/registry/servicediscovery/service_discovery_registry.go index 4db2c5aad438784b1289b4473aa8d23c4f8d923f..ad6ec981ded9e224cecc0fa37c8e7f8c0254a932 100644 --- a/registry/servicediscovery/service_discovery_registry.go +++ b/registry/servicediscovery/service_discovery_registry.go @@ -26,7 +26,6 @@ import ( ) import ( - cm "github.com/Workiva/go-datastructures/common" gxset "github.com/dubbogo/gost/container/set" perrors "github.com/pkg/errors" "go.uber.org/atomic" @@ -70,7 +69,7 @@ type serviceDiscoveryRegistry struct { metaDataService service.MetadataService registeredListeners *gxset.HashSet subscribedURLsSynthesizers []synthesizer.SubscribedURLsSynthesizer - serviceRevisionExportedURLsCache map[string]map[string][]common.URL + serviceRevisionExportedURLsCache map[string]map[string][]*common.URL } func newServiceDiscoveryRegistry(url *common.URL) (registry.Registry, error) { @@ -94,13 +93,13 @@ func newServiceDiscoveryRegistry(url *common.URL) (registry.Registry, error) { subscribedServices: subscribedServices, subscribedURLsSynthesizers: subscribedURLsSynthesizers, registeredListeners: gxset.NewSet(), - serviceRevisionExportedURLsCache: make(map[string]map[string][]common.URL, 8), + serviceRevisionExportedURLsCache: make(map[string]map[string][]*common.URL, 8), serviceNameMapping: serviceNameMapping, metaDataService: metaDataService, }, nil } -func (s *serviceDiscoveryRegistry) UnRegister(url common.URL) error { +func (s *serviceDiscoveryRegistry) UnRegister(url *common.URL) error { if !shouldRegister(url) { return nil } @@ -108,10 +107,10 @@ func (s *serviceDiscoveryRegistry) UnRegister(url common.URL) error { } func (s *serviceDiscoveryRegistry) UnSubscribe(url *common.URL, listener registry.NotifyListener) error { - if !shouldSubscribe(*url) { + if !shouldSubscribe(url) { return nil } - return s.metaDataService.UnsubscribeURL(*url) + return s.metaDataService.UnsubscribeURL(url) } func creatServiceDiscovery(url *common.URL) (registry.ServiceDiscovery, error) { @@ -145,8 +144,8 @@ func (s *serviceDiscoveryRegistry) GetServiceDiscovery() registry.ServiceDiscove return s.serviceDiscovery } -func (s *serviceDiscoveryRegistry) GetUrl() common.URL { - return *s.url +func (s *serviceDiscoveryRegistry) GetUrl() *common.URL { + return s.url } func (s *serviceDiscoveryRegistry) IsAvailable() bool { @@ -161,7 +160,7 @@ func (s *serviceDiscoveryRegistry) Destroy() { } } -func (s *serviceDiscoveryRegistry) Register(url common.URL) error { +func (s *serviceDiscoveryRegistry) Register(url *common.URL) error { if !shouldRegister(url) { return nil } @@ -185,7 +184,7 @@ func (s *serviceDiscoveryRegistry) Register(url common.URL) error { url.Protocol) } -func shouldRegister(url common.URL) bool { +func shouldRegister(url *common.URL) bool { side := url.GetParam(constant.SIDE_KEY, "") if side == constant.PROVIDER_PROTOCOL { return true @@ -195,14 +194,14 @@ func shouldRegister(url common.URL) bool { } func (s *serviceDiscoveryRegistry) Subscribe(url *common.URL, notify registry.NotifyListener) error { - if !shouldSubscribe(*url) { + if !shouldSubscribe(url) { return nil } - _, err := s.metaDataService.SubscribeURL(*url) + _, err := s.metaDataService.SubscribeURL(url) if err != nil { return perrors.WithMessage(err, "subscribe url error: "+url.String()) } - services := s.getServices(*url) + services := s.getServices(url) if services.Empty() { return perrors.Errorf("Should has at least one way to know which services this interface belongs to, "+ "subscription url:%s", url.String()) @@ -218,12 +217,12 @@ func (s *serviceDiscoveryRegistry) Subscribe(url *common.URL, notify registry.No serviceDiscoveryRegistry: s, }, } - s.registerServiceInstancesChangedListener(*url, listener) + s.registerServiceInstancesChangedListener(url, listener) } return nil } -func (s *serviceDiscoveryRegistry) registerServiceInstancesChangedListener(url common.URL, listener *registry.ServiceInstancesChangedListener) { +func (s *serviceDiscoveryRegistry) registerServiceInstancesChangedListener(url *common.URL, listener *registry.ServiceInstancesChangedListener) { listenerId := listener.ServiceName + ":" + getUrlKey(url) if !s.subscribedServices.Contains(listenerId) { err := s.serviceDiscovery.AddListener(listener) @@ -234,7 +233,7 @@ func (s *serviceDiscoveryRegistry) registerServiceInstancesChangedListener(url c } -func getUrlKey(url common.URL) string { +func getUrlKey(url *common.URL) string { var bf bytes.Buffer if len(url.Protocol) != 0 { bf.WriteString(url.Protocol) @@ -256,7 +255,7 @@ func getUrlKey(url common.URL) string { return bf.String() } -func appendParam(buffer bytes.Buffer, paramKey string, url common.URL) { +func appendParam(buffer bytes.Buffer, paramKey string, url *common.URL) { buffer.WriteString(paramKey) buffer.WriteString("=") buffer.WriteString(url.GetParam(paramKey, "")) @@ -268,8 +267,8 @@ func (s *serviceDiscoveryRegistry) subscribe(url *common.URL, notify registry.No logger.Warnf("here is no instance in service[name : %s]", serviceName) return } - var subscribedURLs []common.URL - subscribedURLs = append(subscribedURLs, s.getExportedUrls(*url, serviceInstances)...) + var subscribedURLs []*common.URL + subscribedURLs = append(subscribedURLs, s.getExportedUrls(url, serviceInstances)...) if len(subscribedURLs) == 0 { subscribedURLs = s.synthesizeSubscribedURLs(url, serviceInstances) } @@ -282,8 +281,8 @@ func (s *serviceDiscoveryRegistry) subscribe(url *common.URL, notify registry.No } -func (s *serviceDiscoveryRegistry) synthesizeSubscribedURLs(subscribedURL *common.URL, serviceInstances []registry.ServiceInstance) []common.URL { - var urls []common.URL +func (s *serviceDiscoveryRegistry) synthesizeSubscribedURLs(subscribedURL *common.URL, serviceInstances []registry.ServiceInstance) []*common.URL { + var urls []*common.URL for _, syn := range s.subscribedURLsSynthesizers { if syn.Support(subscribedURL) { urls = append(urls, syn.Synthesize(subscribedURL, serviceInstances)...) @@ -292,11 +291,11 @@ func (s *serviceDiscoveryRegistry) synthesizeSubscribedURLs(subscribedURL *commo return urls } -func shouldSubscribe(url common.URL) bool { +func shouldSubscribe(url *common.URL) bool { return !shouldRegister(url) } -func (s *serviceDiscoveryRegistry) getServices(url common.URL) *gxset.HashSet { +func (s *serviceDiscoveryRegistry) getServices(url *common.URL) *gxset.HashSet { services := gxset.NewSet() serviceNames := url.GetParam(constant.PROVIDER_BY, "") if len(serviceNames) > 0 { @@ -311,7 +310,7 @@ func (s *serviceDiscoveryRegistry) getServices(url common.URL) *gxset.HashSet { return services } -func (s *serviceDiscoveryRegistry) findMappedServices(url common.URL) *gxset.HashSet { +func (s *serviceDiscoveryRegistry) findMappedServices(url *common.URL) *gxset.HashSet { serviceInterface := url.GetParam(constant.INTERFACE_KEY, url.Path) group := url.GetParam(constant.GROUP_KEY, "") version := url.GetParam(constant.VERSION_KEY, "") @@ -325,7 +324,7 @@ func (s *serviceDiscoveryRegistry) findMappedServices(url common.URL) *gxset.Has return serviceNames } -func (s *serviceDiscoveryRegistry) getExportedUrls(subscribedURL common.URL, serviceInstances []registry.ServiceInstance) []common.URL { +func (s *serviceDiscoveryRegistry) getExportedUrls(subscribedURL *common.URL, serviceInstances []registry.ServiceInstance) []*common.URL { var filterInstances []registry.ServiceInstance for _, s := range serviceInstances { if !s.IsEnable() || !s.IsHealthy() { @@ -340,32 +339,15 @@ func (s *serviceDiscoveryRegistry) getExportedUrls(subscribedURL common.URL, ser filterInstances = append(filterInstances, s) } if len(filterInstances) == 0 { - return []common.URL{} + return []*common.URL{} } s.prepareServiceRevisionExportedURLs(filterInstances) subscribedURLs := s.cloneExportedURLs(subscribedURL, filterInstances) return subscribedURLs } -// comparator is defined as Comparator for skip list to compare the URL -type comparator common.URL - -// Compare is defined as Comparator for skip list to compare the URL -func (c comparator) Compare(comp cm.Comparator) int { - a := common.URL(c).String() - b := common.URL(comp.(comparator)).String() - switch { - case a > b: - return 1 - case a < b: - return -1 - default: - return 0 - } -} - -func (s *serviceDiscoveryRegistry) getExportedUrlsByInst(serviceInstance registry.ServiceInstance) []common.URL { - var urls []common.URL +func (s *serviceDiscoveryRegistry) getExportedUrlsByInst(serviceInstance registry.ServiceInstance) []*common.URL { + var urls []*common.URL metadataStorageType := getExportedStoreType(serviceInstance) proxyFactory := extension.GetMetadataServiceProxyFactory(metadataStorageType) if proxyFactory == nil { @@ -381,7 +363,7 @@ func (s *serviceDiscoveryRegistry) getExportedUrlsByInst(serviceInstance registr return urls } - ret := make([]common.URL, 0, len(result)) + ret := make([]*common.URL, 0, len(result)) for _, ui := range result { u, err := common.NewURL(ui.(string)) @@ -464,18 +446,18 @@ func (s *serviceDiscoveryRegistry) selectServiceInstance(serviceInstances []regi logger.Errorf("get service instance selector cathe error:%s", err.Error()) return nil } - return selector.Select(*s.url, serviceInstances) + return selector.Select(s.url, serviceInstances) } -func (s *serviceDiscoveryRegistry) initRevisionExportedURLsByInst(serviceInstance registry.ServiceInstance) []common.URL { +func (s *serviceDiscoveryRegistry) initRevisionExportedURLsByInst(serviceInstance registry.ServiceInstance) []*common.URL { if serviceInstance == nil { - return []common.URL{} + return nil } serviceName := serviceInstance.GetServiceName() revision := getExportedServicesRevision(serviceInstance) revisionExportedURLsMap := s.serviceRevisionExportedURLsCache[serviceName] if revisionExportedURLsMap == nil { - revisionExportedURLsMap = make(map[string][]common.URL, 4) + revisionExportedURLsMap = make(map[string][]*common.URL, 4) s.serviceRevisionExportedURLsCache[serviceName] = revisionExportedURLsMap } revisionExportedURLs := revisionExportedURLsMap[revision] @@ -521,11 +503,11 @@ func getExportedStoreType(serviceInstance registry.ServiceInstance) string { return result } -func (s *serviceDiscoveryRegistry) cloneExportedURLs(url common.URL, serviceInsances []registry.ServiceInstance) []common.URL { +func (s *serviceDiscoveryRegistry) cloneExportedURLs(url *common.URL, serviceInsances []registry.ServiceInstance) []*common.URL { if len(serviceInsances) == 0 { - return []common.URL{} + return []*common.URL{} } - var clonedExportedURLs []common.URL + var clonedExportedURLs []*common.URL removeParamSet := gxset.NewSet() removeParamSet.Add(constant.PID_KEY) removeParamSet.Add(constant.TIMESTAMP_KEY) @@ -540,7 +522,7 @@ func (s *serviceDiscoveryRegistry) cloneExportedURLs(url common.URL, serviceInsa } cloneUrl := u.CloneExceptParams(removeParamSet) - clonedExportedURLs = append(clonedExportedURLs, *cloneUrl) + clonedExportedURLs = append(clonedExportedURLs, cloneUrl) } } return clonedExportedURLs @@ -548,8 +530,8 @@ func (s *serviceDiscoveryRegistry) cloneExportedURLs(url common.URL, serviceInsa } type endpoint struct { - Port int `json:"port, omitempty"` - Protocol string `json:"protocol, omitempty"` + Port int `json:"port,omitempty"` + Protocol string `json:"protocol,omitempty"` } func getProtocolPort(serviceInstance registry.ServiceInstance, protocol string) int { @@ -571,38 +553,38 @@ func getProtocolPort(serviceInstance registry.ServiceInstance, protocol string) } return -1 } -func (s *serviceDiscoveryRegistry) getTemplateExportedURLs(url common.URL, serviceInstance registry.ServiceInstance) []common.URL { +func (s *serviceDiscoveryRegistry) getTemplateExportedURLs(url *common.URL, serviceInstance registry.ServiceInstance) []*common.URL { exportedURLs := s.getRevisionExportedURLs(serviceInstance) if len(exportedURLs) == 0 { - return []common.URL{} + return []*common.URL{} } return filterSubscribedURLs(url, exportedURLs) } -func (s *serviceDiscoveryRegistry) getRevisionExportedURLs(serviceInstance registry.ServiceInstance) []common.URL { +func (s *serviceDiscoveryRegistry) getRevisionExportedURLs(serviceInstance registry.ServiceInstance) []*common.URL { if serviceInstance == nil { - return []common.URL{} + return []*common.URL{} } serviceName := serviceInstance.GetServiceName() revision := getExportedServicesRevision(serviceInstance) s.lock.RLock() revisionExportedURLsMap, exist := s.serviceRevisionExportedURLsCache[serviceName] if !exist { - return []common.URL{} + return []*common.URL{} } exportedURLs, exist := revisionExportedURLsMap[revision] if !exist { - return []common.URL{} + return []*common.URL{} } s.lock.RUnlock() // Get a copy from source in order to prevent the caller trying to change the cached data - cloneExportedURLs := make([]common.URL, len(exportedURLs)) + cloneExportedURLs := make([]*common.URL, len(exportedURLs)) copy(cloneExportedURLs, exportedURLs) return cloneExportedURLs } -func filterSubscribedURLs(subscribedURL common.URL, exportedURLs []common.URL) []common.URL { - var filterExportedURLs []common.URL +func filterSubscribedURLs(subscribedURL *common.URL, exportedURLs []*common.URL) []*common.URL { + var filterExportedURLs []*common.URL for _, url := range exportedURLs { if url.GetParam(constant.INTERFACE_KEY, url.Path) != subscribedURL.GetParam(constant.INTERFACE_KEY, url.Path) { break diff --git a/registry/servicediscovery/service_discovery_registry_test.go b/registry/servicediscovery/service_discovery_registry_test.go index 53eb86507e635be32eb362519922f7042f945519..ad6b73d3b4da77e5fe21a3085cdc21d3eca0246d 100644 --- a/registry/servicediscovery/service_discovery_registry_test.go +++ b/registry/servicediscovery/service_discovery_registry_test.go @@ -76,7 +76,7 @@ func TestServiceDiscoveryRegistry_Register(t *testing.T) { "&service_discovery=mock" + "&methods=getAllServiceKeys,getServiceRestMetadata,getExportedURLs,getAllExportedURLs" + "&side=provider") - registry, err := newServiceDiscoveryRegistry(®istryURL) + registry, err := newServiceDiscoveryRegistry(registryURL) assert.Nil(t, err) assert.NotNil(t, registry) registry.Register(url) @@ -85,19 +85,19 @@ func TestServiceDiscoveryRegistry_Register(t *testing.T) { type mockEventDispatcher struct { } -func (m *mockEventDispatcher) AddEventListener(listener observer.EventListener) { +func (m *mockEventDispatcher) AddEventListener(observer.EventListener) { } -func (m *mockEventDispatcher) AddEventListeners(listenersSlice []observer.EventListener) { +func (m *mockEventDispatcher) AddEventListeners([]observer.EventListener) { } -func (m *mockEventDispatcher) RemoveEventListener(listener observer.EventListener) { +func (m *mockEventDispatcher) RemoveEventListener(observer.EventListener) { panic("implement me") } -func (m *mockEventDispatcher) RemoveEventListeners(listenersSlice []observer.EventListener) { +func (m *mockEventDispatcher) RemoveEventListeners([]observer.EventListener) { panic("implement me") } @@ -109,17 +109,17 @@ func (m *mockEventDispatcher) RemoveAllEventListeners() { panic("implement me") } -func (m *mockEventDispatcher) Dispatch(event observer.Event) { +func (m *mockEventDispatcher) Dispatch(observer.Event) { } type mockServiceNameMapping struct { } -func (m *mockServiceNameMapping) Map(serviceInterface string, group string, version string, protocol string) error { +func (m *mockServiceNameMapping) Map(string, string, string, string) error { return nil } -func (m *mockServiceNameMapping) Get(serviceInterface string, group string, version string, protocol string) (*gxset.HashSet, error) { +func (m *mockServiceNameMapping) Get(string, string, string, string) (*gxset.HashSet, error) { panic("implement me") } @@ -134,15 +134,15 @@ func (m *mockServiceDiscovery) Destroy() error { panic("implement me") } -func (m *mockServiceDiscovery) Register(instance registry.ServiceInstance) error { +func (m *mockServiceDiscovery) Register(registry.ServiceInstance) error { return nil } -func (m *mockServiceDiscovery) Update(instance registry.ServiceInstance) error { +func (m *mockServiceDiscovery) Update(registry.ServiceInstance) error { panic("implement me") } -func (m *mockServiceDiscovery) Unregister(instance registry.ServiceInstance) error { +func (m *mockServiceDiscovery) Unregister(registry.ServiceInstance) error { panic("implement me") } @@ -154,35 +154,35 @@ func (m *mockServiceDiscovery) GetServices() *gxset.HashSet { panic("implement me") } -func (m *mockServiceDiscovery) GetInstances(serviceName string) []registry.ServiceInstance { +func (m *mockServiceDiscovery) GetInstances(string) []registry.ServiceInstance { panic("implement me") } -func (m *mockServiceDiscovery) GetInstancesByPage(serviceName string, offset int, pageSize int) gxpage.Pager { +func (m *mockServiceDiscovery) GetInstancesByPage(string, int, int) gxpage.Pager { panic("implement me") } -func (m *mockServiceDiscovery) GetHealthyInstancesByPage(serviceName string, offset int, pageSize int, healthy bool) gxpage.Pager { +func (m *mockServiceDiscovery) GetHealthyInstancesByPage(string, int, int, bool) gxpage.Pager { panic("implement me") } -func (m *mockServiceDiscovery) GetRequestInstances(serviceNames []string, offset int, requestedSize int) map[string]gxpage.Pager { +func (m *mockServiceDiscovery) GetRequestInstances([]string, int, int) map[string]gxpage.Pager { panic("implement me") } -func (m *mockServiceDiscovery) AddListener(listener *registry.ServiceInstancesChangedListener) error { +func (m *mockServiceDiscovery) AddListener(*registry.ServiceInstancesChangedListener) error { panic("implement me") } -func (m *mockServiceDiscovery) DispatchEventByServiceName(serviceName string) error { +func (m *mockServiceDiscovery) DispatchEventByServiceName(string) error { panic("implement me") } -func (m *mockServiceDiscovery) DispatchEventForInstances(serviceName string, instances []registry.ServiceInstance) error { +func (m *mockServiceDiscovery) DispatchEventForInstances(string, []registry.ServiceInstance) error { panic("implement me") } -func (m *mockServiceDiscovery) DispatchEvent(event *registry.ServiceInstancesChangedEvent) error { +func (m *mockServiceDiscovery) DispatchEvent(*registry.ServiceInstancesChangedEvent) error { panic("implement me") } @@ -197,27 +197,27 @@ func (m *mockMetadataService) ServiceName() (string, error) { panic("implement me") } -func (m *mockMetadataService) ExportURL(url common.URL) (bool, error) { +func (m *mockMetadataService) ExportURL(*common.URL) (bool, error) { return true, nil } -func (m *mockMetadataService) UnexportURL(url common.URL) error { +func (m *mockMetadataService) UnexportURL(*common.URL) error { panic("implement me") } -func (m *mockMetadataService) SubscribeURL(url common.URL) (bool, error) { +func (m *mockMetadataService) SubscribeURL(*common.URL) (bool, error) { panic("implement me") } -func (m *mockMetadataService) UnsubscribeURL(url common.URL) error { +func (m *mockMetadataService) UnsubscribeURL(*common.URL) error { panic("implement me") } -func (m *mockMetadataService) PublishServiceDefinition(url common.URL) error { +func (m *mockMetadataService) PublishServiceDefinition(*common.URL) error { return nil } -func (m *mockMetadataService) GetExportedURLs(serviceInterface string, group string, version string, protocol string) ([]interface{}, error) { +func (m *mockMetadataService) GetExportedURLs(string, string, string, string) ([]interface{}, error) { panic("implement me") } @@ -225,19 +225,19 @@ func (m *mockMetadataService) MethodMapper() map[string]string { panic("implement me") } -func (m *mockMetadataService) GetSubscribedURLs() ([]common.URL, error) { +func (m *mockMetadataService) GetSubscribedURLs() ([]*common.URL, error) { panic("implement me") } -func (m *mockMetadataService) GetServiceDefinition(interfaceName string, group string, version string) (string, error) { +func (m *mockMetadataService) GetServiceDefinition(string, string, string) (string, error) { panic("implement me") } -func (m *mockMetadataService) GetServiceDefinitionByServiceKey(serviceKey string) (string, error) { +func (m *mockMetadataService) GetServiceDefinitionByServiceKey(string) (string, error) { panic("implement me") } -func (m *mockMetadataService) RefreshMetadata(exportedRevision string, subscribedRevision string) (bool, error) { +func (m *mockMetadataService) RefreshMetadata(string, string) (bool, error) { panic("implement me") } diff --git a/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go b/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go index 086a26de58f8472e35e07a8a174fdee86afa82f2..d1ab6113b31a779529cc7e33ffd0f14233dd9ad6 100644 --- a/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go +++ b/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go @@ -44,8 +44,8 @@ func (r RestSubscribedURLsSynthesizer) Support(subscribedURL *common.URL) bool { return false } -func (r RestSubscribedURLsSynthesizer) Synthesize(subscribedURL *common.URL, serviceInstances []registry.ServiceInstance) []common.URL { - urls := make([]common.URL, len(serviceInstances), len(serviceInstances)) +func (r RestSubscribedURLsSynthesizer) Synthesize(subscribedURL *common.URL, serviceInstances []registry.ServiceInstance) []*common.URL { + urls := make([]*common.URL, len(serviceInstances), len(serviceInstances)) for i, s := range serviceInstances { splitHost := strings.Split(s.GetHost(), ":") u := common.NewURLWithOptions(common.WithProtocol(subscribedURL.Protocol), common.WithIp(splitHost[0]), @@ -55,7 +55,7 @@ func (r RestSubscribedURLsSynthesizer) Synthesize(subscribedURL *common.URL, ser common.WithParamsValue(constant.APPLICATION_KEY, s.GetServiceName()), common.WithParamsValue(constant.REGISTRY_KEY, "true"), ) - urls[i] = *u + urls[i] = u } return urls } diff --git a/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer_test.go b/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer_test.go index b52cc2323d6f9ae1bca8cfd1a4c5217af5e25f12..1bb38c92e32942fb1a39bbaeb9617013459bcdfe 100644 --- a/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer_test.go +++ b/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer_test.go @@ -56,7 +56,7 @@ func TestRestSubscribedURLsSynthesizer_Synthesize(t *testing.T) { }, } - var expectUrls []common.URL + var expectUrls []*common.URL u1 := common.NewURLWithOptions(common.WithProtocol("rest"), common.WithIp("127.0.0.1"), common.WithPort("80"), common.WithPath("org.apache.dubbo-go.mockService"), common.WithParams(url.Values{}), @@ -69,7 +69,7 @@ func TestRestSubscribedURLsSynthesizer_Synthesize(t *testing.T) { common.WithParamsValue(constant.SIDE_KEY, constant.PROVIDER_PROTOCOL), common.WithParamsValue(constant.APPLICATION_KEY, "test2"), common.WithParamsValue(constant.REGISTRY_KEY, "true")) - expectUrls = append(expectUrls, *u1, *u2) - result := syn.Synthesize(&subUrl, instances) + expectUrls = append(expectUrls, u1, u2) + result := syn.Synthesize(subUrl, instances) assert.Equal(t, expectUrls, result) } diff --git a/registry/servicediscovery/synthesizer/subscribed_urls_synthesizer.go b/registry/servicediscovery/synthesizer/subscribed_urls_synthesizer.go index 415ca35fbad2fa335d687dc7a7718fa3a4b2b487..557c86ec127fe88411fdbe9dd83d43ff8cd18cec 100644 --- a/registry/servicediscovery/synthesizer/subscribed_urls_synthesizer.go +++ b/registry/servicediscovery/synthesizer/subscribed_urls_synthesizer.go @@ -27,5 +27,5 @@ type SubscribedURLsSynthesizer interface { // Supports the synthesis of the subscribed url or not Support(subscribedURL *common.URL) bool // synthesize the subscribed url - Synthesize(subscribedURL *common.URL, serviceInstances []registry.ServiceInstance) []common.URL + Synthesize(subscribedURL *common.URL, serviceInstances []registry.ServiceInstance) []*common.URL } diff --git a/registry/zookeeper/listener.go b/registry/zookeeper/listener.go index ec82fa0309118fba4b5c21772d4dfd356f3b0c5c..3b8a51e4b356f3db6ebf9e1193a39f310c5200b5 100644 --- a/registry/zookeeper/listener.go +++ b/registry/zookeeper/listener.go @@ -158,7 +158,7 @@ func (l *RegistryConfigurationListener) Next() (*registry.ServiceEvent, error) { //r.update(e.res) //write to invoker //r.outerEventCh <- e.res - return ®istry.ServiceEvent{Action: e.ConfigType, Service: e.Value.(common.URL)}, nil + return ®istry.ServiceEvent{Action: e.ConfigType, Service: e.Value.(*common.URL)}, nil } } } diff --git a/registry/zookeeper/listener_test.go b/registry/zookeeper/listener_test.go index a0e9147a9e0ee8767efcf78d5e2aa536140f6a8b..20ec1cf69a65601e5dd8351083ce23edfb67d10c 100644 --- a/registry/zookeeper/listener_test.go +++ b/registry/zookeeper/listener_test.go @@ -34,7 +34,7 @@ import ( func Test_DataChange(t *testing.T) { listener := NewRegistryDataListener() url, _ := common.NewURL("jsonrpc%3A%2F%2F127.0.0.1%3A20001%2Fcom.ikurento.user.UserProvider%3Fanyhost%3Dtrue%26app.version%3D0.0.1%26application%3DBDTService%26category%3Dproviders%26cluster%3Dfailover%26dubbo%3Ddubbo-provider-golang-1.3.0%26environment%3Ddev%26group%3D%26interface%3Dcom.ikurento.user.UserProvider%26ip%3D10.32.20.124%26loadbalance%3Drandom%26methods.GetUser.loadbalance%3Drandom%26methods.GetUser.retries%3D1%26methods.GetUser.weight%3D0%26module%3Ddubbogo%2Buser-info%2Bserver%26name%3DBDTService%26organization%3Dikurento.com%26owner%3DZX%26pid%3D74500%26retries%3D0%26service.filter%3Decho%26side%3Dprovider%26timestamp%3D1560155407%26version%3D%26warmup%3D100") - listener.SubscribeURL(&url, &MockConfigurationListener{}) + listener.SubscribeURL(url, &MockConfigurationListener{}) int := listener.DataChange(remoting.Event{Path: "/dubbo/com.ikurento.user.UserProvider/providers/jsonrpc%3A%2F%2F127.0.0.1%3A20001%2Fcom.ikurento.user.UserProvider%3Fanyhost%3Dtrue%26app.version%3D0.0.1%26application%3DBDTService%26category%3Dproviders%26cluster%3Dfailover%26dubbo%3Ddubbo-provider-golang-1.3.0%26environment%3Ddev%26group%3D%26interface%3Dcom.ikurento.user.UserProvider%26ip%3D10.32.20.124%26loadbalance%3Drandom%26methods.GetUser.loadbalance%3Drandom%26methods.GetUser.retries%3D1%26methods.GetUser.weight%3D0%26module%3Ddubbogo%2Buser-info%2Bserver%26name%3DBDTService%26organization%3Dikurento.com%26owner%3DZX%26pid%3D74500%26retries%3D0%26service.filter%3Decho%26side%3Dprovider%26timestamp%3D1560155407%26version%3D%26warmup%3D100"}) assert.Equal(t, true, int) } diff --git a/registry/zookeeper/registry_test.go b/registry/zookeeper/registry_test.go index d915fc2ce10359f0dd1970daf019746ce066f511..e630db7e41092e48592bf99690f11863a23e23d3 100644 --- a/registry/zookeeper/registry_test.go +++ b/registry/zookeeper/registry_test.go @@ -37,7 +37,7 @@ func Test_Register(t *testing.T) { regurl, _ := common.NewURL("registry://127.0.0.1:1111", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER))) url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithParamsValue("serviceid", "soa.mock"), common.WithMethods([]string{"GetUser", "AddUser"})) - ts, reg, _ := newMockZkRegistry(®url) + ts, reg, _ := newMockZkRegistry(regurl) defer ts.Stop() err := reg.Register(url) children, _ := reg.client.GetChildren("/dubbo/com.ikurento.user.UserProvider/providers") @@ -50,7 +50,7 @@ func Test_UnRegister(t *testing.T) { regurl, _ := common.NewURL("registry://127.0.0.1:1111", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER))) url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithParamsValue("serviceid", "soa.mock"), common.WithMethods([]string{"GetUser", "AddUser"})) - ts, reg, _ := newMockZkRegistry(®url) + ts, reg, _ := newMockZkRegistry(regurl) defer ts.Stop() err := reg.Register(url) children, _ := reg.client.GetChildren("/dubbo/com.ikurento.user.UserProvider/providers") @@ -73,7 +73,7 @@ func Test_UnRegister(t *testing.T) { func Test_Subscribe(t *testing.T) { regurl, _ := common.NewURL("registry://127.0.0.1:1111", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER))) url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithMethods([]string{"GetUser", "AddUser"})) - ts, reg, _ := newMockZkRegistry(®url) + ts, reg, _ := newMockZkRegistry(regurl) //provider register err := reg.Register(url) @@ -85,10 +85,10 @@ func Test_Subscribe(t *testing.T) { //consumer register regurl.SetParam(constant.ROLE_KEY, strconv.Itoa(common.CONSUMER)) - _, reg2, _ := newMockZkRegistry(®url, zookeeper.WithTestCluster(ts)) + _, reg2, _ := newMockZkRegistry(regurl, zookeeper.WithTestCluster(ts)) reg2.Register(url) - listener, _ := reg2.DoSubscribe(&url) + listener, _ := reg2.DoSubscribe(url) serviceEvent, _ := listener.Next() assert.NoError(t, err) @@ -102,7 +102,7 @@ func Test_Subscribe(t *testing.T) { func Test_UnSubscribe(t *testing.T) { regurl, _ := common.NewURL("registry://127.0.0.1:1111", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER))) url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithMethods([]string{"GetUser", "AddUser"})) - ts, reg, _ := newMockZkRegistry(®url) + ts, reg, _ := newMockZkRegistry(regurl) //provider register err := reg.Register(url) @@ -114,10 +114,10 @@ func Test_UnSubscribe(t *testing.T) { //consumer register regurl.SetParam(constant.ROLE_KEY, strconv.Itoa(common.CONSUMER)) - _, reg2, _ := newMockZkRegistry(®url, zookeeper.WithTestCluster(ts)) + _, reg2, _ := newMockZkRegistry(regurl, zookeeper.WithTestCluster(ts)) reg2.Register(url) - listener, _ := reg2.DoSubscribe(&url) + listener, _ := reg2.DoSubscribe(url) serviceEvent, _ := listener.Next() assert.NoError(t, err) @@ -126,7 +126,7 @@ func Test_UnSubscribe(t *testing.T) { } assert.Regexp(t, ".*ServiceEvent{Action{add}.*", serviceEvent.String()) - reg2.UnSubscribe(&url, nil) + reg2.UnSubscribe(url, nil) assert.Nil(t, reg2.listener) defer ts.Stop() @@ -136,13 +136,13 @@ func Test_ConsumerDestory(t *testing.T) { regurl, _ := common.NewURL("registry://127.0.0.1:1111", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.CONSUMER))) url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithMethods([]string{"GetUser", "AddUser"})) - ts, reg, err := newMockZkRegistry(®url) + ts, reg, err := newMockZkRegistry(regurl) defer ts.Stop() assert.NoError(t, err) err = reg.Register(url) assert.NoError(t, err) - _, err = reg.DoSubscribe(&url) + _, err = reg.DoSubscribe(url) assert.NoError(t, err) //listener.Close() @@ -156,7 +156,7 @@ func Test_ProviderDestory(t *testing.T) { regurl, _ := common.NewURL("registry://127.0.0.1:1111", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER))) url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithMethods([]string{"GetUser", "AddUser"})) - ts, reg, err := newMockZkRegistry(®url) + ts, reg, err := newMockZkRegistry(regurl) defer ts.Stop() assert.NoError(t, err) diff --git a/registry/zookeeper/service_discovery.go b/registry/zookeeper/service_discovery.go index 5ad83ef90947afc0a5ca75af5009e8b55b4f6627..6d9582f33a7b2517c4edc96d00d00ad6b57a4835 100644 --- a/registry/zookeeper/service_discovery.go +++ b/registry/zookeeper/service_discovery.go @@ -154,8 +154,8 @@ func (zksd *zookeeperServiceDiscovery) RestartCallBack() bool { } // nolint -func (zksd *zookeeperServiceDiscovery) GetUrl() common.URL { - return *zksd.url +func (zksd *zookeeperServiceDiscovery) GetUrl() *common.URL { + return zksd.url } // nolint diff --git a/remoting/etcdv3/listener.go b/remoting/etcdv3/listener.go index 4f80a89dfb713036a5d4d812bc7a2d5551f42284..c66928a6367cb2449de79a51b59d122a74a79911 100644 --- a/remoting/etcdv3/listener.go +++ b/remoting/etcdv3/listener.go @@ -129,8 +129,6 @@ func (l *EventListener) handleEvents(event *clientv3.Event, listeners ...remotin default: return false } - - panic("unreachable") } // ListenServiceNodeEventWithPrefix listens on a set of key with spec prefix diff --git a/remoting/exchange_client.go b/remoting/exchange_client.go index ef0c3dbce7372b7446731613dba54771f46e5183..b3423eb679c438c991c0ccbd0b0a0ba02ae55ae8 100644 --- a/remoting/exchange_client.go +++ b/remoting/exchange_client.go @@ -42,7 +42,7 @@ type Client interface { // responseHandler is used to deal with msg SetResponseHandler(responseHandler ResponseHandler) // connect url - Connect(url common.URL) error + Connect(url *common.URL) error // close Close() // send request to server. @@ -69,7 +69,7 @@ type ResponseHandler interface { } // create ExchangeClient -func NewExchangeClient(url common.URL, client Client, connectTimeout time.Duration, lazyInit bool) *ExchangeClient { +func NewExchangeClient(url *common.URL, client Client, connectTimeout time.Duration, lazyInit bool) *ExchangeClient { exchangeClient := &ExchangeClient{ ConnectTimeout: connectTimeout, address: url.Location, @@ -86,7 +86,7 @@ func NewExchangeClient(url common.URL, client Client, connectTimeout time.Durati return exchangeClient } -func (cl *ExchangeClient) doInit(url common.URL) error { +func (cl *ExchangeClient) doInit(url *common.URL) error { if cl.init { return nil } @@ -104,7 +104,7 @@ func (cl *ExchangeClient) doInit(url common.URL) error { } // two way request -func (client *ExchangeClient) Request(invocation *protocol.Invocation, url common.URL, timeout time.Duration, +func (client *ExchangeClient) Request(invocation *protocol.Invocation, url *common.URL, timeout time.Duration, result *protocol.RPCResult) error { if er := client.doInit(url); er != nil { return er @@ -134,7 +134,7 @@ func (client *ExchangeClient) Request(invocation *protocol.Invocation, url commo } // async two way request -func (client *ExchangeClient) AsyncRequest(invocation *protocol.Invocation, url common.URL, timeout time.Duration, +func (client *ExchangeClient) AsyncRequest(invocation *protocol.Invocation, url *common.URL, timeout time.Duration, callback common.AsyncCallback, result *protocol.RPCResult) error { if er := client.doInit(url); er != nil { return er @@ -160,7 +160,7 @@ func (client *ExchangeClient) AsyncRequest(invocation *protocol.Invocation, url } // oneway request -func (client *ExchangeClient) Send(invocation *protocol.Invocation, url common.URL, timeout time.Duration) error { +func (client *ExchangeClient) Send(invocation *protocol.Invocation, url *common.URL, timeout time.Duration) error { if er := client.doInit(url); er != nil { return er } diff --git a/remoting/exchange_server.go b/remoting/exchange_server.go index a31e994d7411df2da94c210a1b3d4b24aae9fcba..a8d7c73f305a42e0402861817e5dbe2abfcfdd01 100644 --- a/remoting/exchange_server.go +++ b/remoting/exchange_server.go @@ -32,11 +32,11 @@ type Server interface { // This is abstraction level. it is like facade. type ExchangeServer struct { Server Server - Url common.URL + Url *common.URL } // Create ExchangeServer -func NewExchangeServer(url common.URL, server Server) *ExchangeServer { +func NewExchangeServer(url *common.URL, server Server) *ExchangeServer { exchangServer := &ExchangeServer{ Server: server, Url: url, diff --git a/remoting/getty/dubbo_codec_for_test.go b/remoting/getty/dubbo_codec_for_test.go index b91fc9f4ccf69299870f9daf3707521d913cd4c0..fca5da89643adee2f5e6c1e8dca8ec3da4c987e4 100644 --- a/remoting/getty/dubbo_codec_for_test.go +++ b/remoting/getty/dubbo_codec_for_test.go @@ -55,15 +55,15 @@ func (c *DubboTestCodec) EncodeRequest(request *remoting.Request) (*bytes.Buffer if !ok { return nil, perrors.Errorf("encode request failed for parameter type :%+v", request) } - invocation := *invoc + tmpInvocation := invoc svc := impl.Service{} - svc.Path = invocation.AttachmentsByKey(constant.PATH_KEY, "") - svc.Interface = invocation.AttachmentsByKey(constant.INTERFACE_KEY, "") - svc.Version = invocation.AttachmentsByKey(constant.VERSION_KEY, "") - svc.Group = invocation.AttachmentsByKey(constant.GROUP_KEY, "") - svc.Method = invocation.MethodName() - timeout, err := strconv.Atoi(invocation.AttachmentsByKey(constant.TIMEOUT_KEY, strconv.Itoa(constant.DEFAULT_REMOTING_TIMEOUT))) + svc.Path = tmpInvocation.AttachmentsByKey(constant.PATH_KEY, "") + svc.Interface = tmpInvocation.AttachmentsByKey(constant.INTERFACE_KEY, "") + svc.Version = tmpInvocation.AttachmentsByKey(constant.VERSION_KEY, "") + svc.Group = tmpInvocation.AttachmentsByKey(constant.GROUP_KEY, "") + svc.Method = tmpInvocation.MethodName() + timeout, err := strconv.Atoi(tmpInvocation.AttachmentsByKey(constant.TIMEOUT_KEY, strconv.Itoa(constant.DEFAULT_REMOTING_TIMEOUT))) if err != nil { // it will be wrapped in readwrite.Write . return nil, perrors.WithStack(err) @@ -71,7 +71,7 @@ func (c *DubboTestCodec) EncodeRequest(request *remoting.Request) (*bytes.Buffer svc.Timeout = time.Duration(timeout) header := impl.DubboHeader{} - serialization := invocation.AttachmentsByKey(constant.SERIALIZATION_KEY, constant.HESSIAN2_SERIALIZATION) + serialization := tmpInvocation.AttachmentsByKey(constant.SERIALIZATION_KEY, constant.HESSIAN2_SERIALIZATION) if serialization == constant.PROTOBUF_SERIALIZATION { header.SerialID = constant.S_Proto } else { @@ -87,7 +87,7 @@ func (c *DubboTestCodec) EncodeRequest(request *remoting.Request) (*bytes.Buffer pkg := &impl.DubboPackage{ Header: header, Service: svc, - Body: impl.NewRequestPayload(invocation.Arguments(), invocation.Attachments()), + Body: impl.NewRequestPayload(tmpInvocation.Arguments(), tmpInvocation.Attachments()), Err: nil, Codec: impl.NewDubboCodec(nil), } diff --git a/remoting/getty/getty_client.go b/remoting/getty/getty_client.go index 7edc1cf8c59f86a3f89c623b4ed02b6b0a0495ec..d4d20d9d8fba226194b1aacb0d96aed0b9a82e59 100644 --- a/remoting/getty/getty_client.go +++ b/remoting/getty/getty_client.go @@ -151,7 +151,7 @@ func (c *Client) SetResponseHandler(responseHandler remoting.ResponseHandler) { } // init client and try to connection. -func (c *Client) Connect(url common.URL) error { +func (c *Client) Connect(url *common.URL) error { initClient(url.Protocol) c.conf = *clientConf // new client diff --git a/remoting/getty/getty_client_test.go b/remoting/getty/getty_client_test.go index 41ca3108a8a8d578c6aaaf374dc9f5fa6300a8b0..6b8e3ec2834b6eb80a49ce296c8c8876b68fdd23 100644 --- a/remoting/getty/getty_client_test.go +++ b/remoting/getty/getty_client_test.go @@ -51,7 +51,7 @@ func TestRunSuite(t *testing.T) { svr.Stop() } -func testRequestOneWay(t *testing.T, svr *Server, url common.URL, client *Client) { +func testRequestOneWay(t *testing.T, svr *Server, url *common.URL, client *Client) { request := remoting.NewRequest("2.0.2") up := &UserProvider{} @@ -80,7 +80,7 @@ func setAttachment(invocation *invocation.RPCInvocation, attachments map[string] } } -func getClient(url common.URL) *Client { +func getClient(url *common.URL) *Client { client := NewClient(Options{ ConnectTimeout: config.GetConsumerConfig().ConnectTimeout, }) @@ -92,7 +92,7 @@ func getClient(url common.URL) *Client { return client } -func testClient_Call(t *testing.T, svr *Server, url common.URL, c *Client) { +func testClient_Call(t *testing.T, svr *Server, url *common.URL, c *Client) { c.pool = newGettyRPCClientConnPool(c, clientConf.PoolSize, time.Duration(int(time.Second)*clientConf.PoolTTL)) testGetBigPkg(t, c) @@ -309,7 +309,7 @@ func testGetUser61(t *testing.T, c *Client) { assert.Equal(t, User{Id: "1", Name: ""}, *user) } -func testClient_AsyncCall(t *testing.T, svr *Server, url common.URL, client *Client) { +func testClient_AsyncCall(t *testing.T, svr *Server, url *common.URL, client *Client) { user := &User{} lock := sync.Mutex{} request := remoting.NewRequest("2.0.2") @@ -337,7 +337,7 @@ func testClient_AsyncCall(t *testing.T, svr *Server, url common.URL, client *Cli time.Sleep(1 * time.Second) } -func InitTest(t *testing.T) (*Server, common.URL) { +func InitTest(t *testing.T) (*Server, *common.URL) { hessian.RegisterPOJO(&User{}) remoting.RegistryCodec("dubbo", &DubboTestCodec{}) diff --git a/remoting/getty/getty_server.go b/remoting/getty/getty_server.go index 7c8fa29a622b4b746801d1d2ce878f8b353c1a76..ab574ec4dd3139cf83a82ad80d87f34127d666c3 100644 --- a/remoting/getty/getty_server.go +++ b/remoting/getty/getty_server.go @@ -117,7 +117,7 @@ type Server struct { } // NewServer create a new Server -func NewServer(url common.URL, handlers func(*invocation.RPCInvocation) protocol.RPCResult) *Server { +func NewServer(url *common.URL, handlers func(*invocation.RPCInvocation) protocol.RPCResult) *Server { //init initServer(url.Protocol) diff --git a/remoting/getty/listener.go b/remoting/getty/listener.go index 97c9e7ba3e6dd2b807f4301a1519ac5b7190d2ab..d4819a16e22be475efd4e3afb9c71aa02e27f0e0 100644 --- a/remoting/getty/listener.go +++ b/remoting/getty/listener.go @@ -274,7 +274,6 @@ func (h *RpcServerHandler) OnMessage(session getty.Session, pkg interface{}) { invoc, ok := req.Data.(*invocation.RPCInvocation) if !ok { panic("create invocation occur some exception for the type is not suitable one.") - return } attachments := invoc.Attachments() attachments[constant.LOCAL_ADDR] = session.LocalAddr() diff --git a/remoting/kubernetes/client.go b/remoting/kubernetes/client.go index 0a0548959a3e6d839321d03a627bb6aba66d8474..fce9e80eb88b73cfbe96a4aaebeb106a902fe41d 100644 --- a/remoting/kubernetes/client.go +++ b/remoting/kubernetes/client.go @@ -47,7 +47,7 @@ type Client struct { } // newClient returns Client instance for registry -func newClient(url common.URL) (*Client, error) { +func newClient(url *common.URL) (*Client, error) { ctx, cancel := context.WithCancel(context.Background()) diff --git a/remoting/kubernetes/facade_test.go b/remoting/kubernetes/facade_test.go index 65c5d715a38bd0862245255e0276ff5e959de3a3..00e2e1171c54c2b07973b66cb96cf64e67683f00 100644 --- a/remoting/kubernetes/facade_test.go +++ b/remoting/kubernetes/facade_test.go @@ -43,8 +43,8 @@ func (r *mockFacade) SetClient(client *Client) { r.client = client } -func (r *mockFacade) GetUrl() common.URL { - return *r.URL +func (r *mockFacade) GetUrl() *common.URL { + return r.URL } func (r *mockFacade) Destroy() { @@ -68,7 +68,7 @@ func Test_Facade(t *testing.T) { mockClient := getTestClient(t) m := &mockFacade{ - URL: ®Url, + URL: regUrl, client: mockClient, } diff --git a/remoting/zookeeper/facade.go b/remoting/zookeeper/facade.go index 2a034390c016864f95303b12b6c56533771075f3..4dc0a549f2ae53edcc7a645de4dfffc8b9da00a0 100644 --- a/remoting/zookeeper/facade.go +++ b/remoting/zookeeper/facade.go @@ -37,7 +37,7 @@ type ZkClientFacade interface { WaitGroup() *sync.WaitGroup // for wait group control, zk client listener & zk client container Done() chan struct{} // for zk client control RestartCallBack() bool - GetUrl() common.URL + GetUrl() *common.URL } // HandleClientRestart keeps the connection between client and server diff --git a/remoting/zookeeper/facade_test.go b/remoting/zookeeper/facade_test.go index 1cd8f064bb15a2ac48b0d62154309b27c55ab946..3d5798c947fb0fb33adce708e1bcdb8fb24e530f 100644 --- a/remoting/zookeeper/facade_test.go +++ b/remoting/zookeeper/facade_test.go @@ -68,8 +68,8 @@ func (r *mockFacade) Done() chan struct{} { return r.done } -func (r *mockFacade) GetUrl() common.URL { - return *r.URL +func (r *mockFacade) GetUrl() *common.URL { + return r.URL } func (r *mockFacade) Destroy() { @@ -90,7 +90,7 @@ func Test_Facade(t *testing.T) { assert.NoError(t, err) defer ts.Stop() url, _ := common.NewURL("mock://127.0.0.1") - mock := newMockFacade(z, &url) + mock := newMockFacade(z, url) go HandleClientRestart(mock) states := []zk.State{zk.StateConnecting, zk.StateConnected, zk.StateHasSession} verifyEventStateOrder(t, event, states, "event channel")