diff --git a/.gitignore b/.gitignore index b76e94a1d6..f369c2833a 100644 --- a/.gitignore +++ b/.gitignore @@ -29,4 +29,4 @@ coverage.txt # unit test remoting/zookeeper/zookeeper-4unittest/ config_center/zookeeper/zookeeper-4unittest/ -registry/zookeeper/zookeeper-4unittest/ \ No newline at end of file +registry/zookeeper/zookeeper-4unittest/ diff --git a/README.md b/README.md index 36e0ad78c3..c5ad2f3a56 100644 --- a/README.md +++ b/README.md @@ -34,13 +34,13 @@ Finished List: - Configure Center: Zookeeper - Cluster Strategy: Failover/[Failfast](https://github.com/apache/dubbo-go/pull/140)/[Failsafe/Failback](https://github.com/apache/dubbo-go/pull/136)/[Available](https://github.com/apache/dubbo-go/pull/155)/[Broadcast](https://github.com/apache/dubbo-go/pull/158)/[Forking](https://github.com/apache/dubbo-go/pull/161) - Load Balance: Random/[RoundRobin](https://github.com/apache/dubbo-go/pull/66)/[LeastActive](https://github.com/apache/dubbo-go/pull/65) -- Filter: Echo Health Check/[Circuit break and service downgrade](https://github.com/apache/dubbo-go/pull/133) +- Filter: Echo Health Check/[Circuit break and service downgrade](https://github.com/apache/dubbo-go/pull/133)/[TokenFilter](https://github.com/apache/dubbo-go/pull/202) - Other feature: [generic invoke](https://github.com/apache/dubbo-go/pull/122)/start check/connecting certain provider/multi-protocols/multi-registries/multi-versions/service group Working List: - Load Balance: ConsistentHash -- Filter: TokenFilter/AccessLogFilter/CountFilter/ExecuteLimitFilter/TpsLimitFilter +- Filter: AccessLogFilter/CountFilter/ExecuteLimitFilter/TpsLimitFilter - Registry: k8s - Configure Center: apollo - Dynamic Configuration Center & Metadata Center (dubbo v2.7.x) diff --git a/README_CN.md b/README_CN.md index 387070d267..266d1d0e92 100644 --- a/README_CN.md +++ b/README_CN.md @@ -33,14 +33,14 @@ Apache License, Version 2.0 - 配置中心: Zookeeper - 集群策略: Failover/[Failfast](https://github.com/apache/dubbo-go/pull/140)/[Failsafe/Failback](https://github.com/apache/dubbo-go/pull/136)/[Available](https://github.com/apache/dubbo-go/pull/155)/[Broadcast](https://github.com/apache/dubbo-go/pull/158)/[Forking](https://github.com/apache/dubbo-go/pull/161) - 负载均衡策略: Random/[RoundRobin](https://github.com/apache/dubbo-go/pull/66)/[LeastActive](https://github.com/apache/dubbo-go/pull/65) -- 过滤器: Echo Health Check/[服务熔断&降级](https://github.com/apache/dubbo-go/pull/133) +- 过滤器: Echo Health Check/[服务熔断&降级](https://github.com/apache/dubbo-go/pull/133)/[TokenFilter](https://github.com/apache/dubbo-go/pull/202) - 其他功能支持: [泛化调用](https://github.com/apache/dubbo-go/pull/122)/启动时检查/服务直连/多服务协议/多注册中心/多服务版本/服务分组 开发中列表: - 集群策略: Forking - 负载均衡策略: ConsistentHash -- 过滤器: TokenFilter/AccessLogFilter/CountFilter/ExecuteLimitFilter/TpsLimitFilter +- 过滤器: AccessLogFilter/CountFilter/ExecuteLimitFilter/TpsLimitFilter - 注册中心: k8s - 配置中心: apollo - 动态配置中心 & 元数据中心 (dubbo v2.7.x) diff --git a/before_ut.sh b/before_ut.sh new file mode 100644 index 0000000000..7acee76ce5 --- /dev/null +++ b/before_ut.sh @@ -0,0 +1,4 @@ +mkdir -p remoting/zookeeper/zookeeper-4unittest/contrib/fatjar config_center/zookeeper/zookeeper-4unittest/contrib/fatjar registry/zookeeper/zookeeper-4unittest/contrib/fatjar +wget -P "remoting/zookeeper/zookeeper-4unittest/contrib/fatjar" https://github.com/dubbogo/resources/raw/master/zookeeper-4unitest/contrib/fatjar/zookeeper-3.4.9-fatjar.jar +cp remoting/zookeeper/zookeeper-4unittest/contrib/fatjar/zookeeper-3.4.9-fatjar.jar config_center/zookeeper/zookeeper-4unittest/contrib/fatjar/ +cp remoting/zookeeper/zookeeper-4unittest/contrib/fatjar/zookeeper-3.4.9-fatjar.jar registry/zookeeper/zookeeper-4unittest/contrib/fatjar/ \ No newline at end of file diff --git a/cluster/directory/base_directory.go b/cluster/directory/base_directory.go index b201197714..1d59b51cc3 100644 --- a/cluster/directory/base_directory.go +++ b/cluster/directory/base_directory.go @@ -42,6 +42,9 @@ func NewBaseDirectory(url *common.URL) BaseDirectory { func (dir *BaseDirectory) GetUrl() common.URL { return *dir.url } +func (dir *BaseDirectory) GetDirectoryUrl() *common.URL { + return dir.url +} func (dir *BaseDirectory) Destroy(doDestroy func()) { if dir.destroyed.CAS(false, true) { diff --git a/common/config/environment.go b/common/config/environment.go index 8709d69a78..931f046091 100644 --- a/common/config/environment.go +++ b/common/config/environment.go @@ -23,15 +23,21 @@ import ( "sync" ) +import ( + "github.com/apache/dubbo-go/config_center" +) + // There is dubbo.properties file and application level config center configuration which higner than normal config center in java. So in java the // configuration sequence will be config center > application level config center > dubbo.properties > spring bean configuration. // But in go, neither the dubbo.properties file or application level config center configuration will not support for the time being. // We just have config center configuration which can override configuration in consumer.yaml & provider.yaml. // But for add these features in future ,I finish the environment struct following Environment class in java. type Environment struct { - configCenterFirst bool - externalConfigs sync.Map - externalConfigMap sync.Map + configCenterFirst bool + externalConfigs sync.Map + externalConfigMap sync.Map + appExternalConfigMap sync.Map + dynamicConfiguration config_center.DynamicConfiguration } var ( @@ -45,6 +51,9 @@ func GetEnvInstance() *Environment { }) return instance } +func NewEnvInstance() { + instance = &Environment{configCenterFirst: true} +} //func (env *Environment) SetConfigCenterFirst() { // env.configCenterFirst = true @@ -60,23 +69,34 @@ func (env *Environment) UpdateExternalConfigMap(externalMap map[string]string) { } } +func (env *Environment) UpdateAppExternalConfigMap(externalMap map[string]string) { + for k, v := range externalMap { + env.appExternalConfigMap.Store(k, v) + } +} + func (env *Environment) Configuration() *list.List { list := list.New() - memConf := newInmemoryConfiguration() - memConf.setProperties(&(env.externalConfigMap)) - list.PushBack(memConf) + // The sequence would be: SystemConfiguration -> ExternalConfiguration -> AppExternalConfiguration -> AbstractConfig -> PropertiesConfiguration + list.PushFront(newInmemoryConfiguration(&(env.externalConfigMap))) + list.PushFront(newInmemoryConfiguration(&(env.appExternalConfigMap))) return list } +func (env *Environment) SetDynamicConfiguration(dc config_center.DynamicConfiguration) { + env.dynamicConfiguration = dc +} + +func (env *Environment) GetDynamicConfiguration() config_center.DynamicConfiguration { + return env.dynamicConfiguration +} + type InmemoryConfiguration struct { store *sync.Map } -func newInmemoryConfiguration() *InmemoryConfiguration { - return &InmemoryConfiguration{} -} -func (conf *InmemoryConfiguration) setProperties(p *sync.Map) { - conf.store = p +func newInmemoryConfiguration(p *sync.Map) *InmemoryConfiguration { + return &InmemoryConfiguration{store: p} } func (conf *InmemoryConfiguration) GetProperty(key string) (bool, string) { diff --git a/common/config/environment_test.go b/common/config/environment_test.go index ab7cafae89..2d84dc4ae3 100644 --- a/common/config/environment_test.go +++ b/common/config/environment_test.go @@ -19,6 +19,7 @@ package config import ( "testing" ) + import ( "github.com/stretchr/testify/assert" ) @@ -38,7 +39,7 @@ func TestEnvironment_UpdateExternalConfigMap(t *testing.T) { func TestEnvironment_ConfigurationAndGetProperty(t *testing.T) { GetEnvInstance().UpdateExternalConfigMap(map[string]string{"1": "2"}) list := GetEnvInstance().Configuration() - ok, v := list.Front().Value.(*InmemoryConfiguration).GetProperty("1") + ok, v := list.Back().Value.(*InmemoryConfiguration).GetProperty("1") assert.True(t, ok) assert.Equal(t, "2", v) } diff --git a/common/constant/default.go b/common/constant/default.go index 541ed1d330..405920e20f 100644 --- a/common/constant/default.go +++ b/common/constant/default.go @@ -18,8 +18,14 @@ package constant const ( - DUBBO = "dubbo" + DUBBO = "dubbo" + PROVIDER_PROTOCOL = "provider" + //compatible with 2.6.x + OVERRIDE_PROTOCOL = "override" + EMPTY_PROTOCOL = "empty" + ROUTER_PROTOCOL = "router" ) + const ( DEFAULT_WEIGHT = 100 // DEFAULT_WARMUP = 10 * 60 // in java here is 10*60*1000 because of System.currentTimeMillis() is measured in milliseconds & in go time.Unix() is second @@ -40,7 +46,7 @@ const ( const ( DEFAULT_KEY = "default" PREFIX_DEFAULT_KEY = "default." - DEFAULT_SERVICE_FILTERS = "echo" + DEFAULT_SERVICE_FILTERS = "echo,token" DEFAULT_REFERENCE_FILTERS = "" GENERIC_REFERENCE_FILTERS = "generic" GENERIC = "$invoke" @@ -48,5 +54,16 @@ const ( ) const ( - ANY_VALUE = "*" + ANY_VALUE = "*" + ANYHOST_VALUE = "0.0.0.0" + REMOVE_VALUE_PREFIX = "-" +) + +const ( + CONFIGURATORS_CATEGORY = "configurators" + ROUTER_CATEGORY = "category" + DEFAULT_CATEGORY = PROVIDER_CATEGORY + DYNAMIC_CONFIGURATORS_CATEGORY = "dynamicconfigurators" + APP_DYNAMIC_CONFIGURATORS_CATEGORY = "appdynamicconfigurators" + PROVIDER_CATEGORY = "providers" ) diff --git a/common/constant/env.go b/common/constant/env.go index f0e4fabe02..759cb0be0a 100644 --- a/common/constant/env.go +++ b/common/constant/env.go @@ -18,7 +18,7 @@ package constant const ( - CONF_CONSUMER_FILE_PATH = "CONF_CONSUMER_FILE_PATH" - CONF_PROVIDER_FILE_PATH = "CONF_PROVIDER_FILE_PATH" - APP_LOG_CONF_FILE string = "APP_LOG_CONF_FILE" + CONF_CONSUMER_FILE_PATH = "CONF_CONSUMER_FILE_PATH" + CONF_PROVIDER_FILE_PATH = "CONF_PROVIDER_FILE_PATH" + APP_LOG_CONF_FILE = "APP_LOG_CONF_FILE" ) diff --git a/common/constant/key.go b/common/constant/key.go index ed60c24b63..abb78c987b 100644 --- a/common/constant/key.go +++ b/common/constant/key.go @@ -22,15 +22,22 @@ const ( ) const ( - GROUP_KEY = "group" - VERSION_KEY = "version" - INTERFACE_KEY = "interface" - PATH_KEY = "path" - SERVICE_KEY = "service" - METHODS_KEY = "methods" - TIMEOUT_KEY = "timeout" - BEAN_NAME_KEY = "bean.name" - GENERIC_KEY = "generic" + GROUP_KEY = "group" + VERSION_KEY = "version" + INTERFACE_KEY = "interface" + PATH_KEY = "path" + SERVICE_KEY = "service" + METHODS_KEY = "methods" + TIMEOUT_KEY = "timeout" + CATEGORY_KEY = "category" + CHECK_KEY = "check" + ENABLED_KEY = "enabled" + SIDE_KEY = "side" + OVERRIDE_PROVIDERS_KEY = "providerAddresses" + BEAN_NAME_KEY = "bean.name" + GENERIC_KEY = "generic" + CLASSIFIER_KEY = "classifier" + TOKEN_KEY = "token" ) const ( @@ -79,16 +86,23 @@ const ( ) const ( - CONFIG_NAMESPACE_KEY = "config.namespace" - CONFIG_TIMEOUT_KET = "config.timeout" + CONFIG_NAMESPACE_KEY = "config.namespace" + CONFIG_TIMEOUT_KET = "config.timeout" + CONFIG_VERSION_KEY = "configVersion" + COMPATIBLE_CONFIG_KEY = "compatible_config" ) const ( - RegistryConfigPrefix = "dubbo.registries." - ReferenceConfigPrefix = "dubbo.reference." - ServiceConfigPrefix = "dubbo.service." - ProtocolConfigPrefix = "dubbo.protocols." - ProviderConfigPrefix = "dubbo.provider." - ConsumerConfigPrefix = "dubbo.consumer." + RegistryConfigPrefix = "dubbo.registries." + SingleRegistryConfigPrefix = "dubbo.registry." + ReferenceConfigPrefix = "dubbo.reference." + ServiceConfigPrefix = "dubbo.service." + ProtocolConfigPrefix = "dubbo.protocols." + ProviderConfigPrefix = "dubbo.provider." + ConsumerConfigPrefix = "dubbo.consumer." +) + +const ( + CONFIGURATORS_SUFFIX = ".configurators" ) const ( diff --git a/common/extension/configurator.go b/common/extension/configurator.go new file mode 100644 index 0000000000..40d134f474 --- /dev/null +++ b/common/extension/configurator.go @@ -0,0 +1,60 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package extension + +import ( + "github.com/apache/dubbo-go/common" + "github.com/apache/dubbo-go/config_center" +) + +const DefaultKey = "default" + +type getConfiguratorFunc func(url *common.URL) config_center.Configurator + +var ( + configurator = make(map[string]getConfiguratorFunc) +) + +func SetConfigurator(name string, v getConfiguratorFunc) { + configurator[name] = v +} + +func GetConfigurator(name string, url *common.URL) config_center.Configurator { + if configurator[name] == nil { + panic("configurator for " + name + " is not existing, make sure you have import the package.") + } + return configurator[name](url) + +} +func SetDefaultConfigurator(v getConfiguratorFunc) { + configurator[DefaultKey] = v +} + +func GetDefaultConfigurator(url *common.URL) config_center.Configurator { + if configurator[DefaultKey] == nil { + panic("configurator for default is not existing, make sure you have import the package.") + } + return configurator[DefaultKey](url) + +} +func GetDefaultConfiguratorFunc() getConfiguratorFunc { + if configurator[DefaultKey] == nil { + panic("configurator for default is not existing, make sure you have import the package.") + } + return configurator[DefaultKey] +} diff --git a/common/url.go b/common/url.go index 7c3f7e056c..bf58ca188c 100644 --- a/common/url.go +++ b/common/url.go @@ -31,7 +31,10 @@ import ( ) import ( + "github.com/dubbogo/gost/container" + "github.com/jinzhu/copier" perrors "github.com/pkg/errors" + "github.com/satori/go.uuid" ) import ( @@ -148,6 +151,18 @@ func WithLocation(location string) option { } } +func WithToken(token string) option { + return func(url *URL) { + if len(token) > 0 { + value := token + if strings.ToLower(token) == "true" || strings.ToLower(token) == "default" { + value = uuid.NewV4().String() + } + url.SetParam(constant.TOKEN_KEY, value) + } + } +} + func NewURLWithOptions(opts ...option) *URL { url := &URL{} for _, opt := range opts { @@ -230,13 +245,37 @@ func (c URL) URLEqual(url URL) bool { if cKey != urlKey { return false } + if url.GetParam(constant.ENABLED_KEY, "true") != "true" && url.GetParam(constant.ENABLED_KEY, "") != constant.ANY_VALUE { + return false + } + //TODO :may need add interface key any value condition + if !isMatchCategory(url.GetParam(constant.CATEGORY_KEY, constant.DEFAULT_CATEGORY), c.GetParam(constant.CATEGORY_KEY, constant.DEFAULT_CATEGORY)) { + return false + } return true } - +func isMatchCategory(category1 string, category2 string) bool { + if len(category2) == 0 { + return category1 == constant.DEFAULT_CATEGORY + } else if strings.Contains(category2, constant.ANY_VALUE) { + return true + } else if strings.Contains(category2, constant.REMOVE_VALUE_PREFIX) { + return !strings.Contains(category2, constant.REMOVE_VALUE_PREFIX+category1) + } else { + return strings.Contains(category2, category1) + } +} func (c URL) String() string { - buildString := fmt.Sprintf( - "%s://%s:%s@%s:%s%s?", - c.Protocol, c.Username, c.Password, c.Ip, c.Port, c.Path) + var buildString string + if len(c.Username) == 0 && len(c.Password) == 0 { + buildString = fmt.Sprintf( + "%s://%s:%s%s?", + c.Protocol, c.Ip, c.Port, c.Path) + } else { + buildString = fmt.Sprintf( + "%s://%s:%s@%s:%s%s?", + c.Protocol, c.Username, c.Password, c.Ip, c.Port, c.Path) + } c.paramsLock.RLock() buildString += c.params.Encode() c.paramsLock.RUnlock() @@ -274,6 +313,11 @@ func (c URL) ServiceKey() string { return buf.String() } +func (c *URL) EncodedServiceKey() string { + serviceKey := c.ServiceKey() + return strings.Replace(serviceKey, "/", "*", 1) +} + func (c URL) Context() context.Context { return c.ctx } @@ -322,6 +366,11 @@ func (c URL) GetParam(s string, d string) string { c.paramsLock.RUnlock() return r } + +func (c URL) GetParams() url.Values { + return c.params +} + func (c URL) GetParamAndDecoded(key string) (string, error) { c.paramsLock.RLock() defer c.paramsLock.RUnlock() @@ -398,6 +447,21 @@ func (c URL) GetMethodParam(method string, key string, d string) string { return r } +func (c *URL) RemoveParams(set *container.HashSet) { + c.paramsLock.Lock() + defer c.paramsLock.Unlock() + for k := range set.Items { + s := k.(string) + delete(c.params, s) + } +} + +func (c *URL) SetParams(m url.Values) { + for k := range m { + c.SetParam(k, m.Get(k)) + } +} + // ToMap transfer URL to Map func (c URL) ToMap() map[string]string { @@ -442,8 +506,9 @@ func (c URL) ToMap() map[string]string { // configuration > reference config >service config // in this function we should merge the reference local url config into the service url from registry. //TODO configuration merge, in the future , the configuration center's config should merge too. -func MergeUrl(serviceUrl URL, referenceUrl *URL) URL { - mergedUrl := serviceUrl + +func MergeUrl(serviceUrl *URL, referenceUrl *URL) *URL { + mergedUrl := serviceUrl.Clone() //iterator the referenceUrl if serviceUrl not have the key ,merge in referenceUrl.RangeParams(func(key, value string) bool { @@ -470,8 +535,18 @@ func MergeUrl(serviceUrl URL, referenceUrl *URL) URL { return mergedUrl } +func (c *URL) Clone() *URL { + newUrl := &URL{} + copier.Copy(newUrl, c) + newUrl.params = url.Values{} + c.RangeParams(func(key, value string) bool { + newUrl.SetParam(key, value) + return true + }) + return newUrl +} -func mergeNormalParam(mergedUrl URL, referenceUrl *URL, paramKeys []string) []func(method string) { +func mergeNormalParam(mergedUrl *URL, referenceUrl *URL, paramKeys []string) []func(method string) { var methodConfigMergeFcn = []func(method string){} for _, paramKey := range paramKeys { if v := referenceUrl.GetParam(paramKey, ""); len(v) > 0 { diff --git a/common/url_test.go b/common/url_test.go index 4b7d9376a4..41fd374a4d 100644 --- a/common/url_test.go +++ b/common/url_test.go @@ -56,7 +56,7 @@ func TestNewURLWithOptions(t *testing.T) { } func TestURL(t *testing.T) { - u, err := NewURL(context.TODO(), "dubbo://:@127.0.0.1:20000/com.ikurento.user.UserProvider?anyhost=true&"+ + u, err := NewURL(context.TODO(), "dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?anyhost=true&"+ "application=BDTService&category=providers&default.timeout=10000&dubbo=dubbo-provider-golang-1.0.0&"+ "environment=dev&interface=com.ikurento.user.UserProvider&ip=192.168.56.1&methods=GetUser%2C&"+ "module=dubbogo+user-info+server&org=ikurento.com&owner=ZX&pid=1447&revision=0.0.1&"+ @@ -76,14 +76,14 @@ func TestURL(t *testing.T) { "2C&module=dubbogo+user-info+server&org=ikurento.com&owner=ZX&pid=1447&revision=0.0.1&side=provider&timeout=3000&t"+ "imestamp=1556509797245", u.params.Encode()) - assert.Equal(t, "dubbo://:@127.0.0.1:20000/com.ikurento.user.UserProvider?anyhost=true&application=BDTServi"+ + assert.Equal(t, "dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?anyhost=true&application=BDTServi"+ "ce&category=providers&default.timeout=10000&dubbo=dubbo-provider-golang-1.0.0&environment=dev&interface=com.ikure"+ "nto.user.UserProvider&ip=192.168.56.1&methods=GetUser%2C&module=dubbogo+user-info+server&org=ikurento.com&owner="+ "ZX&pid=1447&revision=0.0.1&side=provider&timeout=3000×tamp=1556509797245", u.String()) } func TestURLWithoutSchema(t *testing.T) { - u, err := NewURL(context.TODO(), "@127.0.0.1:20000/com.ikurento.user.UserProvider?anyhost=true&"+ + u, err := NewURL(context.TODO(), "127.0.0.1:20000/com.ikurento.user.UserProvider?anyhost=true&"+ "application=BDTService&category=providers&default.timeout=10000&dubbo=dubbo-provider-golang-1.0.0&"+ "environment=dev&interface=com.ikurento.user.UserProvider&ip=192.168.56.1&methods=GetUser%2C&"+ "module=dubbogo+user-info+server&org=ikurento.com&owner=ZX&pid=1447&revision=0.0.1&"+ @@ -103,20 +103,20 @@ func TestURLWithoutSchema(t *testing.T) { "2C&module=dubbogo+user-info+server&org=ikurento.com&owner=ZX&pid=1447&revision=0.0.1&side=provider&timeout=3000&t"+ "imestamp=1556509797245", u.params.Encode()) - assert.Equal(t, "dubbo://:@127.0.0.1:20000/com.ikurento.user.UserProvider?anyhost=true&application=BDTServi"+ + assert.Equal(t, "dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?anyhost=true&application=BDTServi"+ "ce&category=providers&default.timeout=10000&dubbo=dubbo-provider-golang-1.0.0&environment=dev&interface=com.ikure"+ "nto.user.UserProvider&ip=192.168.56.1&methods=GetUser%2C&module=dubbogo+user-info+server&org=ikurento.com&owner="+ "ZX&pid=1447&revision=0.0.1&side=provider&timeout=3000×tamp=1556509797245", u.String()) } func TestURL_URLEqual(t *testing.T) { - u1, err := NewURL(context.TODO(), "dubbo://:@127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0") + u1, err := NewURL(context.TODO(), "dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0") assert.NoError(t, err) - u2, err := NewURL(context.TODO(), "dubbo://:@127.0.0.2:20001/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0") + u2, err := NewURL(context.TODO(), "dubbo://127.0.0.2:20001/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0") assert.NoError(t, err) assert.True(t, u1.URLEqual(u2)) - u3, err := NewURL(context.TODO(), "dubbo://:@127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=gg&version=2.6.0") + u3, err := NewURL(context.TODO(), "dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=gg&version=2.6.0") assert.NoError(t, err) assert.False(t, u1.URLEqual(u3)) } @@ -231,10 +231,31 @@ func TestMergeUrl(t *testing.T) { referenceUrl, _ := NewURL(context.TODO(), "mock1://127.0.0.1:1111", WithParams(referenceUrlParams), WithMethods([]string{"testMethod"})) serviceUrl, _ := NewURL(context.TODO(), "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", "")) assert.Equal(t, "1", mergedUrl.GetParam(constant.RETRIES_KEY, "")) assert.Equal(t, "1", mergedUrl.GetParam("methods.testMethod."+constant.RETRIES_KEY, "")) } + +func TestURL_SetParams(t *testing.T) { + u1, err := NewURL(context.TODO(), "dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0&configVersion=1.0") + assert.NoError(t, err) + params := url.Values{} + params.Set("key", "3") + u1.SetParams(params) + assert.Equal(t, "3", u1.GetParam("key", "")) + assert.Equal(t, "2.6.0", u1.GetParam("version", "")) +} + +func TestClone(t *testing.T) { + u1, err := NewURL(context.TODO(), "dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0&configVersion=1.0") + assert.NoError(t, err) + u2 := u1.Clone() + assert.Equal(t, u2.Protocol, "dubbo") + assert.Equal(t, "1.0", u2.GetParam("configVersion", "")) + u2.Protocol = "provider" + assert.Equal(t, u1.Protocol, "dubbo") + assert.Equal(t, u2.Protocol, "provider") +} diff --git a/common/utils/net.go b/common/utils/net.go index 41d7b9e2e5..47a2502317 100644 --- a/common/utils/net.go +++ b/common/utils/net.go @@ -19,6 +19,7 @@ package utils import ( "net" + "strings" ) import ( @@ -37,44 +38,39 @@ func init() { } } -// ref: https://stackoverflow.com/questions/23558425/how-do-i-get-the-local-ip-address-in-go func GetLocalIP() (string, error) { - ifs, err := net.Interfaces() + faces, err := net.Interfaces() if err != nil { return "", perrors.WithStack(err) } - var ipAddr []byte - for _, i := range ifs { - addrs, err := i.Addrs() + var addr net.IP + for _, face := range faces { + if !isValidNetworkInterface(face) { + continue + } + + addrs, err := face.Addrs() if err != nil { return "", perrors.WithStack(err) } - var ip net.IP - for _, addr := range addrs { - switch v := addr.(type) { - case *net.IPNet: - ip = v.IP - case *net.IPAddr: - ip = v.IP - } - if !ip.IsLoopback() && ip.To4() != nil && isPrivateIP(ip.String()) { - ipAddr = ip - break + if ipv4, ok := getValidIPv4(addrs); ok { + addr = ipv4 + if isPrivateIP(ipv4) { + return ipv4.String(), nil } } } - if ipAddr == nil { + if addr == nil { return "", perrors.Errorf("can not get local IP") } - return net.IP(ipAddr).String(), nil + return addr.String(), nil } -func isPrivateIP(ipAddr string) bool { - ip := net.ParseIP(ipAddr) +func isPrivateIP(ip net.IP) bool { for _, priv := range privateBlocks { if priv.Contains(ip) { return true @@ -82,3 +78,47 @@ func isPrivateIP(ipAddr string) bool { } return false } + +func getValidIPv4(addrs []net.Addr) (net.IP, bool) { + for _, addr := range addrs { + var ip net.IP + + switch v := addr.(type) { + case *net.IPNet: + ip = v.IP + case *net.IPAddr: + ip = v.IP + } + + if ip == nil || ip.IsLoopback() { + continue + } + + ip = ip.To4() + if ip == nil { + // not an valid ipv4 address + continue + } + + return ip, true + } + return nil, false +} + +func isValidNetworkInterface(face net.Interface) bool { + if face.Flags&net.FlagUp == 0 { + // interface down + return false + } + + if face.Flags&net.FlagLoopback != 0 { + // loopback interface + return false + } + + if strings.Contains(strings.ToLower(face.Name), "docker") { + return false + } + + return true +} diff --git a/config/application_config.go b/config/application_config.go index af4ffd6acf..fcd4d38c9b 100644 --- a/config/application_config.go +++ b/config/application_config.go @@ -17,7 +17,13 @@ package config -import "github.com/apache/dubbo-go/common/constant" +import ( + "github.com/creasty/defaults" +) + +import ( + "github.com/apache/dubbo-go/common/constant" +) type ApplicationConfig struct { Organization string `yaml:"organization" json:"organization,omitempty" property:"organization"` @@ -37,3 +43,13 @@ func (c *ApplicationConfig) Id() string { func (c *ApplicationConfig) SetId(id string) { } +func (c *ApplicationConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { + if err := defaults.Set(c); err != nil { + return err + } + type plain ApplicationConfig + if err := unmarshal((*plain)(c)); err != nil { + return err + } + return nil +} diff --git a/config/base_config.go b/config/base_config.go index 54ad8aba36..264eeda3cc 100644 --- a/config/base_config.go +++ b/config/base_config.go @@ -20,10 +20,13 @@ import ( "context" "reflect" "strconv" + "strings" ) + import ( perrors "github.com/pkg/errors" ) + import ( "github.com/apache/dubbo-go/common" "github.com/apache/dubbo-go/common/config" @@ -60,6 +63,7 @@ func (c *BaseConfig) prepareEnvironment() error { factory := extension.GetConfigCenterFactory(c.ConfigCenterConfig.Protocol) dynamicConfig, err := factory.GetDynamicConfiguration(c.configCenterUrl) + config.GetEnvInstance().SetDynamicConfiguration(dynamicConfig) if err != nil { logger.Errorf("Get dynamic configuration error , error message is %v", err) return perrors.WithStack(err) @@ -69,43 +73,109 @@ func (c *BaseConfig) prepareEnvironment() error { logger.Errorf("Get config content in dynamic configuration error , error message is %v", err) return perrors.WithStack(err) } + var appGroup string + var appContent string + if providerConfig != nil && providerConfig.ApplicationConfig != nil && + reflect.ValueOf(c.fatherConfig).Elem().Type().Name() == "ProviderConfig" { + appGroup = providerConfig.ApplicationConfig.Name + } else if consumerConfig != nil && consumerConfig.ApplicationConfig != nil && + reflect.ValueOf(c.fatherConfig).Elem().Type().Name() == "ConsumerConfig" { + appGroup = consumerConfig.ApplicationConfig.Name + } + + if len(appGroup) != 0 { + configFile := c.ConfigCenterConfig.AppConfigFile + if len(configFile) == 0 { + configFile = c.ConfigCenterConfig.ConfigFile + } + appContent, err = dynamicConfig.GetConfig(configFile, config_center.WithGroup(appGroup)) + } + //global config file mapContent, err := dynamicConfig.Parser().Parse(content) if err != nil { return perrors.WithStack(err) } config.GetEnvInstance().UpdateExternalConfigMap(mapContent) + + //appGroup config file + if len(appContent) != 0 { + appMapConent, err := dynamicConfig.Parser().Parse(appContent) + if err != nil { + return perrors.WithStack(err) + } + config.GetEnvInstance().UpdateAppExternalConfigMap(appMapConent) + } + return nil } -func getKeyPrefix(val reflect.Value, id reflect.Value) string { +func getKeyPrefix(val reflect.Value) []string { var ( prefix string - idStr string ) - if id.Kind() == reflect.String { - idStr = id.Interface().(string) - } if val.CanAddr() { prefix = val.Addr().MethodByName("Prefix").Call(nil)[0].String() } else { prefix = val.MethodByName("Prefix").Call(nil)[0].String() } + var retPrefixs []string + + for _, pfx := range strings.Split(prefix, "|") { + + retPrefixs = append(retPrefixs, pfx) - if idStr != "" { - return prefix + idStr + "." - } else { - return prefix } -} + return retPrefixs +} +func getPtrElement(v reflect.Value) reflect.Value { + if v.Kind() == reflect.Ptr { + v = v.Elem() + if v.Kind() == reflect.Ptr { + return getPtrElement(v) + } + } + return v +} func setFieldValue(val reflect.Value, id reflect.Value, config *config.InmemoryConfiguration) { for i := 0; i < val.NumField(); i++ { if key := val.Type().Field(i).Tag.Get("property"); key != "-" && key != "" { f := val.Field(i) if f.IsValid() { setBaseValue := func(f reflect.Value) { - ok, value := config.GetProperty(getKeyPrefix(val, id) + key) + + var ( + ok bool + value string + idStr string + ) + + prefixs := getKeyPrefix(val) + + if id.Kind() == reflect.String { + idStr = id.Interface().(string) + } + + for _, pfx := range prefixs { + + if len(pfx) > 0 { + if len(idStr) > 0 { + ok, value = config.GetProperty(pfx + idStr + "." + key) + } + if len(value) == 0 || !ok { + ok, value = config.GetProperty(pfx + key) + } + + } else { + ok, value = config.GetProperty(key) + } + + if ok { + break + } + + } if ok { switch f.Kind() { case reflect.Int64: @@ -151,12 +221,12 @@ func setFieldValue(val reflect.Value, id reflect.Value, config *config.InmemoryC } - setBaseValue(f) if f.Kind() == reflect.Ptr { - if f.Elem().Kind() == reflect.Struct { - setFieldValue(f.Elem(), reflect.Value{}, config) + f = getPtrElement(f) + if f.Kind() == reflect.Struct { + setFieldValue(f, reflect.Value{}, config) } else { - setBaseValue(f.Elem()) + setBaseValue(f) } } @@ -167,10 +237,11 @@ func setFieldValue(val reflect.Value, id reflect.Value, config *config.InmemoryC for i := 0; i < f.Len(); i++ { e := f.Index(i) if e.Kind() == reflect.Ptr { - if e.Elem().Kind() == reflect.Struct { - setFieldValue(e.Elem(), reflect.Value{}, config) + e = getPtrElement(e) + if e.Kind() == reflect.Struct { + setFieldValue(e, reflect.Value{}, config) } else { - setBaseValue(e.Elem()) + setBaseValue(e) } } @@ -183,10 +254,16 @@ func setFieldValue(val reflect.Value, id reflect.Value, config *config.InmemoryC //initiate config s := reflect.New(f.Type().Elem().Elem()) prefix := s.MethodByName("Prefix").Call(nil)[0].String() - m := config.GetSubProperty(prefix) - for k := range m { - f.SetMapIndex(reflect.ValueOf(k), reflect.New(f.Type().Elem().Elem())) + for _, pfx := range strings.Split(prefix, "|") { + m := config.GetSubProperty(pfx) + if m != nil { + for k := range m { + f.SetMapIndex(reflect.ValueOf(k), reflect.New(f.Type().Elem().Elem())) + } + } + } + } //iter := f.MapRange() @@ -195,10 +272,11 @@ func setFieldValue(val reflect.Value, id reflect.Value, config *config.InmemoryC v := f.MapIndex(k) switch v.Kind() { case reflect.Ptr: - if v.Elem().Kind() == reflect.Struct { - setFieldValue(v.Elem(), k, config) + v = getPtrElement(v) + if v.Kind() == reflect.Struct { + setFieldValue(v, k, config) } else { - setBaseValue(v.Elem()) + setBaseValue(v) } case reflect.Int64, reflect.String, reflect.Bool, reflect.Float64: setBaseValue(v) @@ -207,6 +285,7 @@ func setFieldValue(val reflect.Value, id reflect.Value, config *config.InmemoryC } } } + setBaseValue(f) } } @@ -214,8 +293,13 @@ func setFieldValue(val reflect.Value, id reflect.Value, config *config.InmemoryC } func (c *BaseConfig) fresh() { configList := config.GetEnvInstance().Configuration() - config := configList.Front().Value.(*config.InmemoryConfiguration) + for element := configList.Front(); element != nil; element = element.Next() { + config := element.Value.(*config.InmemoryConfiguration) + c.freshInternalConfig(config) + } +} +func (c *BaseConfig) freshInternalConfig(config *config.InmemoryConfiguration) { //reflect to init struct tp := reflect.ValueOf(c.fatherConfig).Elem().Type() initializeStruct(tp, reflect.ValueOf(c.fatherConfig).Elem()) diff --git a/config/base_config_test.go b/config/base_config_test.go index 7cb18c2c58..6dc3749e55 100644 --- a/config/base_config_test.go +++ b/config/base_config_test.go @@ -125,6 +125,258 @@ func Test_refresh(t *testing.T) { assert.Equal(t, "dubbo", father.ApplicationConfig.Name) } +func Test_appExternal_refresh(t *testing.T) { + c := &BaseConfig{} + mockMap := map[string]string{} + mockMap["dubbo.registries.shanghai_reg1.protocol"] = "mock100" + mockMap["dubbo.reference.com.MockService.MockService.retries"] = "10" + mockMap["dubbo.reference.com.MockService.retries"] = "5" + mockMap["dubbo.com.MockService.MockService.GetUser.retries"] = "10" + mockMap["dubbo.consumer.check"] = "false" + mockMap["dubbo.application.name"] = "dubbo" + + config.GetEnvInstance().UpdateAppExternalConfigMap(mockMap) + mockMap["dubbo.consumer.check"] = "true" + config.GetEnvInstance().UpdateExternalConfigMap(mockMap) + father := &ConsumerConfig{ + Check: &[]bool{true}[0], + ApplicationConfig: &ApplicationConfig{ + Organization: "dubbo_org", + Name: "dubbo", + Module: "module", + Version: "2.6.0", + Owner: "dubbo", + Environment: "test"}, + Registries: map[string]*RegistryConfig{ + //"shanghai_reg1": { + // id: "shanghai_reg1", + // Protocol: "mock", + // TimeoutStr: "2s", + // Group: "shanghai_idc", + // Address: "127.0.0.1:2181", + // Username: "user1", + // Password: "pwd1", + //}, + "shanghai_reg2": { + Protocol: "mock", + TimeoutStr: "2s", + Group: "shanghai_idc", + Address: "127.0.0.2:2181", + Username: "user1", + Password: "pwd1", + }, + "hangzhou_reg1": { + Protocol: "mock", + TimeoutStr: "2s", + Group: "hangzhou_idc", + Address: "127.0.0.3:2181", + Username: "user1", + Password: "pwd1", + }, + "hangzhou_reg2": { + Protocol: "mock", + TimeoutStr: "2s", + Group: "hangzhou_idc", + Address: "127.0.0.4:2181", + Username: "user1", + Password: "pwd1", + }, + }, + References: map[string]*ReferenceConfig{ + "MockService": { + InterfaceName: "com.MockService", + Protocol: "mock", + Cluster: "failover", + Loadbalance: "random", + Retries: "3", + Group: "huadong_idc", + Version: "1.0.0", + Methods: []*MethodConfig{ + { + InterfaceId: "MockService", + InterfaceName: "com.MockService", + Name: "GetUser", + Retries: "2", + Loadbalance: "random", + }, + { + InterfaceId: "MockService", + InterfaceName: "com.MockService", + Name: "GetUser1", + Retries: "2", + Loadbalance: "random", + }, + }, + }, + }, + } + + c.SetFatherConfig(father) + c.fresh() + assert.Equal(t, "mock100", father.Registries["shanghai_reg1"].Protocol) + assert.Equal(t, "10", father.References["MockService"].Retries) + + assert.Equal(t, "10", father.References["MockService"].Methods[0].Retries) + assert.Equal(t, &[]bool{true}[0], father.Check) + assert.Equal(t, "dubbo", father.ApplicationConfig.Name) +} + +func Test_appExternalWithoutId_refresh(t *testing.T) { + c := &BaseConfig{} + mockMap := map[string]string{} + mockMap["dubbo.registries.shanghai_reg1.protocol"] = "mock100" + mockMap["dubbo.reference.com.MockService.retries"] = "10" + mockMap["dubbo.com.MockService.MockService.GetUser.retries"] = "10" + mockMap["dubbo.consumer.check"] = "false" + mockMap["dubbo.application.name"] = "dubbo" + + config.GetEnvInstance().UpdateAppExternalConfigMap(mockMap) + mockMap["dubbo.consumer.check"] = "true" + config.GetEnvInstance().UpdateExternalConfigMap(mockMap) + father := &ConsumerConfig{ + Check: &[]bool{true}[0], + ApplicationConfig: &ApplicationConfig{ + Organization: "dubbo_org", + Name: "dubbo", + Module: "module", + Version: "2.6.0", + Owner: "dubbo", + Environment: "test"}, + Registries: map[string]*RegistryConfig{ + //"shanghai_reg1": { + // id: "shanghai_reg1", + // Protocol: "mock", + // TimeoutStr: "2s", + // Group: "shanghai_idc", + // Address: "127.0.0.1:2181", + // Username: "user1", + // Password: "pwd1", + //}, + "shanghai_reg2": { + Protocol: "mock", + TimeoutStr: "2s", + Group: "shanghai_idc", + Address: "127.0.0.2:2181", + Username: "user1", + Password: "pwd1", + }, + "hangzhou_reg1": { + Protocol: "mock", + TimeoutStr: "2s", + Group: "hangzhou_idc", + Address: "127.0.0.3:2181", + Username: "user1", + Password: "pwd1", + }, + "hangzhou_reg2": { + Protocol: "mock", + TimeoutStr: "2s", + Group: "hangzhou_idc", + Address: "127.0.0.4:2181", + Username: "user1", + Password: "pwd1", + }, + }, + References: map[string]*ReferenceConfig{ + "MockService": { + InterfaceName: "com.MockService", + Protocol: "mock", + Cluster: "failover", + Loadbalance: "random", + Retries: "3", + Group: "huadong_idc", + Version: "1.0.0", + Methods: []*MethodConfig{ + { + InterfaceId: "MockService", + InterfaceName: "com.MockService", + Name: "GetUser", + Retries: "3", + Loadbalance: "random", + }, + { + InterfaceId: "MockService", + InterfaceName: "com.MockService", + Name: "GetUser1", + Retries: "2", + Loadbalance: "random", + }, + }, + }, + }, + } + + c.SetFatherConfig(father) + c.fresh() + assert.Equal(t, "mock100", father.Registries["shanghai_reg1"].Protocol) + assert.Equal(t, "10", father.References["MockService"].Retries) + + assert.Equal(t, "10", father.References["MockService"].Methods[0].Retries) + assert.Equal(t, &[]bool{true}[0], father.Check) + assert.Equal(t, "dubbo", father.ApplicationConfig.Name) +} + +func Test_refresh_singleRegistry(t *testing.T) { + c := &BaseConfig{} + mockMap := map[string]string{} + mockMap["dubbo.registry.address"] = "mock100://127.0.0.1:2181" + mockMap["dubbo.reference.com.MockService.MockService.retries"] = "10" + mockMap["dubbo.com.MockService.MockService.GetUser.retries"] = "10" + mockMap["dubbo.consumer.check"] = "false" + mockMap["dubbo.application.name"] = "dubbo" + + config.GetEnvInstance().UpdateExternalConfigMap(mockMap) + + father := &ConsumerConfig{ + Check: &[]bool{true}[0], + ApplicationConfig: &ApplicationConfig{ + Organization: "dubbo_org", + Name: "dubbo", + Module: "module", + Version: "2.6.0", + Owner: "dubbo", + Environment: "test"}, + Registries: map[string]*RegistryConfig{}, + Registry: &RegistryConfig{}, + References: map[string]*ReferenceConfig{ + "MockService": { + InterfaceName: "com.MockService", + Protocol: "mock", + Cluster: "failover", + Loadbalance: "random", + Retries: "3", + Group: "huadong_idc", + Version: "1.0.0", + Methods: []*MethodConfig{ + { + InterfaceId: "MockService", + InterfaceName: "com.MockService", + Name: "GetUser", + Retries: "2", + Loadbalance: "random", + }, + { + InterfaceId: "MockService", + InterfaceName: "com.MockService", + Name: "GetUser1", + Retries: "2", + Loadbalance: "random", + }, + }, + }, + }, + } + + c.SetFatherConfig(father) + c.fresh() + assert.Equal(t, "mock100://127.0.0.1:2181", father.Registry.Address) + assert.Equal(t, "10", father.References["MockService"].Retries) + + assert.Equal(t, "10", father.References["MockService"].Methods[0].Retries) + assert.Equal(t, &[]bool{false}[0], father.Check) + assert.Equal(t, "dubbo", father.ApplicationConfig.Name) +} + func Test_refreshProvider(t *testing.T) { c := &BaseConfig{} mockMap := map[string]string{} @@ -233,7 +485,7 @@ func Test_startConfigCenter(t *testing.T) { }} err := c.startConfigCenter(context.Background()) assert.NoError(t, err) - b, v := config.GetEnvInstance().Configuration().Front().Value.(*config.InmemoryConfiguration).GetProperty("dubbo.application.organization") + b, v := config.GetEnvInstance().Configuration().Back().Value.(*config.InmemoryConfiguration).GetProperty("dubbo.application.organization") assert.True(t, b) assert.Equal(t, "ikurento.com", v) } diff --git a/config/config_center_config.go b/config/config_center_config.go index 47efce1265..ed43558956 100644 --- a/config/config_center_config.go +++ b/config/config_center_config.go @@ -22,15 +22,31 @@ import ( "time" ) +import ( + "github.com/creasty/defaults" +) + type ConfigCenterConfig struct { - context context.Context - Protocol string `required:"true" yaml:"protocol" json:"protocol,omitempty"` - Address string `yaml:"address" json:"address,omitempty"` - Cluster string `yaml:"cluster" json:"cluster,omitempty"` - Group string `default:"dubbo" yaml:"group" json:"group,omitempty"` - Username string `yaml:"username" json:"username,omitempty"` - Password string `yaml:"password" json:"password,omitempty"` - ConfigFile string `default:"dubbo.properties" yaml:"config_file" json:"config_file,omitempty"` - TimeoutStr string `yaml:"timeout" json:"timeout,omitempty"` - timeout time.Duration + context context.Context + Protocol string `required:"true" yaml:"protocol" json:"protocol,omitempty"` + Address string `yaml:"address" json:"address,omitempty"` + Cluster string `yaml:"cluster" json:"cluster,omitempty"` + Group string `default:"dubbo" yaml:"group" json:"group,omitempty"` + Username string `yaml:"username" json:"username,omitempty"` + Password string `yaml:"password" json:"password,omitempty"` + ConfigFile string `default:"dubbo.properties" yaml:"config_file" json:"config_file,omitempty"` + AppConfigFile string `default:"dubbo.properties" yaml:"app_config_file" json:"app_config_file,omitempty"` + TimeoutStr string `yaml:"timeout" json:"timeout,omitempty"` + timeout time.Duration +} + +func (c *ConfigCenterConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { + if err := defaults.Set(c); err != nil { + return err + } + type plain ConfigCenterConfig + if err := unmarshal((*plain)(c)); err != nil { + return err + } + return nil } diff --git a/config/config_loader.go b/config/config_loader.go index c5127c8c43..b737d3f233 100644 --- a/config/config_loader.go +++ b/config/config_loader.go @@ -55,15 +55,31 @@ func init() { } } +func checkRegistries(registries map[string]*RegistryConfig, singleRegistry *RegistryConfig) { + if len(registries) == 0 && singleRegistry != nil { + registries[constant.DEFAULT_KEY] = singleRegistry + } +} + +func checkApplicationName(config *ApplicationConfig) { + if config == nil || len(config.Name) == 0 { + errMsg := "application config must not be nil, pls check your configuration" + logger.Errorf(errMsg) + panic(errMsg) + } +} + // Dubbo Init func Load() { // reference config if consumerConfig == nil { logger.Warnf("consumerConfig is nil!") } else { + checkApplicationName(consumerConfig.ApplicationConfig) if err := configCenterRefreshConsumer(); err != nil { logger.Errorf("[consumer config center refresh] %#v", err) } + checkRegistries(consumerConfig.Registries, consumerConfig.Registry) for key, ref := range consumerConfig.References { if ref.Generic { genericService := NewGenericService(key) @@ -92,7 +108,9 @@ func Load() { checkok = false count++ if count > maxWait { - panic(fmt.Sprintf("Failed to check the status of the service %v . No provider available for the service to the consumer use dubbo version %v", refconfig.InterfaceName, constant.Version)) + errMsg := fmt.Sprintf("Failed to check the status of the service %v . No provider available for the service to the consumer use dubbo version %v", refconfig.InterfaceName, constant.Version) + logger.Error(errMsg) + panic(errMsg) } time.Sleep(time.Second * 1) break @@ -113,9 +131,11 @@ func Load() { if providerConfig == nil { logger.Warnf("providerConfig is nil!") } else { + checkApplicationName(providerConfig.ApplicationConfig) if err := configCenterRefreshProvider(); err != nil { logger.Errorf("[provider config center refresh] %#v", err) } + checkRegistries(providerConfig.Registries, providerConfig.Registry) for key, svs := range providerConfig.Services { rpcService := GetProviderService(key) if rpcService == nil { diff --git a/config/config_loader_test.go b/config/config_loader_test.go index 107fea0b1d..498f826780 100644 --- a/config/config_loader_test.go +++ b/config/config_loader_test.go @@ -29,6 +29,8 @@ import ( import ( "github.com/apache/dubbo-go/cluster/cluster_impl" "github.com/apache/dubbo-go/common" + "github.com/apache/dubbo-go/common/config" + "github.com/apache/dubbo-go/common/constant" "github.com/apache/dubbo-go/common/extension" "github.com/apache/dubbo-go/common/proxy/proxy_factory" "github.com/apache/dubbo-go/config_center" @@ -58,8 +60,36 @@ func TestConfigLoader(t *testing.T) { } func TestLoad(t *testing.T) { - doInit() - doinit() + doInitConsumer() + doInitProvider() + + ms := &MockService{} + SetConsumerService(ms) + SetProviderService(ms) + + extension.SetProtocol("registry", GetProtocol) + extension.SetCluster("registryAware", cluster_impl.NewRegistryAwareCluster) + extension.SetProxyFactory("default", proxy_factory.NewDefaultProxyFactory) + + Load() + + assert.Equal(t, ms, GetRPCService(ms.Reference())) + ms2 := &struct { + MockService + }{} + RPCService(ms2) + assert.NotEqual(t, ms2, GetRPCService(ms2.Reference())) + + conServices = map[string]common.RPCService{} + proServices = map[string]common.RPCService{} + common.ServiceMap.UnRegister("mock", "MockService") + consumerConfig = nil + providerConfig = nil +} + +func TestLoadWithSingleReg(t *testing.T) { + doInitConsumerWithSingleRegistry() + doInitProviderWithSingleRegistry() ms := &MockService{} SetConsumerService(ms) @@ -86,8 +116,8 @@ func TestLoad(t *testing.T) { } func TestWithNoRegLoad(t *testing.T) { - doInit() - doinit() + doInitConsumer() + doInitProvider() providerConfig.Services["MockService"].Registry = "" consumerConfig.References["MockService"].Registry = "" ms := &MockService{} @@ -145,3 +175,60 @@ func TestConfigLoaderWithConfigCenter(t *testing.T) { assert.Equal(t, "127.0.0.1:2181", consumerConfig.Registries["hangzhouzk"].Address) } + +func TestConfigLoaderWithConfigCenterSingleRegistry(t *testing.T) { + consumerConfig = nil + providerConfig = nil + config.NewEnvInstance() + extension.SetConfigCenterFactory("mock", func() config_center.DynamicConfigurationFactory { + return &config_center.MockDynamicConfigurationFactory{Content: ` + dubbo.consumer.request_timeout=5s + dubbo.consumer.connect_timeout=5s + dubbo.application.organization=ikurento.com + dubbo.application.name=BDTService + dubbo.application.module=dubbogo user-info server + dubbo.application.version=0.0.1 + dubbo.application.owner=ZX + dubbo.application.environment=dev + dubbo.registry.address=mock://127.0.0.1:2182 + dubbo.service.com.ikurento.user.UserProvider.protocol=dubbo + dubbo.service.com.ikurento.user.UserProvider.interface=com.ikurento.user.UserProvider + dubbo.service.com.ikurento.user.UserProvider.loadbalance=random + dubbo.service.com.ikurento.user.UserProvider.warmup=100 + dubbo.service.com.ikurento.user.UserProvider.cluster=failover + dubbo.protocols.jsonrpc1.name=jsonrpc + dubbo.protocols.jsonrpc1.ip=127.0.0.1 + dubbo.protocols.jsonrpc1.port=20001 +`} + }) + + conPath, err := filepath.Abs("./testdata/consumer_config_with_configcenter.yml") + assert.NoError(t, err) + proPath, err := filepath.Abs("./testdata/provider_config.yml") + assert.NoError(t, err) + + assert.Nil(t, consumerConfig) + assert.Equal(t, ConsumerConfig{}, GetConsumerConfig()) + assert.Nil(t, providerConfig) + assert.Equal(t, ProviderConfig{}, GetProviderConfig()) + + err = ConsumerInit(conPath) + checkApplicationName(consumerConfig.ApplicationConfig) + configCenterRefreshConsumer() + checkRegistries(consumerConfig.Registries, consumerConfig.Registry) + assert.NoError(t, err) + err = ProviderInit(proPath) + checkApplicationName(providerConfig.ApplicationConfig) + configCenterRefreshProvider() + checkRegistries(providerConfig.Registries, providerConfig.Registry) + assert.NoError(t, err) + + assert.NotNil(t, consumerConfig) + assert.NotEqual(t, ConsumerConfig{}, GetConsumerConfig()) + assert.NotNil(t, providerConfig) + assert.NotEqual(t, ProviderConfig{}, GetProviderConfig()) + + assert.Equal(t, "BDTService", consumerConfig.ApplicationConfig.Name) + assert.Equal(t, "mock://127.0.0.1:2182", consumerConfig.Registries[constant.DEFAULT_KEY].Address) + +} diff --git a/config/config_utils.go b/config/config_utils.go index 90837344ca..6bc574a546 100644 --- a/config/config_utils.go +++ b/config/config_utils.go @@ -21,6 +21,7 @@ import ( "regexp" "strings" ) + import ( "github.com/apache/dubbo-go/common/constant" ) diff --git a/config/consumer_config.go b/config/consumer_config.go index 55082ffe41..b1ebdd5d8e 100644 --- a/config/consumer_config.go +++ b/config/consumer_config.go @@ -22,10 +22,13 @@ import ( "path" "time" ) + import ( + "github.com/creasty/defaults" perrors "github.com/pkg/errors" "gopkg.in/yaml.v2" ) + import ( "github.com/apache/dubbo-go/common/constant" "github.com/apache/dubbo-go/common/logger" @@ -39,7 +42,7 @@ type ConsumerConfig struct { BaseConfig `yaml:",inline"` Filter string `yaml:"filter" json:"filter,omitempty" property:"filter"` // application - ApplicationConfig *ApplicationConfig `yaml:"application_config" json:"application_config,omitempty" property:"application_config"` + ApplicationConfig *ApplicationConfig `yaml:"application" json:"application,omitempty" property:"application"` // client Connect_Timeout string `default:"100ms" yaml:"connect_timeout" json:"connect_timeout,omitempty" property:"connect_timeout"` ConnectTimeout time.Duration @@ -49,12 +52,24 @@ type ConsumerConfig struct { ProxyFactory string `yaml:"proxy_factory" default:"default" json:"proxy_factory,omitempty" property:"proxy_factory"` Check *bool `yaml:"check" json:"check,omitempty" property:"check"` + Registry *RegistryConfig `yaml:"registry" json:"registry,omitempty" property:"registry"` Registries map[string]*RegistryConfig `yaml:"registries" json:"registries,omitempty" property:"registries"` References map[string]*ReferenceConfig `yaml:"references" json:"references,omitempty" property:"references"` ProtocolConf interface{} `yaml:"protocol_conf" json:"protocol_conf,omitempty" property:"protocol_conf"` FilterConf interface{} `yaml:"filter_conf" json:"filter_conf,omitempty" property:"filter_conf" ` } +func (c *ConsumerConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { + if err := defaults.Set(c); err != nil { + return err + } + type plain ConsumerConfig + if err := unmarshal((*plain)(c)); err != nil { + return err + } + return nil +} + func (*ConsumerConfig) Prefix() string { return constant.ConsumerConfigPrefix } diff --git a/config/method_config.go b/config/method_config.go index 560eaeaefa..ac9242a230 100644 --- a/config/method_config.go +++ b/config/method_config.go @@ -16,6 +16,10 @@ */ package config +import ( + "github.com/creasty/defaults" +) + import ( "github.com/apache/dubbo-go/common/constant" ) @@ -36,3 +40,14 @@ func (c *MethodConfig) Prefix() string { return constant.DUBBO + "." + c.InterfaceName + "." + c.Name + "." } } + +func (c *MethodConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { + if err := defaults.Set(c); err != nil { + return err + } + type plain MethodConfig + if err := unmarshal((*plain)(c)); err != nil { + return err + } + return nil +} diff --git a/config/protocol_config.go b/config/protocol_config.go index 6440f3090d..b71423670c 100644 --- a/config/protocol_config.go +++ b/config/protocol_config.go @@ -19,6 +19,7 @@ package config import ( "strings" ) + import ( "github.com/apache/dubbo-go/common/constant" ) diff --git a/config/provider_config.go b/config/provider_config.go index db8abaf73e..00faa1d0ab 100644 --- a/config/provider_config.go +++ b/config/provider_config.go @@ -23,6 +23,7 @@ import ( ) import ( + "github.com/creasty/defaults" perrors "github.com/pkg/errors" "gopkg.in/yaml.v2" ) @@ -41,7 +42,8 @@ type ProviderConfig struct { Filter string `yaml:"filter" json:"filter,omitempty" property:"filter"` ProxyFactory string `yaml:"proxy_factory" default:"default" json:"proxy_factory,omitempty" property:"proxy_factory"` - ApplicationConfig *ApplicationConfig `yaml:"application_config" json:"application_config,omitempty" property:"application_config"` + ApplicationConfig *ApplicationConfig `yaml:"application" json:"application,omitempty" property:"application"` + Registry *RegistryConfig `yaml:"registry" json:"registry,omitempty" property:"registry"` Registries map[string]*RegistryConfig `yaml:"registries" json:"registries,omitempty" property:"registries"` Services map[string]*ServiceConfig `yaml:"services" json:"services,omitempty" property:"services"` Protocols map[string]*ProtocolConfig `yaml:"protocols" json:"protocols,omitempty" property:"protocols"` @@ -49,6 +51,17 @@ type ProviderConfig struct { FilterConf interface{} `yaml:"filter_conf" json:"filter_conf,omitempty" property:"filter_conf" ` } +func (c *ProviderConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { + if err := defaults.Set(c); err != nil { + return err + } + type plain ProviderConfig + if err := unmarshal((*plain)(c)); err != nil { + return err + } + return nil +} + func (*ProviderConfig) Prefix() string { return constant.ProviderConfigPrefix } diff --git a/config/provider_config_test.go b/config/provider_config_test.go new file mode 100644 index 0000000000..db4b5f9906 --- /dev/null +++ b/config/provider_config_test.go @@ -0,0 +1,33 @@ +package config + +import ( + "path/filepath" + "testing" +) + +import ( + "github.com/stretchr/testify/assert" +) + +func TestConsumerInit(t *testing.T) { + conPath, err := filepath.Abs("./testdata/consumer_config_with_configcenter.yml") + assert.NoError(t, err) + assert.NoError(t, ConsumerInit(conPath)) + assert.Equal(t, "default", consumerConfig.ProxyFactory) + assert.Equal(t, "dubbo.properties", consumerConfig.ConfigCenterConfig.ConfigFile) + assert.Equal(t, "100ms", consumerConfig.Connect_Timeout) +} + +func TestConsumerInitWithDefaultProtocol(t *testing.T) { + conPath, err := filepath.Abs("./testdata/consumer_config_withoutProtocol.yml") + assert.NoError(t, err) + assert.NoError(t, ConsumerInit(conPath)) + assert.Equal(t, "dubbo", consumerConfig.References["UserProvider"].Protocol) +} + +func TestProviderInitWithDefaultProtocol(t *testing.T) { + conPath, err := filepath.Abs("./testdata/provider_config_withoutProtocol.yml") + assert.NoError(t, err) + assert.NoError(t, ProviderInit(conPath)) + assert.Equal(t, "dubbo", providerConfig.Services["UserProvider"].Protocol) +} diff --git a/config/reference_config.go b/config/reference_config.go index 1a318a6487..26976f1ccf 100644 --- a/config/reference_config.go +++ b/config/reference_config.go @@ -25,6 +25,10 @@ import ( "time" ) +import ( + "github.com/creasty/defaults" +) + import ( "github.com/apache/dubbo-go/cluster/directory" "github.com/apache/dubbo-go/common" @@ -43,7 +47,7 @@ type ReferenceConfig struct { Check *bool `yaml:"check" json:"check,omitempty" property:"check"` Url string `yaml:"url" json:"url,omitempty" property:"url"` Filter string `yaml:"filter" json:"filter,omitempty" property:"filter"` - Protocol string `yaml:"protocol" json:"protocol,omitempty" property:"protocol"` + Protocol string `default:"dubbo" yaml:"protocol" json:"protocol,omitempty" property:"protocol"` Registry string `yaml:"registry" json:"registry,omitempty" property:"registry"` Cluster string `yaml:"cluster" json:"cluster,omitempty" property:"cluster"` Loadbalance string `yaml:"loadbalance" json:"loadbalance,omitempty" property:"loadbalance"` @@ -68,6 +72,7 @@ func NewReferenceConfig(id string, ctx context.Context) *ReferenceConfig { } func (refconfig *ReferenceConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { + type rf ReferenceConfig raw := rf{} // Put your defaults here if err := unmarshal(&raw); err != nil { @@ -75,6 +80,10 @@ func (refconfig *ReferenceConfig) UnmarshalYAML(unmarshal func(interface{}) erro } *refconfig = ReferenceConfig(raw) + if err := defaults.Set(refconfig); err != nil { + return err + } + return nil } @@ -97,8 +106,8 @@ func (refconfig *ReferenceConfig) Refer() { serviceUrl.Path = "/" + refconfig.id } // merge url need to do - newUrl := common.MergeUrl(serviceUrl, url) - refconfig.urls = append(refconfig.urls, &newUrl) + newUrl := common.MergeUrl(&serviceUrl, url) + refconfig.urls = append(refconfig.urls, newUrl) } } diff --git a/config/reference_config_test.go b/config/reference_config_test.go index cbe5c4cd65..a81dbf06ce 100644 --- a/config/reference_config_test.go +++ b/config/reference_config_test.go @@ -36,7 +36,7 @@ import ( var regProtocol protocol.Protocol -func doInit() { +func doInitConsumer() { consumerConfig = &ConsumerConfig{ ApplicationConfig: &ApplicationConfig{ Organization: "dubbo_org", @@ -110,8 +110,53 @@ func doInit() { } } +func doInitConsumerWithSingleRegistry() { + consumerConfig = &ConsumerConfig{ + ApplicationConfig: &ApplicationConfig{ + Organization: "dubbo_org", + Name: "dubbo", + Module: "module", + Version: "2.6.0", + Owner: "dubbo", + Environment: "test"}, + Registry: &RegistryConfig{ + Address: "mock://27.0.0.1:2181", + Username: "user1", + Password: "pwd1", + }, + Registries: map[string]*RegistryConfig{}, + References: map[string]*ReferenceConfig{ + "MockService": { + Params: map[string]string{ + "serviceid": "soa.mock", + "forks": "5", + }, + InterfaceName: "com.MockService", + Protocol: "mock", + Cluster: "failover", + Loadbalance: "random", + Retries: "3", + Group: "huadong_idc", + Version: "1.0.0", + Methods: []*MethodConfig{ + { + Name: "GetUser", + Retries: "2", + Loadbalance: "random", + }, + { + Name: "GetUser1", + Retries: "2", + Loadbalance: "random", + }, + }, + }, + }, + } +} + func Test_ReferMultireg(t *testing.T) { - doInit() + doInitConsumer() extension.SetProtocol("registry", GetProtocol) extension.SetCluster("registryAware", cluster_impl.NewRegistryAwareCluster) @@ -124,7 +169,7 @@ func Test_ReferMultireg(t *testing.T) { } func Test_Refer(t *testing.T) { - doInit() + doInitConsumer() extension.SetProtocol("registry", GetProtocol) extension.SetCluster("registryAware", cluster_impl.NewRegistryAwareCluster) @@ -137,7 +182,7 @@ func Test_Refer(t *testing.T) { consumerConfig = nil } func Test_ReferP2P(t *testing.T) { - doInit() + doInitConsumer() extension.SetProtocol("dubbo", GetProtocol) m := consumerConfig.References["MockService"] m.Url = "dubbo://127.0.0.1:20000" @@ -151,7 +196,7 @@ func Test_ReferP2P(t *testing.T) { } func Test_ReferMultiP2P(t *testing.T) { - doInit() + doInitConsumer() extension.SetProtocol("dubbo", GetProtocol) m := consumerConfig.References["MockService"] m.Url = "dubbo://127.0.0.1:20000;dubbo://127.0.0.2:20000" @@ -165,7 +210,7 @@ func Test_ReferMultiP2P(t *testing.T) { } func Test_ReferMultiP2PWithReg(t *testing.T) { - doInit() + doInitConsumer() extension.SetProtocol("dubbo", GetProtocol) extension.SetProtocol("registry", GetProtocol) m := consumerConfig.References["MockService"] @@ -180,7 +225,7 @@ func Test_ReferMultiP2PWithReg(t *testing.T) { } func Test_Implement(t *testing.T) { - doInit() + doInitConsumer() extension.SetProtocol("registry", GetProtocol) extension.SetCluster("registryAware", cluster_impl.NewRegistryAwareCluster) for _, reference := range consumerConfig.References { @@ -193,7 +238,7 @@ func Test_Implement(t *testing.T) { } func Test_Forking(t *testing.T) { - doInit() + doInitConsumer() extension.SetProtocol("dubbo", GetProtocol) extension.SetProtocol("registry", GetProtocol) m := consumerConfig.References["MockService"] diff --git a/config/registry_config.go b/config/registry_config.go index 0abdab810f..9ffa41eb5b 100644 --- a/config/registry_config.go +++ b/config/registry_config.go @@ -24,6 +24,10 @@ import ( "strings" ) +import ( + "github.com/creasty/defaults" +) + import ( "github.com/apache/dubbo-go/common" "github.com/apache/dubbo-go/common/constant" @@ -42,8 +46,19 @@ type RegistryConfig struct { Params map[string]string `yaml:"params" json:"params,omitempty" property:"params"` } +func (c *RegistryConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { + if err := defaults.Set(c); err != nil { + return err + } + type plain RegistryConfig + if err := unmarshal((*plain)(c)); err != nil { + return err + } + return nil +} + func (*RegistryConfig) Prefix() string { - return constant.RegistryConfigPrefix + return constant.RegistryConfigPrefix + "|" + constant.SingleRegistryConfigPrefix } func loadRegistries(targetRegistries string, registries map[string]*RegistryConfig, roleType common.RoleType) []*common.URL { @@ -73,27 +88,22 @@ func loadRegistries(targetRegistries string, registries map[string]*RegistryConf url common.URL err error ) - if addresses := strings.Split(registryConf.Address, ","); len(addresses) > 1 { - url, err = common.NewURL( - context.Background(), - constant.REGISTRY_PROTOCOL+"://"+addresses[0], - common.WithParams(registryConf.getUrlMap(roleType)), - common.WithUsername(registryConf.Username), - common.WithPassword(registryConf.Password), - common.WithLocation(registryConf.Address), - ) - } else { - url, err = common.NewURL( - context.Background(), - constant.REGISTRY_PROTOCOL+"://"+registryConf.Address, - common.WithParams(registryConf.getUrlMap(roleType)), - common.WithUsername(registryConf.Username), - common.WithPassword(registryConf.Password), - ) - } + + addresses := strings.Split(registryConf.Address, ",") + address := addresses[0] + address = traslateRegistryConf(address, registryConf) + url, err = common.NewURL( + context.Background(), + constant.REGISTRY_PROTOCOL+"://"+address, + common.WithParams(registryConf.getUrlMap(roleType)), + common.WithUsername(registryConf.Username), + common.WithPassword(registryConf.Password), + common.WithLocation(registryConf.Address), + ) if err != nil { - logger.Errorf("The registry id:%s url is invalid ,and will skip the registry, error: %#v", k, err) + logger.Errorf("The registry id:%s url is invalid , error: %#v", k, err) + panic(err) } else { urls = append(urls, &url) } @@ -115,3 +125,17 @@ func (regconfig *RegistryConfig) getUrlMap(roleType common.RoleType) url.Values } return urlMap } + +func traslateRegistryConf(address string, registryConf *RegistryConfig) string { + if strings.Contains(address, "://") { + translatedUrl, err := url.Parse(address) + if err != nil { + logger.Errorf("The registry url is invalid , error: %#v", err) + panic(err) + } + address = translatedUrl.Host + registryConf.Protocol = translatedUrl.Scheme + registryConf.Address = strings.Replace(registryConf.Address, translatedUrl.Scheme+"://", "", -1) + } + return address +} diff --git a/config/registry_config_test.go b/config/registry_config_test.go index f600a21a01..45d38b29cc 100644 --- a/config/registry_config_test.go +++ b/config/registry_config_test.go @@ -20,11 +20,15 @@ import ( "fmt" "testing" ) + import ( - "github.com/apache/dubbo-go/common" "github.com/stretchr/testify/assert" ) +import ( + "github.com/apache/dubbo-go/common" +) + func Test_loadRegistries(t *testing.T) { target := "shanghai1" regs := map[string]*RegistryConfig{ diff --git a/config/service_config.go b/config/service_config.go index 5f08681838..ce15c61eb3 100644 --- a/config/service_config.go +++ b/config/service_config.go @@ -28,6 +28,7 @@ import ( ) import ( + "github.com/creasty/defaults" perrors "github.com/pkg/errors" "go.uber.org/atomic" ) @@ -45,7 +46,7 @@ type ServiceConfig struct { context context.Context id string Filter string `yaml:"filter" json:"filter,omitempty" property:"filter"` - Protocol string `required:"true" yaml:"protocol" json:"protocol,omitempty" property:"protocol"` //multi protocol support, split by ',' + Protocol string `default:"dubbo" required:"true" yaml:"protocol" json:"protocol,omitempty" property:"protocol"` //multi protocol support, split by ',' InterfaceName string `required:"true" yaml:"interface" json:"interface,omitempty" property:"interface"` Registry string `yaml:"registry" json:"registry,omitempty" property:"registry"` Cluster string `default:"failover" yaml:"cluster" json:"cluster,omitempty" property:"cluster"` @@ -56,10 +57,10 @@ type ServiceConfig struct { Warmup string `yaml:"warmup" json:"warmup,omitempty" property:"warmup"` Retries string `yaml:"retries" json:"retries,omitempty" property:"retries"` Params map[string]string `yaml:"params" json:"params,omitempty" property:"params"` + Token string `yaml:"token" json:"token,omitempty" property:"token"` unexported *atomic.Bool exported *atomic.Bool rpcService common.RPCService - exporters []protocol.Exporter cacheProtocol protocol.Protocol cacheMutex sync.Mutex } @@ -68,6 +69,17 @@ func (c *ServiceConfig) Prefix() string { return constant.ServiceConfigPrefix + c.InterfaceName + "." } +func (c *ServiceConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { + if err := defaults.Set(c); err != nil { + return err + } + type plain ServiceConfig + if err := unmarshal((*plain)(c)); err != nil { + return err + } + return nil +} + // The only way to get a new ServiceConfig func NewServiceConfig(id string, context context.Context) *ServiceConfig { @@ -111,7 +123,9 @@ func (srvconfig *ServiceConfig) Export() error { common.WithPort(proto.Port), common.WithParams(urlMap), common.WithParamsValue(constant.BEAN_NAME_KEY, srvconfig.id), - common.WithMethods(strings.Split(methods, ","))) + common.WithMethods(strings.Split(methods, ",")), + common.WithToken(srvconfig.Token), + ) if len(regUrls) > 0 { for _, regUrl := range regUrls { @@ -129,7 +143,6 @@ func (srvconfig *ServiceConfig) Export() error { if exporter == nil { panic(perrors.New(fmt.Sprintf("Registry protocol new exporter error,registry is {%v},url is {%v}", regUrl, url))) } - srvconfig.exporters = append(srvconfig.exporters, exporter) } } else { invoker := extension.GetProxyFactory(providerConfig.ProxyFactory).GetInvoker(*url) @@ -137,7 +150,6 @@ func (srvconfig *ServiceConfig) Export() error { if exporter == nil { panic(perrors.New(fmt.Sprintf("Filter protocol without registry new exporter error,url is {%v}", url))) } - srvconfig.exporters = append(srvconfig.exporters, exporter) } } diff --git a/config/service_config_test.go b/config/service_config_test.go index bfbe9134fd..8ae67533bd 100644 --- a/config/service_config_test.go +++ b/config/service_config_test.go @@ -21,15 +21,11 @@ import ( "testing" ) -import ( - "github.com/stretchr/testify/assert" -) - import ( "github.com/apache/dubbo-go/common/extension" ) -func doinit() { +func doInitProvider() { providerConfig = &ProviderConfig{ ApplicationConfig: &ApplicationConfig{ Organization: "dubbo_org", @@ -108,17 +104,64 @@ func doinit() { } } +func doInitProviderWithSingleRegistry() { + providerConfig = &ProviderConfig{ + ApplicationConfig: &ApplicationConfig{ + Organization: "dubbo_org", + Name: "dubbo", + Module: "module", + Version: "2.6.0", + Owner: "dubbo", + Environment: "test"}, + Registry: &RegistryConfig{ + Address: "mock://127.0.0.1:2181", + Username: "user1", + Password: "pwd1", + }, + Registries: map[string]*RegistryConfig{}, + Services: map[string]*ServiceConfig{ + "MockService": { + InterfaceName: "com.MockService", + Protocol: "mock", + Cluster: "failover", + Loadbalance: "random", + Retries: "3", + Group: "huadong_idc", + Version: "1.0.0", + Methods: []*MethodConfig{ + { + Name: "GetUser", + Retries: "2", + Loadbalance: "random", + Weight: 200, + }, + { + Name: "GetUser1", + Retries: "2", + Loadbalance: "random", + Weight: 200, + }, + }, + }, + }, + Protocols: map[string]*ProtocolConfig{ + "mock": { + Name: "mock", + Ip: "127.0.0.1", + Port: "20000", + }, + }, + } +} + func Test_Export(t *testing.T) { - doinit() + doInitProvider() extension.SetProtocol("registry", GetProtocol) for i := range providerConfig.Services { service := providerConfig.Services[i] service.Implement(&MockService{}) service.Export() - assert.Condition(t, func() bool { - return len(service.exporters) > 0 - }) } providerConfig = nil } diff --git a/config/testdata/consumer_config.yml b/config/testdata/consumer_config.yml index 459edd9826..9fd50bb4d3 100644 --- a/config/testdata/consumer_config.yml +++ b/config/testdata/consumer_config.yml @@ -8,7 +8,7 @@ request_timeout : "100ms" connect_timeout : "100ms" check: true # application config -application_config: +application: organization : "ikurento.com" name : "BDTService" module : "dubbogo user-info client" diff --git a/config/testdata/consumer_config_with_configcenter.yml b/config/testdata/consumer_config_with_configcenter.yml index 69df73f51f..0550cc8974 100644 --- a/config/testdata/consumer_config_with_configcenter.yml +++ b/config/testdata/consumer_config_with_configcenter.yml @@ -1,5 +1,7 @@ # dubbo client yaml configure file +application: + name: "BDTService" config_center: protocol: "mock" address: "127.0.0.1" diff --git a/examples/general/dubbo/go-client/profiles/release/client.yml b/config/testdata/consumer_config_withoutProtocol.yml similarity index 61% rename from examples/general/dubbo/go-client/profiles/release/client.yml rename to config/testdata/consumer_config_withoutProtocol.yml index 6b45f44077..5e57c7ddf6 100644 --- a/examples/general/dubbo/go-client/profiles/release/client.yml +++ b/config/testdata/consumer_config_withoutProtocol.yml @@ -1,22 +1,23 @@ # dubbo client yaml configure file +filter: "" -check: true # client -request_timeout : "3s" +request_timeout : "100ms" # connect timeout -connect_timeout : "3s" - +connect_timeout : "100ms" +check: true # application config -application_config: +application: organization : "ikurento.com" name : "BDTService" module : "dubbogo user-info client" version : "0.0.1" owner : "ZX" - environment : "release" + environment : "dev" registries : + "hangzhouzk": protocol: "zookeeper" timeout : "3s" @@ -32,33 +33,20 @@ registries : references: "UserProvider": - # 可以指定多个registry,使用逗号隔开;不指定默认向所有注册中心注册 - registry: "hangzhouzk" - protocol : "dubbo" + registry: "hangzhouzk,shanghaizk" + filter: "" + version: "1.0" + group: "as" interface : "com.ikurento.user.UserProvider" + url: "dubbo://127.0.0.1:20000/UserProvider" cluster: "failover" methods : - name: "GetUser" - retries: "3" - "UserProvider1": - registry: "hangzhouzk" - protocol: "dubbo" - version: "2.0" - interface: "com.ikurento.user.UserProvider" - cluster: "failover" - methods: - - name: "GetUser" - retries: "3" - "UserProvider2": - registry: "hangzhouzk" - protocol: "dubbo" - version: "2.0" - group: "as" - interface: "com.ikurento.user.UserProvider" - cluster: "failover" - methods: - - name: "GetUser" - retries: "3" + retries: 3 + params: + "serviceid": + "soa.com.ikurento.user.UserProvider" + "forks": 5 protocol_conf: dubbo: @@ -68,6 +56,12 @@ protocol_conf: session_timeout: "20s" pool_size: 64 pool_ttl: 600 + # gr_pool_size is recommended to be set to [cpu core number] * 100 + gr_pool_size: 1200 + # queue_len is recommended to be set to 64 or 128 + queue_len: 64 + # queue_number is recommended to be set to gr_pool_size / 20 + queue_number: 60 getty_session_param: compress_encoding: false tcp_no_delay: true @@ -79,5 +73,6 @@ protocol_conf: tcp_read_timeout: "1s" tcp_write_timeout: "5s" wait_timeout: "1s" - max_msg_len: 10240 + max_msg_len: 1024 session_name: "client" + diff --git a/config/testdata/provider_config.yml b/config/testdata/provider_config.yml index e135860c20..5cbefe0811 100644 --- a/config/testdata/provider_config.yml +++ b/config/testdata/provider_config.yml @@ -2,7 +2,7 @@ filter: "" # application config -application_config: +application: organization : "ikurento.com" name : "BDTService" module : "dubbogo user-info server" diff --git a/examples/general/dubbo/go-server/profiles/release/server.yml b/config/testdata/provider_config_withoutProtocol.yml similarity index 56% rename from examples/general/dubbo/go-server/profiles/release/server.yml rename to config/testdata/provider_config_withoutProtocol.yml index dc3bc00276..2f65868d49 100644 --- a/examples/general/dubbo/go-server/profiles/release/server.yml +++ b/config/testdata/provider_config_withoutProtocol.yml @@ -1,14 +1,14 @@ # dubbo server yaml configure file - +filter: "" # application config -application_config: +application: organization : "ikurento.com" name : "BDTService" module : "dubbogo user-info server" version : "0.0.1" owner : "ZX" - environment : "release" + environment : "dev" registries : "hangzhouzk": @@ -27,55 +27,40 @@ registries : services: "UserProvider": - # 可以指定多个registry,使用逗号隔开;不指定默认向所有注册中心注册 - registry: "hangzhouzk" - protocol : "dubbo" - # 相当于dubbo.xml中的interface + registry: "hangzhouzk,shanghaizk" + filter: "" + # equivalent to interface of dubbo.xml interface : "com.ikurento.user.UserProvider" loadbalance: "random" + version: "1.0" + group: "as" warmup: "100" cluster: "failover" methods: - name: "GetUser" - retries: "1" + retries: 1 loadbalance: "random" - "UserProvider1": - registry: "hangzhouzk" - protocol: "dubbo" - version: "2.0" - interface: "com.ikurento.user.UserProvider" - loadbalance: "random" - warmup: "100" - cluster: "failover" - methods: - - name: "GetUser" - retries: "1" - loadbalance: "random" - "UserProvider2": - registry: "hangzhouzk" - protocol: "dubbo" - version: "2.0" - group: "as" - interface: "com.ikurento.user.UserProvider" - loadbalance: "random" - warmup: "100" - cluster: "failover" - methods: - - name: "GetUser" - retries: "1" - loadbalance: "random" protocols: - "dubbo1": + "dubbo": name: "dubbo" - # ip : "127.0.0.1" - port: 20000 - + # while using dubbo protocol, ip cannot is 127.0.0.1, because client of java-dubbo will get 'connection refuse' + ip : "127.0.0.1" + port : 20000 + #- name: "jsonrpc" + # ip: "127.0.0.1" + # port: 20001 protocol_conf: dubbo: session_number: 700 session_timeout: "20s" + # gr_pool_size is recommended to be set to [cpu core number] * 10 + gr_pool_size: 120 + # queue_len is recommended to be set to 64 or 128 + queue_len: 64 + # queue_number is recommended to be set to gr_pool_size / 20 + queue_number: 6 getty_session_param: compress_encoding: false tcp_no_delay: true diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/app/version.go b/config_center/configuration_listener.go similarity index 65% rename from examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/app/version.go rename to config_center/configuration_listener.go index c6138584f1..1419bcdd0c 100644 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/app/version.go +++ b/config_center/configuration_listener.go @@ -15,8 +15,26 @@ * limitations under the License. */ -package main +package config_center -var ( - Version = "2.6.0" +import ( + "fmt" ) + +import ( + "github.com/apache/dubbo-go/remoting" +) + +type ConfigurationListener interface { + Process(*ConfigChangeEvent) +} + +type ConfigChangeEvent struct { + Key string + Value interface{} + ConfigType remoting.EventType +} + +func (c ConfigChangeEvent) String() string { + return fmt.Sprintf("ConfigChangeEvent{key = %v , value = %v , changeType = %v}", c.Key, c.Value, c.ConfigType) +} diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/app/version.go b/config_center/configurator.go similarity index 84% rename from examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/app/version.go rename to config_center/configurator.go index c6138584f1..3ba293ec60 100644 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/app/version.go +++ b/config_center/configurator.go @@ -15,8 +15,13 @@ * limitations under the License. */ -package main +package config_center -var ( - Version = "2.6.0" +import ( + "github.com/apache/dubbo-go/common" ) + +type Configurator interface { + GetUrl() *common.URL + Configure(url *common.URL) +} diff --git a/config_center/configuration_parser.go b/config_center/configurator/mock.go similarity index 57% rename from config_center/configuration_parser.go rename to config_center/configurator/mock.go index 95b122e1e7..1f03d107c8 100644 --- a/config_center/configuration_parser.go +++ b/config_center/configurator/mock.go @@ -14,29 +14,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -package config_center +package configurator import ( - "github.com/magiconair/properties" + "github.com/apache/dubbo-go/common" + "github.com/apache/dubbo-go/common/constant" + "github.com/apache/dubbo-go/config_center" ) -import ( - "github.com/apache/dubbo-go/common/logger" -) +func NewMockConfigurator(url *common.URL) config_center.Configurator { + return &mockConfigurator{configuratorUrl: url} +} -type ConfigurationParser interface { - Parse(string) (map[string]string, error) +type mockConfigurator struct { + configuratorUrl *common.URL } -//for support properties file in config center -type DefaultConfigurationParser struct{} +func (c *mockConfigurator) GetUrl() *common.URL { + return c.configuratorUrl +} -func (parser *DefaultConfigurationParser) Parse(content string) (map[string]string, error) { - properties, err := properties.LoadString(content) - if err != nil { - logger.Errorf("Parse the content {%v} in DefaultConfigurationParser error ,error message is {%v}", content, err) - return nil, err +func (c *mockConfigurator) Configure(url *common.URL) { + if cluster := c.GetUrl().GetParam(constant.CLUSTER_KEY, ""); cluster != "" { + url.SetParam(constant.CLUSTER_KEY, cluster) } - return properties.Map(), nil } diff --git a/config_center/configurator/override.go b/config_center/configurator/override.go new file mode 100644 index 0000000000..660c6ee315 --- /dev/null +++ b/config_center/configurator/override.go @@ -0,0 +1,131 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package configurator + +import ( + "strings" +) + +import ( + "github.com/dubbogo/gost/container" +) + +import ( + "github.com/apache/dubbo-go/common" + "github.com/apache/dubbo-go/common/constant" + "github.com/apache/dubbo-go/common/extension" + "github.com/apache/dubbo-go/common/utils" + "github.com/apache/dubbo-go/config_center" +) + +func init() { + extension.SetDefaultConfigurator(newConfigurator) +} +func newConfigurator(url *common.URL) config_center.Configurator { + return &overrideConfigurator{configuratorUrl: url} +} + +type overrideConfigurator struct { + configuratorUrl *common.URL +} + +func (c *overrideConfigurator) GetUrl() *common.URL { + return c.configuratorUrl +} + +func (c *overrideConfigurator) Configure(url *common.URL) { + //remove configuratorUrl some param that can not be configured + if c.configuratorUrl.GetParam(constant.ENABLED_KEY, "true") == "false" || len(c.configuratorUrl.Location) == 0 { + return + } + + //branch for version 2.7.x + apiVersion := c.configuratorUrl.GetParam(constant.CONFIG_VERSION_KEY, "") + if len(apiVersion) != 0 { + currentSide := url.GetParam(constant.SIDE_KEY, "") + configuratorSide := c.configuratorUrl.GetParam(constant.SIDE_KEY, "") + if currentSide == configuratorSide && common.DubboRole[common.CONSUMER] == currentSide && c.configuratorUrl.Port == "0" { + localIP, _ := utils.GetLocalIP() + c.configureIfMatch(localIP, url) + } else if currentSide == configuratorSide && common.DubboRole[common.PROVIDER] == currentSide && c.configuratorUrl.Port == url.Port { + c.configureIfMatch(url.Ip, url) + } + } else { + //branch for version 2.6.x and less + c.configureDeprecated(url) + } +} + +//translate from java, compatible rules in java +func (c *overrideConfigurator) configureIfMatch(host string, url *common.URL) { + if constant.ANYHOST_VALUE == c.configuratorUrl.Ip || host == c.configuratorUrl.Ip { + providers := c.configuratorUrl.GetParam(constant.OVERRIDE_PROVIDERS_KEY, "") + if len(providers) == 0 || strings.Index(providers, url.Location) >= 0 || strings.Index(providers, constant.ANYHOST_VALUE) >= 0 { + configApp := c.configuratorUrl.GetParam(constant.APPLICATION_KEY, c.configuratorUrl.Username) + currentApp := url.GetParam(constant.APPLICATION_KEY, url.Username) + if len(configApp) == 0 || constant.ANY_VALUE == configApp || configApp == currentApp { + conditionKeys := container.NewSet() + conditionKeys.Add(constant.CATEGORY_KEY) + conditionKeys.Add(constant.CHECK_KEY) + conditionKeys.Add(constant.ENABLED_KEY) + conditionKeys.Add(constant.GROUP_KEY) + conditionKeys.Add(constant.VERSION_KEY) + conditionKeys.Add(constant.APPLICATION_KEY) + conditionKeys.Add(constant.SIDE_KEY) + conditionKeys.Add(constant.CONFIG_VERSION_KEY) + conditionKeys.Add(constant.COMPATIBLE_CONFIG_KEY) + returnUrl := false + c.configuratorUrl.RangeParams(func(k, v string) bool { + value := c.configuratorUrl.GetParam(k, "") + if strings.HasPrefix(k, "~") || k == constant.APPLICATION_KEY || k == constant.SIDE_KEY { + conditionKeys.Add(k) + if len(value) != 0 && value != constant.ANY_VALUE && value != url.GetParam(strings.TrimPrefix(k, "~"), "") { + returnUrl = true + return false + } + } + return true + }) + if returnUrl { + return + } + configUrl := c.configuratorUrl.Clone() + configUrl.RemoveParams(conditionKeys) + url.SetParams(configUrl.GetParams()) + } + } + } +} + +func (c *overrideConfigurator) configureDeprecated(url *common.URL) { + // If override url has port, means it is a provider address. We want to control a specific provider with this override url, it may take effect on the specific provider instance or on consumers holding this provider instance. + if c.configuratorUrl.Port != "0" { + if url.Port == c.configuratorUrl.Port { + c.configureIfMatch(url.Ip, url) + } + } else { + // override url don't have a port, means the ip override url specify is a consumer address or 0.0.0.0 + // 1.If it is a consumer ip address, the intention is to control a specific consumer instance, it must takes effect at the consumer side, any provider received this override url should ignore; + // 2.If the ip is 0.0.0.0, this override url can be used on consumer, and also can be used on provider + if url.GetParam(constant.SIDE_KEY, "") == common.DubboRole[common.CONSUMER] { + localIP, _ := utils.GetLocalIP() + c.configureIfMatch(localIP, url) + } else { + c.configureIfMatch(constant.ANYHOST_VALUE, url) + } + } +} diff --git a/config_center/configurator/override_test.go b/config_center/configurator/override_test.go new file mode 100644 index 0000000000..a585f4217f --- /dev/null +++ b/config_center/configurator/override_test.go @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package configurator + +import ( + "context" + "testing" +) + +import ( + "github.com/stretchr/testify/assert" +) + +import ( + "github.com/apache/dubbo-go/common" + "github.com/apache/dubbo-go/common/constant" + "github.com/apache/dubbo-go/common/extension" +) + +func Test_configureVerison2p6(t *testing.T) { + url, err := common.NewURL(context.Background(), "override://0.0.0.0:0/com.xxx.mock.userProvider?group=1&version=1&cluster=failfast&application=BDTService") + assert.NoError(t, err) + configurator := extension.GetConfigurator("default", &url) + assert.Equal(t, "override", configurator.GetUrl().Protocol) + + providerUrl, err := common.NewURL(context.Background(), "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") + configurator.Configure(&providerUrl) + assert.Equal(t, "failfast", providerUrl.GetParam(constant.CLUSTER_KEY, "")) + +} +func Test_configureVerisonOverrideAddr(t *testing.T) { + url, err := common.NewURL(context.Background(), "override://0.0.0.0:0/com.xxx.mock.userProvider?group=1&version=1&cluster=failfast&application=BDTService&providerAddresses=127.0.0.2:20001|127.0.0.3:20001") + assert.NoError(t, err) + configurator := extension.GetConfigurator("default", &url) + assert.Equal(t, "override", configurator.GetUrl().Protocol) + + providerUrl, err := common.NewURL(context.Background(), "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") + configurator.Configure(&providerUrl) + assert.Equal(t, "failover", providerUrl.GetParam(constant.CLUSTER_KEY, "")) + +} +func Test_configureVerison2p6WithIp(t *testing.T) { + url, err := common.NewURL(context.Background(), "override://127.0.0.1:20001/com.xxx.mock.userProvider?group=1&version=1&cluster=failfast&application=BDTService") + assert.NoError(t, err) + configurator := extension.GetConfigurator("default", &url) + assert.Equal(t, "override", configurator.GetUrl().Protocol) + + providerUrl, err := common.NewURL(context.Background(), "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") + configurator.Configure(&providerUrl) + assert.Equal(t, "failfast", providerUrl.GetParam(constant.CLUSTER_KEY, "")) + +} + +func Test_configureVerison2p7(t *testing.T) { + url, err := common.NewURL(context.Background(), "jsonrpc://0.0.0.0:20001/com.xxx.mock.userProvider?group=1&version=1&cluster=failfast&application=BDTService&configVersion=1.0&side=provider") + assert.NoError(t, err) + configurator := extension.GetConfigurator("default", &url) + + providerUrl, err := common.NewURL(context.Background(), "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") + 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 3b829507b1..1028b26d96 100644 --- a/config_center/dynamic_configuration.go +++ b/config_center/dynamic_configuration.go @@ -20,8 +20,9 @@ package config_center import ( "time" ) + import ( - "github.com/apache/dubbo-go/remoting" + "github.com/apache/dubbo-go/config_center/parser" ) ////////////////////////////////////////// @@ -31,10 +32,10 @@ const DEFAULT_GROUP = "dubbo" const DEFAULT_CONFIG_TIMEOUT = "10s" type DynamicConfiguration interface { - Parser() ConfigurationParser - SetParser(ConfigurationParser) - AddListener(string, remoting.ConfigurationListener, ...Option) - RemoveListener(string, remoting.ConfigurationListener, ...Option) + Parser() parser.ConfigurationParser + SetParser(parser.ConfigurationParser) + AddListener(string, ConfigurationListener, ...Option) + RemoveListener(string, ConfigurationListener, ...Option) GetConfig(string, ...Option) (string, error) GetConfigs(string, ...Option) (string, error) } diff --git a/config_center/mock_dynamic_config.go b/config_center/mock_dynamic_config.go index a6c7267a4f..47b509231d 100644 --- a/config_center/mock_dynamic_config.go +++ b/config_center/mock_dynamic_config.go @@ -20,23 +20,33 @@ package config_center import ( "sync" ) + +import ( + "gopkg.in/yaml.v2" +) + import ( "github.com/apache/dubbo-go/common" + "github.com/apache/dubbo-go/common/constant" + "github.com/apache/dubbo-go/config_center/parser" "github.com/apache/dubbo-go/remoting" ) -type MockDynamicConfigurationFactory struct{} +type MockDynamicConfigurationFactory struct { + Content string +} var ( once sync.Once - dynamicConfiguration *mockDynamicConfiguration + dynamicConfiguration *MockDynamicConfiguration ) func (f *MockDynamicConfigurationFactory) GetDynamicConfiguration(url *common.URL) (DynamicConfiguration, error) { var err error once.Do(func() { - dynamicConfiguration = &mockDynamicConfiguration{} - dynamicConfiguration.SetParser(&DefaultConfigurationParser{}) + dynamicConfiguration = &MockDynamicConfiguration{listener: map[string]ConfigurationListener{}} + dynamicConfiguration.SetParser(&parser.DefaultConfigurationParser{}) + dynamicConfiguration.content = ` dubbo.consumer.request_timeout=5s dubbo.consumer.connect_timeout=5s @@ -62,34 +72,81 @@ func (f *MockDynamicConfigurationFactory) GetDynamicConfiguration(url *common.UR dubbo.protocols.jsonrpc1.port=20001 ` }) + if len(f.Content) != 0 { + dynamicConfiguration.content = f.Content + } return dynamicConfiguration, err } -type mockDynamicConfiguration struct { - parser ConfigurationParser - content string +type MockDynamicConfiguration struct { + parser parser.ConfigurationParser + content string + listener map[string]ConfigurationListener } -func (c *mockDynamicConfiguration) AddListener(key string, listener remoting.ConfigurationListener, opions ...Option) { +func (c *MockDynamicConfiguration) AddListener(key string, listener ConfigurationListener, opions ...Option) { + c.listener[key] = listener } -func (c *mockDynamicConfiguration) RemoveListener(key string, listener remoting.ConfigurationListener, opions ...Option) { +func (c *MockDynamicConfiguration) RemoveListener(key string, listener ConfigurationListener, opions ...Option) { } -func (c *mockDynamicConfiguration) GetConfig(key string, opts ...Option) (string, error) { +func (c *MockDynamicConfiguration) GetConfig(key string, opts ...Option) (string, error) { return c.content, nil } //For zookeeper, getConfig and getConfigs have the same meaning. -func (c *mockDynamicConfiguration) GetConfigs(key string, opts ...Option) (string, error) { +func (c *MockDynamicConfiguration) GetConfigs(key string, opts ...Option) (string, error) { return c.GetConfig(key, opts...) } -func (c *mockDynamicConfiguration) Parser() ConfigurationParser { +func (c *MockDynamicConfiguration) Parser() parser.ConfigurationParser { return c.parser } -func (c *mockDynamicConfiguration) SetParser(p ConfigurationParser) { +func (c *MockDynamicConfiguration) SetParser(p parser.ConfigurationParser) { c.parser = p } + +func (c *MockDynamicConfiguration) MockServiceConfigEvent() { + config := &parser.ConfiguratorConfig{ + ConfigVersion: "2.7.1", + Scope: parser.GeneralType, + Key: "org.apache.dubbo-go.mockService", + Enabled: true, + Configs: []parser.ConfigItem{ + {Type: parser.GeneralType, + Enabled: true, + Addresses: []string{"0.0.0.0"}, + Services: []string{"org.apache.dubbo-go.mockService"}, + Side: "provider", + Parameters: map[string]string{"cluster": "mock1"}, + }, + }, + } + value, _ := yaml.Marshal(config) + key := "group*org.apache.dubbo-go.mockService:1.0.0" + constant.CONFIGURATORS_SUFFIX + c.listener[key].Process(&ConfigChangeEvent{Key: key, Value: string(value), ConfigType: remoting.EventTypeAdd}) +} + +func (c *MockDynamicConfiguration) MockApplicationConfigEvent() { + config := &parser.ConfiguratorConfig{ + ConfigVersion: "2.7.1", + Scope: parser.ScopeApplication, + Key: "org.apache.dubbo-go.mockService", + Enabled: true, + Configs: []parser.ConfigItem{ + {Type: parser.ScopeApplication, + Enabled: true, + Addresses: []string{"0.0.0.0"}, + Services: []string{"org.apache.dubbo-go.mockService"}, + Side: "provider", + Parameters: map[string]string{"cluster": "mock1"}, + }, + }, + } + value, _ := yaml.Marshal(config) + key := "test-application" + constant.CONFIGURATORS_SUFFIX + c.listener[key].Process(&ConfigChangeEvent{Key: key, Value: string(value), ConfigType: remoting.EventTypeAdd}) +} diff --git a/config_center/parser/configuration_parser.go b/config_center/parser/configuration_parser.go new file mode 100644 index 0000000000..1ce6594017 --- /dev/null +++ b/config_center/parser/configuration_parser.go @@ -0,0 +1,251 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package parser + +import ( + "context" + "strconv" + "strings" +) + +import ( + "github.com/magiconair/properties" + perrors "github.com/pkg/errors" + "gopkg.in/yaml.v2" +) + +import ( + "github.com/apache/dubbo-go/common" + "github.com/apache/dubbo-go/common/constant" + "github.com/apache/dubbo-go/common/logger" +) + +const ( + ScopeApplication = "application" + GeneralType = "general" +) + +type ConfigurationParser interface { + Parse(string) (map[string]string, error) + ParseToUrls(content string) ([]*common.URL, error) +} + +//for support properties file in config center +type DefaultConfigurationParser struct{} + +type ConfiguratorConfig struct { + ConfigVersion string `yaml:"configVersion"` + Scope string `yaml:"scope"` + Key string `yaml:"key"` + Enabled bool `yaml:"enabled"` + Configs []ConfigItem `yaml:"configs"` +} + +type ConfigItem struct { + Type string `yaml:"type"` + Enabled bool `yaml:"enabled"` + Addresses []string `yaml:"addresses"` + ProviderAddresses []string `yaml:"providerAddresses"` + Services []string `yaml:"services"` + Applications []string `yaml:"applications"` + Parameters map[string]string `yaml:"parameters"` + Side string `yaml:"side"` +} + +func (parser *DefaultConfigurationParser) Parse(content string) (map[string]string, error) { + properties, err := properties.LoadString(content) + if err != nil { + logger.Errorf("Parse the content {%v} in DefaultConfigurationParser error ,error message is {%v}", content, err) + return nil, err + } + return properties.Map(), nil +} + +func (parser *DefaultConfigurationParser) ParseToUrls(content string) ([]*common.URL, error) { + config := ConfiguratorConfig{} + if err := yaml.Unmarshal([]byte(content), &config); err != nil { + return nil, err + } + scope := config.Scope + items := config.Configs + var allUrls []*common.URL + if scope == ScopeApplication { + for _, v := range items { + urls, err := appItemToUrls(v, config) + if err != nil { + return nil, err + } + allUrls = append(allUrls, urls...) + } + } else { + for _, v := range items { + urls, err := serviceItemToUrls(v, config) + if err != nil { + return nil, err + } + allUrls = append(allUrls, urls...) + } + } + return allUrls, nil +} +func serviceItemToUrls(item ConfigItem, config ConfiguratorConfig) ([]*common.URL, error) { + var addresses = item.Addresses + if len(addresses) == 0 { + addresses = append(addresses, constant.ANYHOST_VALUE) + } + var urls []*common.URL + for _, v := range addresses { + urlStr := constant.OVERRIDE_PROTOCOL + "://" + v + "/" + serviceStr, err := getServiceString(config.Key) + if err != nil { + return nil, perrors.WithStack(err) + } + urlStr = urlStr + serviceStr + paramStr, err := getParamString(item) + if err != nil { + return nil, perrors.WithStack(err) + } + urlStr = urlStr + paramStr + urlStr = urlStr + getEnabledString(item, config) + urlStr = urlStr + "&category=" + urlStr = urlStr + constant.DYNAMIC_CONFIGURATORS_CATEGORY + urlStr = urlStr + "&configVersion=" + urlStr = urlStr + config.ConfigVersion + apps := item.Applications + if len(apps) > 0 { + for _, v := range apps { + newUrlStr := urlStr + newUrlStr = newUrlStr + "&application" + newUrlStr = newUrlStr + v + url, err := common.NewURL(context.Background(), newUrlStr) + if err != nil { + perrors.WithStack(err) + } + urls = append(urls, &url) + } + } else { + url, err := common.NewURL(context.Background(), urlStr) + if err != nil { + perrors.WithStack(err) + } + urls = append(urls, &url) + } + } + return urls, nil +} +func appItemToUrls(item ConfigItem, config ConfiguratorConfig) ([]*common.URL, error) { + var addresses = item.Addresses + if len(addresses) == 0 { + addresses = append(addresses, constant.ANYHOST_VALUE) + } + var urls []*common.URL + for _, v := range addresses { + urlStr := constant.OVERRIDE_PROTOCOL + "://" + v + "/" + services := item.Services + if len(services) == 0 { + services = append(services, constant.ANY_VALUE) + } + for _, vs := range services { + serviceStr, err := getServiceString(vs) + if err != nil { + return nil, perrors.WithStack(err) + } + urlStr = urlStr + serviceStr + paramStr, err := getParamString(item) + if err != nil { + return nil, perrors.WithStack(err) + } + urlStr = urlStr + paramStr + urlStr = urlStr + "&application=" + urlStr = urlStr + config.Key + urlStr = urlStr + getEnabledString(item, config) + urlStr = urlStr + "&category=" + urlStr = urlStr + constant.APP_DYNAMIC_CONFIGURATORS_CATEGORY + urlStr = urlStr + "&configVersion=" + urlStr = urlStr + config.ConfigVersion + url, err := common.NewURL(context.Background(), urlStr) + if err != nil { + return nil, perrors.WithStack(err) + } + urls = append(urls, &url) + } + } + return urls, nil +} + +func getServiceString(service string) (string, error) { + if len(service) == 0 { + return "", perrors.New("service field in configuration is null.") + } + var serviceStr string + i := strings.Index(service, "/") + if i > 0 { + serviceStr = serviceStr + "group=" + serviceStr = serviceStr + service[0:i] + serviceStr = serviceStr + "&" + service = service[i+1:] + } + j := strings.Index(service, ":") + if j > 0 { + serviceStr = serviceStr + "version=" + serviceStr = serviceStr + service[j+1:] + serviceStr = serviceStr + "&" + service = service[0:j] + } + serviceStr = service + "?" + serviceStr + return serviceStr, nil +} + +func getParamString(item ConfigItem) (string, error) { + var retStr string + retStr = retStr + "category=" + retStr = retStr + constant.DYNAMIC_CONFIGURATORS_CATEGORY + if len(item.Side) > 0 { + retStr = retStr + "&side=" + retStr = retStr + item.Side + } + params := item.Parameters + if len(params) <= 0 { + return "", perrors.New("Invalid configurator rule, please specify at least one parameter " + + "you want to change in the rule.") + } + for k, v := range params { + retStr = retStr + "&" + retStr = retStr + k + retStr = retStr + "=" + retStr = retStr + v + } + + if len(item.ProviderAddresses) >= 0 { + retStr = retStr + "&" + retStr = retStr + constant.OVERRIDE_PROVIDERS_KEY + retStr = retStr + "=" + retStr = retStr + strings.Join(item.ProviderAddresses, ",") + } + + return retStr, nil +} +func getEnabledString(item ConfigItem, config ConfiguratorConfig) string { + retStr := "&enabled=" + if len(item.Type) == 0 || item.Type == GeneralType { + retStr = retStr + strconv.FormatBool(config.Enabled) + } else { + retStr = retStr + strconv.FormatBool(item.Enabled) + } + return retStr +} diff --git a/config_center/configuration_parser_test.go b/config_center/parser/configuration_parser_test.go similarity index 98% rename from config_center/configuration_parser_test.go rename to config_center/parser/configuration_parser_test.go index 4a67d42304..7a59ea9b48 100644 --- a/config_center/configuration_parser_test.go +++ b/config_center/parser/configuration_parser_test.go @@ -15,7 +15,7 @@ * limitations under the License. */ -package config_center +package parser import ( "testing" diff --git a/config_center/zookeeper/factory.go b/config_center/zookeeper/factory.go index c1c7e27b14..611f4b9785 100644 --- a/config_center/zookeeper/factory.go +++ b/config_center/zookeeper/factory.go @@ -20,10 +20,12 @@ package zookeeper import ( "sync" ) + import ( "github.com/apache/dubbo-go/common" "github.com/apache/dubbo-go/common/extension" "github.com/apache/dubbo-go/config_center" + "github.com/apache/dubbo-go/config_center/parser" ) func init() { @@ -44,7 +46,7 @@ func (f *zookeeperDynamicConfigurationFactory) GetDynamicConfiguration(url *comm if err != nil { return nil, err } - dynamicConfiguration.SetParser(&config_center.DefaultConfigurationParser{}) + dynamicConfiguration.SetParser(&parser.DefaultConfigurationParser{}) return dynamicConfiguration, err } diff --git a/config_center/zookeeper/impl.go b/config_center/zookeeper/impl.go index f2827b2bb6..84e4b54e23 100644 --- a/config_center/zookeeper/impl.go +++ b/config_center/zookeeper/impl.go @@ -22,16 +22,18 @@ import ( "sync" "time" ) + import ( perrors "github.com/pkg/errors" "github.com/samuel/go-zookeeper/zk" ) + import ( "github.com/apache/dubbo-go/common" "github.com/apache/dubbo-go/common/constant" "github.com/apache/dubbo-go/common/logger" "github.com/apache/dubbo-go/config_center" - "github.com/apache/dubbo-go/remoting" + "github.com/apache/dubbo-go/config_center/parser" "github.com/apache/dubbo-go/remoting/zookeeper" ) @@ -48,7 +50,7 @@ type zookeeperDynamicConfiguration struct { listenerLock sync.Mutex listener *zookeeper.ZkEventListener cacheListener *CacheListener - parser config_center.ConfigurationParser + parser parser.ConfigurationParser } func newZookeeperDynamicConfiguration(url *common.URL) (*zookeeperDynamicConfiguration, error) { @@ -99,11 +101,11 @@ func newMockZookeeperDynamicConfiguration(url *common.URL, opts ...zookeeper.Opt } -func (c *zookeeperDynamicConfiguration) AddListener(key string, listener remoting.ConfigurationListener, opions ...config_center.Option) { +func (c *zookeeperDynamicConfiguration) AddListener(key string, listener config_center.ConfigurationListener, opions ...config_center.Option) { c.cacheListener.AddListener(key, listener) } -func (c *zookeeperDynamicConfiguration) RemoveListener(key string, listener remoting.ConfigurationListener, opions ...config_center.Option) { +func (c *zookeeperDynamicConfiguration) RemoveListener(key string, listener config_center.ConfigurationListener, opions ...config_center.Option) { c.cacheListener.RemoveListener(key, listener) } @@ -143,10 +145,10 @@ func (c *zookeeperDynamicConfiguration) GetConfigs(key string, opts ...config_ce return c.GetConfig(key, opts...) } -func (c *zookeeperDynamicConfiguration) Parser() config_center.ConfigurationParser { +func (c *zookeeperDynamicConfiguration) Parser() parser.ConfigurationParser { return c.parser } -func (c *zookeeperDynamicConfiguration) SetParser(p config_center.ConfigurationParser) { +func (c *zookeeperDynamicConfiguration) SetParser(p parser.ConfigurationParser) { c.parser = p } diff --git a/config_center/zookeeper/impl_test.go b/config_center/zookeeper/impl_test.go index 26b899e82d..2f620457f7 100644 --- a/config_center/zookeeper/impl_test.go +++ b/config_center/zookeeper/impl_test.go @@ -31,13 +31,13 @@ import ( import ( "github.com/apache/dubbo-go/common" "github.com/apache/dubbo-go/config_center" - "github.com/apache/dubbo-go/remoting" + "github.com/apache/dubbo-go/config_center/parser" ) func initZkData(group string, t *testing.T) (*zk.TestCluster, *zookeeperDynamicConfiguration) { regurl, _ := common.NewURL(context.TODO(), "registry://127.0.0.1:1111") ts, reg, err := newMockZookeeperDynamicConfiguration(®url) - reg.SetParser(&config_center.DefaultConfigurationParser{}) + reg.SetParser(&parser.DefaultConfigurationParser{}) assert.NoError(t, err) @@ -161,7 +161,7 @@ type mockDataListener struct { event string } -func (l *mockDataListener) Process(configType *remoting.ConfigChangeEvent) { +func (l *mockDataListener) Process(configType *config_center.ConfigChangeEvent) { fmt.Println("process!!!!!") l.wg.Done() l.event = configType.Key diff --git a/config_center/zookeeper/listener.go b/config_center/zookeeper/listener.go index c79c05c9bc..7128b6f5a3 100644 --- a/config_center/zookeeper/listener.go +++ b/config_center/zookeeper/listener.go @@ -21,7 +21,9 @@ import ( "strings" "sync" ) + import ( + "github.com/apache/dubbo-go/config_center" "github.com/apache/dubbo-go/remoting" ) @@ -33,21 +35,21 @@ type CacheListener struct { func NewCacheListener(rootPath string) *CacheListener { return &CacheListener{rootPath: rootPath} } -func (l *CacheListener) AddListener(key string, listener remoting.ConfigurationListener) { +func (l *CacheListener) AddListener(key string, listener config_center.ConfigurationListener) { // reference from https://stackoverflow.com/questions/34018908/golang-why-dont-we-have-a-set-datastructure // make a map[your type]struct{} like set in java - listeners, loaded := l.keyListeners.LoadOrStore(key, map[remoting.ConfigurationListener]struct{}{listener: struct{}{}}) + listeners, loaded := l.keyListeners.LoadOrStore(key, map[config_center.ConfigurationListener]struct{}{listener: struct{}{}}) if loaded { - listeners.(map[remoting.ConfigurationListener]struct{})[listener] = struct{}{} + listeners.(map[config_center.ConfigurationListener]struct{})[listener] = struct{}{} l.keyListeners.Store(key, listeners) } } -func (l *CacheListener) RemoveListener(key string, listener remoting.ConfigurationListener) { +func (l *CacheListener) RemoveListener(key string, listener config_center.ConfigurationListener) { listeners, loaded := l.keyListeners.Load(key) if loaded { - delete(listeners.(map[remoting.ConfigurationListener]struct{}), listener) + delete(listeners.(map[config_center.ConfigurationListener]struct{}), listener) } } @@ -59,8 +61,8 @@ func (l *CacheListener) DataChange(event remoting.Event) bool { key := l.pathToKey(event.Path) if key != "" { if listeners, ok := l.keyListeners.Load(key); ok { - for listener := range listeners.(map[remoting.ConfigurationListener]struct{}) { - listener.Process(&remoting.ConfigChangeEvent{Key: key, Value: event.Content, ConfigType: event.Action}) + for listener := range listeners.(map[config_center.ConfigurationListener]struct{}) { + listener.Process(&config_center.ConfigChangeEvent{Key: key, Value: event.Content, ConfigType: event.Action}) } return true } diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/app/client.go b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/app/client.go deleted file mode 100644 index 44ffbd98f6..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/app/client.go +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -import ( - "context" - "fmt" - "os" - "os/signal" - "syscall" - "time" -) - -import ( - hessian "github.com/apache/dubbo-go-hessian2" -) - -import ( - "github.com/apache/dubbo-go/common/logger" - _ "github.com/apache/dubbo-go/common/proxy/proxy_factory" - "github.com/apache/dubbo-go/config" - _ "github.com/apache/dubbo-go/protocol/dubbo" - _ "github.com/apache/dubbo-go/registry/protocol" - - _ "github.com/apache/dubbo-go/filter/impl" - - _ "github.com/apache/dubbo-go/cluster/cluster_impl" - _ "github.com/apache/dubbo-go/cluster/loadbalance" - _ "github.com/apache/dubbo-go/config_center/zookeeper" - _ "github.com/apache/dubbo-go/registry/zookeeper" -) - -var ( - survivalTimeout int = 10e9 -) - -// they are necessary: -// export CONF_CONSUMER_FILE_PATH="xxx" -// export APP_LOG_CONF_FILE="xxx" -func main() { - - hessian.RegisterJavaEnum(Gender(MAN)) - hessian.RegisterJavaEnum(Gender(WOMAN)) - hessian.RegisterPOJO(&User{}) - - config.Load() - - println("\n\n\necho") - res, err := userProvider.Echo(context.TODO(), "OK") - if err != nil { - panic(err) - } - println("res: %v\n", res) - - time.Sleep(3e9) - - println("\n\n\nstart to test dubbo") - user := &User{} - err = userProvider.GetUser(context.TODO(), []interface{}{"A003"}, user) - if err != nil { - panic(err) - } - println("response result: %v", user) - - println("\n\n\nstart to test dubbo - GetUser0") - ret, err := userProvider.GetUser0("A003", "Moorse") - if err != nil { - panic(err) - } - println("response result: %v", ret) - - println("\n\n\nstart to test dubbo - GetUsers") - ret1, err := userProvider.GetUsers([]interface{}{[]interface{}{"A002", "A003"}}) - if err != nil { - panic(err) - } - println("response result: %v", ret1) - - println("\n\n\nstart to test dubbo - getUser") - user = &User{} - var i int32 = 1 - err = userProvider.GetUser2(context.TODO(), []interface{}{i}, user) - if err != nil { - panic(err) - } - println("response result: %v", user) - - println("\n\n\nstart to test dubbo - GetUser3") - err = userProvider.GetUser3() - if err != nil { - panic(err) - } - println("succ!") - - println("\n\n\nstart to test dubbo - getErr") - user = &User{} - err = userProvider.GetErr(context.TODO(), []interface{}{"A003"}, user) - if err != nil { - println("getErr - error: %v", err) - } - - println("\n\n\nstart to test dubbo illegal method") - err = userProvider.GetUser1(context.TODO(), []interface{}{"A003"}, user) - if err != nil { - panic(err) - } - - initSignal() -} - -func initSignal() { - signals := make(chan os.Signal, 1) - // It is not possible to block SIGKILL or syscall.SIGSTOP - signal.Notify(signals, os.Interrupt, os.Kill, syscall.SIGHUP, - syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT) - for { - sig := <-signals - logger.Infof("get signal %s", sig.String()) - switch sig { - case syscall.SIGHUP: - // reload() - default: - time.AfterFunc(time.Duration(survivalTimeout)*time.Second, func() { - logger.Warnf("app exit now by force...") - os.Exit(1) - }) - - // The program exits normally or timeout forcibly exits. - fmt.Println("app exit now...") - return - } - } -} - -func println(format string, args ...interface{}) { - fmt.Printf("\033[32;40m"+format+"\033[0m\n", args...) -} diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/app/user.go b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/app/user.go deleted file mode 100644 index 5bddf1e19f..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/app/user.go +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -import ( - "context" - "fmt" - "strconv" - "time" -) - -import ( - hessian "github.com/apache/dubbo-go-hessian2" -) - -import ( - "github.com/apache/dubbo-go/config" -) - -type Gender hessian.JavaEnum - -var userProvider = new(UserProvider) - -func init() { - config.SetConsumerService(userProvider) -} - -const ( - MAN hessian.JavaEnum = iota - WOMAN -) - -var genderName = map[hessian.JavaEnum]string{ - MAN: "MAN", - WOMAN: "WOMAN", -} - -var genderValue = map[string]hessian.JavaEnum{ - "MAN": MAN, - "WOMAN": WOMAN, -} - -func (g Gender) JavaClassName() string { - return "com.ikurento.user.Gender" -} - -func (g Gender) String() string { - s, ok := genderName[hessian.JavaEnum(g)] - if ok { - return s - } - - return strconv.Itoa(int(g)) -} - -func (g Gender) EnumValue(s string) hessian.JavaEnum { - v, ok := genderValue[s] - if ok { - return v - } - - return hessian.InvalidJavaEnum -} - -type User struct { - // !!! Cannot define lowercase names of variable - Id string - Name string - Age int32 - Time time.Time - Sex Gender // notice: java enum Object <--> go string -} - -func (u User) String() string { - return fmt.Sprintf( - "User{Id:%s, Name:%s, Age:%d, Time:%s, Sex:%s}", - u.Id, u.Name, u.Age, u.Time, u.Sex, - ) -} - -func (User) JavaClassName() string { - return "com.ikurento.user.User" -} - -type UserProvider struct { - GetUsers func(req []interface{}) ([]interface{}, error) - GetErr func(ctx context.Context, req []interface{}, rsp *User) error - GetUser func(ctx context.Context, req []interface{}, rsp *User) error - GetUser0 func(id string, name string) (User, error) - GetUser1 func(ctx context.Context, req []interface{}, rsp *User) error - GetUser2 func(ctx context.Context, req []interface{}, rsp *User) error `dubbo:"getUser"` - GetUser3 func() error - Echo func(ctx context.Context, req interface{}) (interface{}, error) // Echo represent EchoFilter will be used -} - -func (u *UserProvider) Reference() string { - return "UserProvider" -} diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/app/version.go b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/app/version.go deleted file mode 100644 index c6138584f1..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/app/version.go +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -var ( - Version = "2.6.0" -) diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/bin/load.sh b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/bin/load.sh deleted file mode 100644 index ffa240b29d..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/bin/load.sh +++ /dev/null @@ -1,203 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -APP_NAME="APPLICATION_NAME" -APP_ARGS="" -SLEEP_INTERVAL=5 -MAX_LIFETIME=4000 - -PROJECT_HOME="" -OS_NAME=`uname` -if [[ ${OS_NAME} != "Windows" ]]; then - PROJECT_HOME=`pwd` - PROJECT_HOME=${PROJECT_HOME}"/" -else - APP_NAME="APPLICATION_NAME.exe" -fi - -export CONF_CONSUMER_FILE_PATH=${PROJECT_HOME}"TARGET_CONF_FILE" -export APP_LOG_CONF_FILE=${PROJECT_HOME}"TARGET_LOG_CONF_FILE" -# export GOTRACEBACK=system -# export GODEBUG=gctrace=1 - -usage() { - echo "Usage: $0 start [conf suffix]" - echo " $0 stop" - echo " $0 term" - echo " $0 restart" - echo " $0 list" - echo " $0 monitor" - echo " $0 crontab" - exit -} - -start() { - arg=$1 - if [ "$arg" = "" ];then - echo "No registry type! Default client.yml!" - else - export CONF_CONSUMER_FILE_PATH=${CONF_CONSUMER_FILE_PATH//\.yml/\_$arg\.yml} - fi - if [ ! -f "${CONF_CONSUMER_FILE_PATH}" ];then - echo $CONF_CONSUMER_FILE_PATH" is not existing!" - return - fi - APP_LOG_PATH=${PROJECT_HOME}"logs/" - mkdir -p ${APP_LOG_PATH} - APP_BIN=${PROJECT_HOME}sbin/${APP_NAME} - chmod u+x ${APP_BIN} - # CMD="nohup ${APP_BIN} ${APP_ARGS} >>${APP_NAME}.nohup.out 2>&1 &" - CMD="${APP_BIN}" - eval ${CMD} - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $2}'` - if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $1}'` - fi - CUR=`date +%FT%T` - if [ "${PID}" != "" ]; then - for p in ${PID} - do - echo "start ${APP_NAME} ( pid =" ${p} ") at " ${CUR} - done - fi -} - -stop() { - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $2}'` - if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $1}'` - fi - if [ "${PID}" != "" ]; - then - for ps in ${PID} - do - echo "kill -SIGINT ${APP_NAME} ( pid =" ${ps} ")" - kill -2 ${ps} - done - fi -} - - -term() { - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $2}'` - if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $1}'` - fi - if [ "${PID}" != "" ]; - then - for ps in ${PID} - do - echo "kill -9 ${APP_NAME} ( pid =" ${ps} ")" - kill -9 ${ps} - done - fi -} - -list() { - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{printf("%s,%s,%s,%s\n", $1, $2, $9, $10)}'` - if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{printf("%s,%s,%s,%s,%s\n", $1, $4, $6, $7, $8)}'` - fi - - if [ "${PID}" != "" ]; then - echo "list ${APP_NAME}" - - if [[ ${OS_NAME} == "Linux" || ${OS_NAME} == "Darwin" ]]; then - echo "index: user, pid, start, duration" - else - echo "index: PID, WINPID, UID, STIME, COMMAND" - fi - idx=0 - for ps in ${PID} - do - echo "${idx}: ${ps}" - ((idx ++)) - done - fi -} - -monitor() { - idx=0 - while true; do - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $2}'` - if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $1}'` - fi - if [[ "${PID}" == "" ]]; then - start - idx=0 - fi - - ((LIFE=idx*${SLEEP_INTERVAL})) - echo "${APP_NAME} ( pid = " ${PID} ") has been working in normal state for " $LIFE " seconds." - ((idx ++)) - sleep ${SLEEP_INTERVAL} - done -} - -crontab() { - idx=0 - while true; do - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $2}'` - if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $1}'` - fi - if [[ "${PID}" == "" ]]; then - start - idx=0 - fi - - ((LIFE=idx*${SLEEP_INTERVAL})) - echo "${APP_NAME} ( pid = " ${PID} ") has been working in normal state for " $LIFE " seconds." - ((idx ++)) - sleep ${SLEEP_INTERVAL} - if [[ ${LIFE} -gt ${MAX_LIFETIME} ]]; then - kill -9 ${PID} - fi - done -} - -opt=$1 -case C"$opt" in - Cstart) - start $2 - ;; - Cstop) - stop - ;; - Cterm) - term - ;; - Crestart) - term - start $2 - ;; - Clist) - list - ;; - Cmonitor) - monitor - ;; - Ccrontab) - crontab - ;; - C*) - usage - ;; -esac - diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/common/app.properties b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/common/app.properties deleted file mode 100644 index e10868f4d2..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/common/app.properties +++ /dev/null @@ -1,23 +0,0 @@ -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -export TARGET_EXEC_NAME="user_info_client" -# BUILD_PACKAGE="dubbogo-examples/user-info/client/app" -export BUILD_PACKAGE="app" - -export TARGET_CONF_FILE="conf/client.yml" -export TARGET_LOG_CONF_FILE="conf/log.yml" diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/common/build.sh b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/common/build.sh deleted file mode 100644 index c9a9e87c73..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/common/build.sh +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -rm -rf target/ - -PROJECT_HOME=`pwd` -TARGET_FOLDER=${PROJECT_HOME}/target/${GOOS} - -TARGET_SBIN_NAME=${TARGET_EXEC_NAME} -version=`cat app/version.go | grep Version | grep -v "Apache" | awk -F '=' '{print $2}' | awk -F '"' '{print $2}'` -if [[ ${GOOS} == "windows" ]]; then - TARGET_SBIN_NAME=${TARGET_SBIN_NAME}.exe -fi -TARGET_NAME=${TARGET_FOLDER}/${TARGET_SBIN_NAME} -if [[ $PROFILE == "dev" || $PROFILE == "test" ]]; then - # GFLAGS=-gcflags "-N -l" -race -x -v # -x会把go build的详细过程输出 - # GFLAGS=-gcflags "-N -l" -race -v - # GFLAGS="-gcflags \"-N -l\" -v" - cd ${BUILD_PACKAGE} && GOOS=$GOOS GOARCH=$GOARCH go build -gcflags "-N -l" -x -v -i -o ${TARGET_NAME} && cd - -else - # -s去掉符号表(然后panic时候的stack trace就没有任何文件名/行号信息了,这个等价于普通C/C++程序被strip的效果), - # -w去掉DWARF调试信息,得到的程序就不能用gdb调试了。-s和-w也可以分开使用,一般来说如果不打算用gdb调试, - # -w基本没啥损失。-s的损失就有点大了。 - cd ${BUILD_PACKAGE} && GOOS=$GOOS GOARCH=$GOARCH go build -ldflags "-w" -x -v -i -o ${TARGET_NAME} && cd - -fi - -TAR_NAME=${TARGET_EXEC_NAME}-${version}-`date "+%Y%m%d-%H%M"`-${PROFILE} - -mkdir -p ${TARGET_FOLDER}/${TAR_NAME} - -SBIN_DIR=${TARGET_FOLDER}/${TAR_NAME}/sbin -BIN_DIR=${TARGET_FOLDER}/${TAR_NAME} -CONF_DIR=${TARGET_FOLDER}/${TAR_NAME}/conf - -mkdir -p ${SBIN_DIR} -mkdir -p ${CONF_DIR} - -mv ${TARGET_NAME} ${SBIN_DIR} -cp -r assembly/bin ${BIN_DIR} -cd ${BIN_DIR}/bin/ && mv load.sh load_${TARGET_EXEC_NAME}.sh && cd - - -platform=$(uname) -# modify APPLICATION_NAME -if [ ${platform} == "Darwin" ]; then - sed -i "" "s~APPLICATION_NAME~${TARGET_EXEC_NAME}~g" ${BIN_DIR}/bin/* -else - sed -i "s~APPLICATION_NAME~${TARGET_EXEC_NAME}~g" ${BIN_DIR}/bin/* -fi - -# modify TARGET_CONF_FILE -if [ ${platform} == "Darwin" ]; then - sed -i "" "s~TARGET_CONF_FILE~${TARGET_CONF_FILE}~g" ${BIN_DIR}/bin/* -else - sed -i "s~TARGET_CONF_FILE~${TARGET_CONF_FILE}~g" ${BIN_DIR}/bin/* -fi - -# modify TARGET_LOG_CONF_FILE -if [ ${platform} == "Darwin" ]; then - sed -i "" "s~TARGET_LOG_CONF_FILE~${TARGET_LOG_CONF_FILE}~g" ${BIN_DIR}/bin/* -else - sed -i "s~TARGET_LOG_CONF_FILE~${TARGET_LOG_CONF_FILE}~g" ${BIN_DIR}/bin/* -fi - -cp -r profiles/${PROFILE}/* ${CONF_DIR} - -cd ${TARGET_FOLDER} - -tar czf ${TAR_NAME}.tar.gz ${TAR_NAME}/* - diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/linux/dev.sh b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/linux/dev.sh deleted file mode 100644 index eada737c8d..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/linux/dev.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=linux -export GOARCH=amd64 - -export PROFILE="dev" - -PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then - . ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then - sh ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/linux/release.sh b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/linux/release.sh deleted file mode 100644 index 10eb3d73f8..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/linux/release.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=linux -export GOARCH=amd64 - -export PROFILE="release" -export PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then - . ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then - sh ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/linux/test.sh b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/linux/test.sh deleted file mode 100644 index 78b650c0d4..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/linux/test.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=linux -export GOARCH=amd64 - -export PROFILE="test" -export PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then - . ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then - sh ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/mac/dev.sh b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/mac/dev.sh deleted file mode 100644 index c828476990..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/mac/dev.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=darwin -export GOARCH=amd64 - -export PROFILE="dev" - -export PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then - . ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then - sh ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/mac/release.sh b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/mac/release.sh deleted file mode 100644 index 91c2dfee79..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/mac/release.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=darwin -export GOARCH=amd64 - -export PROFILE="release" -export PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then - . ${PROJECT_HOME}/assembly/common/app.properties -fi - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then - sh ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/mac/test.sh b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/mac/test.sh deleted file mode 100644 index a7853f5e2d..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/mac/test.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -set -e - -export GOOS=darwin -export GOARCH=amd64 - -export PROFILE="test" -export PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then - . ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then - sh ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/windows/dev.sh b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/windows/dev.sh deleted file mode 100644 index 10a3866c0f..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/windows/dev.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=linux -export GOARCH=amd64 - -export PROFILE="dev" -PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then - . ${PROJECT_HOME}/assembly/common/app.properties -fi - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then - sh ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/windows/release.sh b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/windows/release.sh deleted file mode 100644 index 21af573fa3..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/windows/release.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=windows -export GOARCH=amd64 - -export PROFILE="release" -export PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then - . ${PROJECT_HOME}/assembly/common/app.properties -fi - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then - sh ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/windows/test.sh b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/windows/test.sh deleted file mode 100644 index 2104da8b59..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/assembly/windows/test.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=windows -export GOARCH=amd64 - -export PROFILE="test" -export PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then - . ${PROJECT_HOME}/assembly/common/app.properties -fi - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then - sh ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/profiles/dev/log.yml b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/profiles/dev/log.yml deleted file mode 100644 index 59fa4279ad..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/profiles/dev/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "debug" -development: true -disableCaller: false -disableStacktrace: false -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/profiles/release/client.yml b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/profiles/release/client.yml deleted file mode 100644 index 48b7b0ce95..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/profiles/release/client.yml +++ /dev/null @@ -1,38 +0,0 @@ -# dubbo client yaml configure file - -config_center: - protocol: "zookeeper" - address: "127.0.0.1:2181" - group: "dubbo" - config_file: "dubbo.client.properties" - -references: - "UserProvider": - protocol : "dubbo" - interface : "com.ikurento.user.UserProvider" - cluster: "failover" - methods : - - name: "GetUser" - retries: "3" - -protocol_conf: - dubbo: - reconnect_interval: 0 - connection_number: 2 - heartbeat_period: "5s" - session_timeout: "20s" - pool_size: 64 - pool_ttl: 600 - getty_session_param: - compress_encoding: false - tcp_no_delay: true - tcp_keep_alive: true - keep_alive_period: "120s" - tcp_r_buf_size: 262144 - tcp_w_buf_size: 65536 - pkg_wq_size: 512 - tcp_read_timeout: "1s" - tcp_write_timeout: "5s" - wait_timeout: "1s" - max_msg_len: 10240 - session_name: "client" diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/profiles/release/log.yml b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/profiles/release/log.yml deleted file mode 100644 index e0514be020..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/profiles/release/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "warn" -development: true -disableCaller: true -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/profiles/test/client.yml b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/profiles/test/client.yml deleted file mode 100644 index 48b7b0ce95..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/profiles/test/client.yml +++ /dev/null @@ -1,38 +0,0 @@ -# dubbo client yaml configure file - -config_center: - protocol: "zookeeper" - address: "127.0.0.1:2181" - group: "dubbo" - config_file: "dubbo.client.properties" - -references: - "UserProvider": - protocol : "dubbo" - interface : "com.ikurento.user.UserProvider" - cluster: "failover" - methods : - - name: "GetUser" - retries: "3" - -protocol_conf: - dubbo: - reconnect_interval: 0 - connection_number: 2 - heartbeat_period: "5s" - session_timeout: "20s" - pool_size: 64 - pool_ttl: 600 - getty_session_param: - compress_encoding: false - tcp_no_delay: true - tcp_keep_alive: true - keep_alive_period: "120s" - tcp_r_buf_size: 262144 - tcp_w_buf_size: 65536 - pkg_wq_size: 512 - tcp_read_timeout: "1s" - tcp_write_timeout: "5s" - wait_timeout: "1s" - max_msg_len: 10240 - session_name: "client" diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/profiles/test/log.yml b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/profiles/test/log.yml deleted file mode 100644 index baee0b7248..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-client/profiles/test/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "info" -development: false -disableCaller: false -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/app/server.go b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/app/server.go deleted file mode 100644 index 04c614d732..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/app/server.go +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -import ( - "fmt" - "os" - "os/signal" - "syscall" - "time" -) - -import ( - hessian "github.com/apache/dubbo-go-hessian2" -) - -import ( - _ "github.com/apache/dubbo-go/cluster/cluster_impl" - _ "github.com/apache/dubbo-go/cluster/loadbalance" - "github.com/apache/dubbo-go/common/logger" - _ "github.com/apache/dubbo-go/common/proxy/proxy_factory" - "github.com/apache/dubbo-go/config" - _ "github.com/apache/dubbo-go/config_center/zookeeper" - _ "github.com/apache/dubbo-go/filter/impl" - _ "github.com/apache/dubbo-go/protocol/dubbo" - _ "github.com/apache/dubbo-go/registry/protocol" - _ "github.com/apache/dubbo-go/registry/zookeeper" -) - -var ( - survivalTimeout = int(3e9) -) - -// they are necessary: -// export CONF_PROVIDER_FILE_PATH="xxx" -// export APP_LOG_CONF_FILE="xxx" -func main() { - - // ------for hessian2------ - hessian.RegisterJavaEnum(Gender(MAN)) - hessian.RegisterJavaEnum(Gender(WOMAN)) - hessian.RegisterPOJO(&User{}) - // ------------ - - config.Load() - - initSignal() -} - -func initSignal() { - signals := make(chan os.Signal, 1) - // It is not possible to block SIGKILL or syscall.SIGSTOP - signal.Notify(signals, os.Interrupt, os.Kill, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT) - for { - sig := <-signals - logger.Infof("get signal %s", sig.String()) - switch sig { - case syscall.SIGHUP: - // reload() - default: - time.AfterFunc(time.Duration(float64(survivalTimeout)*float64(time.Second)), func() { - logger.Warnf("app exit now by force...") - os.Exit(1) - }) - - // The program exits normally or timeout forcibly exits. - fmt.Println("provider app exit now...") - return - } - } -} diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/app/user.go b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/app/user.go deleted file mode 100644 index 0e4d057668..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/app/user.go +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -import ( - "context" - "fmt" - "strconv" - "time" -) - -import ( - hessian "github.com/apache/dubbo-go-hessian2" - "github.com/apache/dubbo-go-hessian2/java_exception" - perrors "github.com/pkg/errors" -) - -import ( - "github.com/apache/dubbo-go/config" -) - -type Gender hessian.JavaEnum - -func init() { - config.SetProviderService(new(UserProvider)) -} - -const ( - MAN hessian.JavaEnum = iota - WOMAN -) - -var genderName = map[hessian.JavaEnum]string{ - MAN: "MAN", - WOMAN: "WOMAN", -} - -var genderValue = map[string]hessian.JavaEnum{ - "MAN": MAN, - "WOMAN": WOMAN, -} - -func (g Gender) JavaClassName() string { - return "com.ikurento.user.Gender" -} - -func (g Gender) String() string { - s, ok := genderName[hessian.JavaEnum(g)] - if ok { - return s - } - - return strconv.Itoa(int(g)) -} - -func (g Gender) EnumValue(s string) hessian.JavaEnum { - v, ok := genderValue[s] - if ok { - return v - } - - return hessian.InvalidJavaEnum -} - -type ( - User struct { - // !!! Cannot define lowercase names of variable - Id string - Name string - Age int32 - Time time.Time - Sex Gender // notice: java enum Object <--> go string - } - - UserProvider struct { - user map[string]User - } -) - -var ( - DefaultUser = User{ - Id: "0", Name: "Alex Stocks", Age: 31, - Sex: Gender(MAN), - } - - userMap = UserProvider{user: make(map[string]User)} -) - -func init() { - userMap.user["A000"] = DefaultUser - userMap.user["A001"] = User{Id: "001", Name: "ZhangSheng", Age: 18, Sex: Gender(MAN)} - userMap.user["A002"] = User{Id: "002", Name: "Lily", Age: 20, Sex: Gender(WOMAN)} - userMap.user["A003"] = User{Id: "113", Name: "Moorse", Age: 30, Sex: Gender(WOMAN)} - for k, v := range userMap.user { - v.Time = time.Now() - userMap.user[k] = v - } -} - -func (u User) String() string { - return fmt.Sprintf( - "User{Id:%s, Name:%s, Age:%d, Time:%s, Sex:%s}", - u.Id, u.Name, u.Age, u.Time, u.Sex, - ) -} - -func (u User) JavaClassName() string { - return "com.ikurento.user.User" -} - -func (u *UserProvider) getUser(userId string) (*User, error) { - if user, ok := userMap.user[userId]; ok { - return &user, nil - } - - return nil, fmt.Errorf("invalid user id:%s", userId) -} - -func (u *UserProvider) GetUser(ctx context.Context, req []interface{}, rsp *User) error { - var ( - err error - user *User - ) - - println("req:%#v", req) - user, err = u.getUser(req[0].(string)) - if err == nil { - *rsp = *user - println("rsp:%#v", rsp) - } - return err -} - -func (u *UserProvider) GetErr(ctx context.Context, req []interface{}, rsp *User) error { - return java_exception.NewThrowable("exception") -} - -func (u *UserProvider) GetUser0(id string, name string) (User, error) { - var err error - - println("id:%s, name:%s", id, name) - user, err := u.getUser(id) - if err != nil { - return User{}, err - } - if user.Name != name { - return User{}, perrors.New("name is not " + user.Name) - } - return *user, err -} - -func (u *UserProvider) GetUsers(req []interface{}) ([]interface{}, error) { - var err error - - println("req:%s", req) - t := req[0].([]interface{}) - user, err := u.getUser(t[0].(string)) - if err != nil { - return nil, err - } - println("user:%v", user) - user1, err := u.getUser(t[1].(string)) - if err != nil { - return nil, err - } - println("user1:%v", user1) - - return []interface{}{user, user1}, err -} - -func (u *UserProvider) Reference() string { - return "UserProvider" -} - -func println(format string, args ...interface{}) { - fmt.Printf("\033[32;40m"+format+"\033[0m\n", args...) -} diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/app/version.go b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/app/version.go deleted file mode 100644 index c6138584f1..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/app/version.go +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -var ( - Version = "2.6.0" -) diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/bin/load.sh b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/bin/load.sh deleted file mode 100644 index 90077c2471..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/bin/load.sh +++ /dev/null @@ -1,151 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -APP_NAME="APPLICATION_NAME" -APP_ARGS="" - - -PROJECT_HOME="" -OS_NAME=`uname` -if [[ ${OS_NAME} != "Windows" ]]; then - PROJECT_HOME=`pwd` - PROJECT_HOME=${PROJECT_HOME}"/" -fi - -export CONF_PROVIDER_FILE_PATH=${PROJECT_HOME}"TARGET_CONF_FILE" -export APP_LOG_CONF_FILE=${PROJECT_HOME}"TARGET_LOG_CONF_FILE" - -usage() { - echo "Usage: $0 start [conf suffix]" - echo " $0 stop" - echo " $0 term" - echo " $0 restart" - echo " $0 list" - echo " $0 monitor" - echo " $0 crontab" - exit -} - -start() { - arg=$1 - if [ "$arg" = "" ];then - echo "No registry type! Default server.yml!" - else - export CONF_PROVIDER_FILE_PATH=${CONF_PROVIDER_FILE_PATH//\.yml/\_$arg\.yml} - fi - if [ ! -f "${CONF_PROVIDER_FILE_PATH}" ];then - echo $CONF_PROVIDER_FILE_PATH" is not existing!" - return - fi - APP_LOG_PATH="${PROJECT_HOME}logs/" - mkdir -p ${APP_LOG_PATH} - APP_BIN=${PROJECT_HOME}sbin/${APP_NAME} - chmod u+x ${APP_BIN} - # CMD="nohup ${APP_BIN} ${APP_ARGS} >>${APP_NAME}.nohup.out 2>&1 &" - CMD="${APP_BIN}" - eval ${CMD} - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $2}'` - if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $1}'` - fi - CUR=`date +%FT%T` - if [ "${PID}" != "" ]; then - for p in ${PID} - do - echo "start ${APP_NAME} ( pid =" ${p} ") at " ${CUR} - done - fi -} - -stop() { - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $2}'` - if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $1}'` - fi - if [ "${PID}" != "" ]; - then - for ps in ${PID} - do - echo "kill -SIGINT ${APP_NAME} ( pid =" ${ps} ")" - kill -2 ${ps} - done - fi -} - - -term() { - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $2}'` - if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $1}'` - fi - if [ "${PID}" != "" ]; - then - for ps in ${PID} - do - echo "kill -9 ${APP_NAME} ( pid =" ${ps} ")" - kill -9 ${ps} - done - fi -} - -list() { - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{printf("%s,%s,%s,%s\n", $1, $2, $9, $10)}'` - if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{printf("%s,%s,%s,%s,%s\n", $1, $4, $6, $7, $8)}'` - fi - - if [ "${PID}" != "" ]; then - echo "list ${APP_NAME}" - - if [[ ${OS_NAME} == "Linux" || ${OS_NAME} == "Darwin" ]]; then - echo "index: user, pid, start, duration" - else - echo "index: PID, WINPID, UID, STIME, COMMAND" - fi - idx=0 - for ps in ${PID} - do - echo "${idx}: ${ps}" - ((idx ++)) - done - fi -} - -opt=$1 -case C"$opt" in - Cstart) - start $2 - ;; - Cstop) - stop - ;; - Cterm) - term - ;; - Crestart) - term - start $2 - ;; - Clist) - list - ;; - C*) - usage - ;; -esac - diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/common/app.properties b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/common/app.properties deleted file mode 100644 index 1f0827eb51..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/common/app.properties +++ /dev/null @@ -1,23 +0,0 @@ -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -TARGET_EXEC_NAME="user_info_server" -# BUILD_PACKAGE="dubbogo-examples/user-info/server/app" -BUILD_PACKAGE="app" - -TARGET_CONF_FILE="conf/server.yml" -TARGET_LOG_CONF_FILE="conf/log.yml" diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/common/build.sh b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/common/build.sh deleted file mode 100644 index 89a95ce679..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/common/build.sh +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -rm -rf target/ - -PROJECT_HOME=`pwd` -TARGET_FOLDER=${PROJECT_HOME}/target/${GOOS} - -TARGET_SBIN_NAME=${TARGET_EXEC_NAME} -version=`cat app/version.go | grep Version | grep -v "Apache" | awk -F '=' '{print $2}' | awk -F '"' '{print $2}'` -if [[ ${GOOS} == "windows" ]]; then - TARGET_SBIN_NAME=${TARGET_SBIN_NAME}.exe -fi -TARGET_NAME=${TARGET_FOLDER}/${TARGET_SBIN_NAME} -if [[ $PROFILE = "test" ]]; then - # GFLAGS=-gcflags "-N -l" -race -x -v # -x会把go build的详细过程输出 - # GFLAGS=-gcflags "-N -l" -race -v - # GFLAGS="-gcflags \"-N -l\" -v" - cd ${BUILD_PACKAGE} && go build -gcflags "-N -l" -x -v -i -o ${TARGET_NAME} && cd - -else - # -s去掉符号表(然后panic时候的stack trace就没有任何文件名/行号信息了,这个等价于普通C/C++程序被strip的效果), - # -w去掉DWARF调试信息,得到的程序就不能用gdb调试了。-s和-w也可以分开使用,一般来说如果不打算用gdb调试, - # -w基本没啥损失。-s的损失就有点大了。 - cd ${BUILD_PACKAGE} && go build -ldflags "-w" -x -v -i -o ${TARGET_NAME} && cd - -fi - -TAR_NAME=${TARGET_EXEC_NAME}-${version}-`date "+%Y%m%d-%H%M"`-${PROFILE} - -mkdir -p ${TARGET_FOLDER}/${TAR_NAME} - -SBIN_DIR=${TARGET_FOLDER}/${TAR_NAME}/sbin -BIN_DIR=${TARGET_FOLDER}/${TAR_NAME} -CONF_DIR=${TARGET_FOLDER}/${TAR_NAME}/conf - -mkdir -p ${SBIN_DIR} -mkdir -p ${CONF_DIR} - -mv ${TARGET_NAME} ${SBIN_DIR} -cp -r assembly/bin ${BIN_DIR} -# modify APPLICATION_NAME -# OS=`uname` -# if [[ $OS=="Darwin" ]]; then -if [ "$(uname)" == "Darwin" ]; then - sed -i "" "s~APPLICATION_NAME~${TARGET_EXEC_NAME}~g" ${BIN_DIR}/bin/* -else - sed -i "s~APPLICATION_NAME~${TARGET_EXEC_NAME}~g" ${BIN_DIR}/bin/* -fi -# modify TARGET_CONF_FILE -if [ "$(uname)" == "Darwin" ]; then - sed -i "" "s~TARGET_CONF_FILE~${TARGET_CONF_FILE}~g" ${BIN_DIR}/bin/* -else - sed -i "s~TARGET_CONF_FILE~${TARGET_CONF_FILE}~g" ${BIN_DIR}/bin/* -fi -# modify TARGET_LOG_CONF_FILE -if [ "$(uname)" == "Darwin" ]; then - sed -i "" "s~TARGET_LOG_CONF_FILE~${TARGET_LOG_CONF_FILE}~g" ${BIN_DIR}/bin/* -else - sed -i "s~TARGET_LOG_CONF_FILE~${TARGET_LOG_CONF_FILE}~g" ${BIN_DIR}/bin/* -fi - -cp -r profiles/${PROFILE}/* ${CONF_DIR} - -cd ${TARGET_FOLDER} - -tar czf ${TAR_NAME}.tar.gz ${TAR_NAME}/* - diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/linux/dev.sh b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/linux/dev.sh deleted file mode 100644 index d830ac98c2..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/linux/dev.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=linux -export GOARCH=amd64 - -PROFILE=dev - -PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then -. ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then -. ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/linux/release.sh b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/linux/release.sh deleted file mode 100644 index 99303800b0..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/linux/release.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=linux -export GOARCH=amd64 - -PROFILE=release - -PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then -. ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then -. ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/linux/test.sh b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/linux/test.sh deleted file mode 100644 index 87144bb973..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/linux/test.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=linux -export GOARCH=amd64 - -PROFILE=test - -PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then -. ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then -. ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/mac/dev.sh b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/mac/dev.sh deleted file mode 100644 index 3a7659b2d5..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/mac/dev.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=darwin -export GOARCH=amd64 - -PROFILE=dev - -PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then -. ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then -. ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/mac/release.sh b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/mac/release.sh deleted file mode 100644 index 1c4bce4bf8..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/mac/release.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=darwin -export GOARCH=amd64 - -PROFILE=release - -PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then -. ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then -. ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/mac/test.sh b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/mac/test.sh deleted file mode 100644 index 69206e32fe..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/mac/test.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -set -e - -export GOOS=darwin -export GOARCH=amd64 - -PROFILE=test - -PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then -. ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then -. ${PROJECT_HOME}/assembly/common/build.sh -fi - diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/windows/dev.sh b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/windows/dev.sh deleted file mode 100644 index 011fb41148..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/windows/dev.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=windows -export GOARCH=amd64 - -PROFILE=dev - -PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then -. ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then -. ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/windows/release.sh b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/windows/release.sh deleted file mode 100644 index 679a26a7dc..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/windows/release.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=windows -export GOARCH=amd64 - -PROFILE=release - -PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then -. ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then -. ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/windows/test.sh b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/windows/test.sh deleted file mode 100644 index 4a36de0f3a..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/assembly/windows/test.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=windows -export GOARCH=amd64 - -PROFILE=test - -PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then -. ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then -. ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/profiles/dev/log.yml b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/profiles/dev/log.yml deleted file mode 100644 index 59fa4279ad..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/profiles/dev/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "debug" -development: true -disableCaller: false -disableStacktrace: false -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/profiles/release/log.yml b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/profiles/release/log.yml deleted file mode 100644 index e0514be020..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/profiles/release/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "warn" -development: true -disableCaller: true -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/profiles/release/server.yml b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/profiles/release/server.yml deleted file mode 100644 index 219b92aebf..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/profiles/release/server.yml +++ /dev/null @@ -1,39 +0,0 @@ -# dubbo server yaml configure file - - -config_center: - protocol: "zookeeper" - address: "127.0.0.1:2181" - group: "dubbo" - config_file: "dubbo.properties" - -services: - "UserProvider": - protocol : "dubbo" - # 相当于dubbo.xml中的interface - interface : "com.ikurento.user.UserProvider" - loadbalance: "random" - warmup: "100" - cluster: "failover" - methods: - - name: "GetUser" - retries: "1" - loadbalance: "random" - -protocol_conf: - dubbo: - session_number: 700 - session_timeout: "20s" - getty_session_param: - compress_encoding: false - tcp_no_delay: true - tcp_keep_alive: true - keep_alive_period: "120s" - tcp_r_buf_size: 262144 - tcp_w_buf_size: 65536 - pkg_wq_size: 512 - tcp_read_timeout: "1s" - tcp_write_timeout: "5s" - wait_timeout: "1s" - max_msg_len: 1024 - session_name: "server" diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/profiles/test/log.yml b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/profiles/test/log.yml deleted file mode 100644 index baee0b7248..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/profiles/test/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "info" -development: false -disableCaller: false -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/profiles/test/server.yml b/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/profiles/test/server.yml deleted file mode 100644 index 219b92aebf..0000000000 --- a/examples/configcenter/zookeeper/dubbo/with-configcenter-go-server/profiles/test/server.yml +++ /dev/null @@ -1,39 +0,0 @@ -# dubbo server yaml configure file - - -config_center: - protocol: "zookeeper" - address: "127.0.0.1:2181" - group: "dubbo" - config_file: "dubbo.properties" - -services: - "UserProvider": - protocol : "dubbo" - # 相当于dubbo.xml中的interface - interface : "com.ikurento.user.UserProvider" - loadbalance: "random" - warmup: "100" - cluster: "failover" - methods: - - name: "GetUser" - retries: "1" - loadbalance: "random" - -protocol_conf: - dubbo: - session_number: 700 - session_timeout: "20s" - getty_session_param: - compress_encoding: false - tcp_no_delay: true - tcp_keep_alive: true - keep_alive_period: "120s" - tcp_r_buf_size: 262144 - tcp_w_buf_size: 65536 - pkg_wq_size: 512 - tcp_read_timeout: "1s" - tcp_write_timeout: "5s" - wait_timeout: "1s" - max_msg_len: 1024 - session_name: "server" diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/app/client.go b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/app/client.go deleted file mode 100644 index db76d939a1..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/app/client.go +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -import ( - "context" - "fmt" - "os" - "os/signal" - "syscall" - "time" -) - -import ( - "github.com/apache/dubbo-go/common/logger" - _ "github.com/apache/dubbo-go/common/proxy/proxy_factory" - "github.com/apache/dubbo-go/config" - _ "github.com/apache/dubbo-go/protocol/jsonrpc" - _ "github.com/apache/dubbo-go/registry/protocol" - - _ "github.com/apache/dubbo-go/filter/impl" - - _ "github.com/apache/dubbo-go/cluster/cluster_impl" - _ "github.com/apache/dubbo-go/cluster/loadbalance" - _ "github.com/apache/dubbo-go/config_center/zookeeper" - _ "github.com/apache/dubbo-go/registry/zookeeper" -) - -var ( - survivalTimeout int = 10e9 -) - -// they are necessary: -// export CONF_CONSUMER_FILE_PATH="xxx" -// export APP_LOG_CONF_FILE="xxx" -func main() { - - config.Load() - - println("\n\n\necho") - res, err := userProvider.Echo(context.TODO(), "OK") - if err != nil { - println("echo - error: %v", err) - } else { - println("res: %v", res) - } - - time.Sleep(3e9) - - println("\n\n\nstart to test jsonrpc") - user := &JsonRPCUser{} - err = userProvider.GetUser(context.TODO(), []interface{}{"A003"}, user) - if err != nil { - panic(err) - } - println("response result: %v", user) - - println("\n\n\nstart to test jsonrpc - GetUser0") - ret, err := userProvider.GetUser0("A003", "Moorse") - if err != nil { - panic(err) - } - println("response result: %v", ret) - - println("\n\n\nstart to test jsonrpc - GetUsers") - ret1, err := userProvider.GetUsers([]interface{}{[]interface{}{"A002", "A003"}}) - if err != nil { - panic(err) - } - println("response result: %v", ret1) - - println("\n\n\nstart to test jsonrpc - getUser") - user = &JsonRPCUser{} - err = userProvider.GetUser2(context.TODO(), []interface{}{1}, user) - if err != nil { - panic(err) - } - println("response result: %v", user) - - println("\n\n\nstart to test jsonrpc - GetUser3") - err = userProvider.GetUser3() - if err != nil { - panic(err) - } - println("succ!") - - println("\n\n\nstart to test jsonrpc illegal method") - err = userProvider.GetUser1(context.TODO(), []interface{}{"A003"}, user) - if err != nil { - panic(err) - } - - initSignal() -} - -func initSignal() { - signals := make(chan os.Signal, 1) - // It is not possible to block SIGKILL or syscall.SIGSTOP - signal.Notify(signals, os.Interrupt, os.Kill, syscall.SIGHUP, - syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT) - for { - sig := <-signals - logger.Infof("get signal %s", sig.String()) - switch sig { - case syscall.SIGHUP: - // reload() - default: - time.AfterFunc(time.Duration(survivalTimeout)*time.Second, func() { - logger.Warnf("app exit now by force...") - os.Exit(1) - }) - - // The program exits normally or timeout forcibly exits. - fmt.Println("app exit now...") - return - } - } -} - -func println(format string, args ...interface{}) { - fmt.Printf("\033[32;40m"+format+"\033[0m\n", args...) -} diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/app/user.go b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/app/user.go deleted file mode 100644 index fef665bb3d..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/app/user.go +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -import ( - "context" - "fmt" - "time" -) - -import ( - "github.com/apache/dubbo-go/config" -) - -var userProvider = new(UserProvider) - -func init() { - config.SetConsumerService(userProvider) -} - -type JsonRPCUser struct { - ID string `json:"id"` - Name string `json:"name"` - Age int64 `json:"age"` - Time int64 `json:"time"` - Sex string `json:"sex"` -} - -func (u JsonRPCUser) String() string { - return fmt.Sprintf( - "User{ID:%s, Name:%s, Age:%d, Time:%s, Sex:%s}", - u.ID, u.Name, u.Age, time.Unix(u.Time, 0).Format("2006-01-02 15:04:05.99999"), u.Sex, - ) -} - -type UserProvider struct { - GetUsers func(req []interface{}) ([]JsonRPCUser, error) - GetUser func(ctx context.Context, req []interface{}, rsp *JsonRPCUser) error - GetUser0 func(id string, name string) (JsonRPCUser, error) - GetUser1 func(ctx context.Context, req []interface{}, rsp *JsonRPCUser) error - GetUser2 func(ctx context.Context, req []interface{}, rsp *JsonRPCUser) error `dubbo:"getUser"` - GetUser3 func() error - Echo func(ctx context.Context, req interface{}) (interface{}, error) // Echo represent EchoFilter will be used -} - -func (u *UserProvider) Reference() string { - return "UserProvider" -} diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/bin/load.sh b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/bin/load.sh deleted file mode 100644 index ffa240b29d..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/bin/load.sh +++ /dev/null @@ -1,203 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -APP_NAME="APPLICATION_NAME" -APP_ARGS="" -SLEEP_INTERVAL=5 -MAX_LIFETIME=4000 - -PROJECT_HOME="" -OS_NAME=`uname` -if [[ ${OS_NAME} != "Windows" ]]; then - PROJECT_HOME=`pwd` - PROJECT_HOME=${PROJECT_HOME}"/" -else - APP_NAME="APPLICATION_NAME.exe" -fi - -export CONF_CONSUMER_FILE_PATH=${PROJECT_HOME}"TARGET_CONF_FILE" -export APP_LOG_CONF_FILE=${PROJECT_HOME}"TARGET_LOG_CONF_FILE" -# export GOTRACEBACK=system -# export GODEBUG=gctrace=1 - -usage() { - echo "Usage: $0 start [conf suffix]" - echo " $0 stop" - echo " $0 term" - echo " $0 restart" - echo " $0 list" - echo " $0 monitor" - echo " $0 crontab" - exit -} - -start() { - arg=$1 - if [ "$arg" = "" ];then - echo "No registry type! Default client.yml!" - else - export CONF_CONSUMER_FILE_PATH=${CONF_CONSUMER_FILE_PATH//\.yml/\_$arg\.yml} - fi - if [ ! -f "${CONF_CONSUMER_FILE_PATH}" ];then - echo $CONF_CONSUMER_FILE_PATH" is not existing!" - return - fi - APP_LOG_PATH=${PROJECT_HOME}"logs/" - mkdir -p ${APP_LOG_PATH} - APP_BIN=${PROJECT_HOME}sbin/${APP_NAME} - chmod u+x ${APP_BIN} - # CMD="nohup ${APP_BIN} ${APP_ARGS} >>${APP_NAME}.nohup.out 2>&1 &" - CMD="${APP_BIN}" - eval ${CMD} - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $2}'` - if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $1}'` - fi - CUR=`date +%FT%T` - if [ "${PID}" != "" ]; then - for p in ${PID} - do - echo "start ${APP_NAME} ( pid =" ${p} ") at " ${CUR} - done - fi -} - -stop() { - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $2}'` - if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $1}'` - fi - if [ "${PID}" != "" ]; - then - for ps in ${PID} - do - echo "kill -SIGINT ${APP_NAME} ( pid =" ${ps} ")" - kill -2 ${ps} - done - fi -} - - -term() { - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $2}'` - if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $1}'` - fi - if [ "${PID}" != "" ]; - then - for ps in ${PID} - do - echo "kill -9 ${APP_NAME} ( pid =" ${ps} ")" - kill -9 ${ps} - done - fi -} - -list() { - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{printf("%s,%s,%s,%s\n", $1, $2, $9, $10)}'` - if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{printf("%s,%s,%s,%s,%s\n", $1, $4, $6, $7, $8)}'` - fi - - if [ "${PID}" != "" ]; then - echo "list ${APP_NAME}" - - if [[ ${OS_NAME} == "Linux" || ${OS_NAME} == "Darwin" ]]; then - echo "index: user, pid, start, duration" - else - echo "index: PID, WINPID, UID, STIME, COMMAND" - fi - idx=0 - for ps in ${PID} - do - echo "${idx}: ${ps}" - ((idx ++)) - done - fi -} - -monitor() { - idx=0 - while true; do - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $2}'` - if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $1}'` - fi - if [[ "${PID}" == "" ]]; then - start - idx=0 - fi - - ((LIFE=idx*${SLEEP_INTERVAL})) - echo "${APP_NAME} ( pid = " ${PID} ") has been working in normal state for " $LIFE " seconds." - ((idx ++)) - sleep ${SLEEP_INTERVAL} - done -} - -crontab() { - idx=0 - while true; do - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $2}'` - if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $1}'` - fi - if [[ "${PID}" == "" ]]; then - start - idx=0 - fi - - ((LIFE=idx*${SLEEP_INTERVAL})) - echo "${APP_NAME} ( pid = " ${PID} ") has been working in normal state for " $LIFE " seconds." - ((idx ++)) - sleep ${SLEEP_INTERVAL} - if [[ ${LIFE} -gt ${MAX_LIFETIME} ]]; then - kill -9 ${PID} - fi - done -} - -opt=$1 -case C"$opt" in - Cstart) - start $2 - ;; - Cstop) - stop - ;; - Cterm) - term - ;; - Crestart) - term - start $2 - ;; - Clist) - list - ;; - Cmonitor) - monitor - ;; - Ccrontab) - crontab - ;; - C*) - usage - ;; -esac - diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/common/app.properties b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/common/app.properties deleted file mode 100644 index e10868f4d2..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/common/app.properties +++ /dev/null @@ -1,23 +0,0 @@ -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -export TARGET_EXEC_NAME="user_info_client" -# BUILD_PACKAGE="dubbogo-examples/user-info/client/app" -export BUILD_PACKAGE="app" - -export TARGET_CONF_FILE="conf/client.yml" -export TARGET_LOG_CONF_FILE="conf/log.yml" diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/common/build.sh b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/common/build.sh deleted file mode 100644 index c9a9e87c73..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/common/build.sh +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -rm -rf target/ - -PROJECT_HOME=`pwd` -TARGET_FOLDER=${PROJECT_HOME}/target/${GOOS} - -TARGET_SBIN_NAME=${TARGET_EXEC_NAME} -version=`cat app/version.go | grep Version | grep -v "Apache" | awk -F '=' '{print $2}' | awk -F '"' '{print $2}'` -if [[ ${GOOS} == "windows" ]]; then - TARGET_SBIN_NAME=${TARGET_SBIN_NAME}.exe -fi -TARGET_NAME=${TARGET_FOLDER}/${TARGET_SBIN_NAME} -if [[ $PROFILE == "dev" || $PROFILE == "test" ]]; then - # GFLAGS=-gcflags "-N -l" -race -x -v # -x会把go build的详细过程输出 - # GFLAGS=-gcflags "-N -l" -race -v - # GFLAGS="-gcflags \"-N -l\" -v" - cd ${BUILD_PACKAGE} && GOOS=$GOOS GOARCH=$GOARCH go build -gcflags "-N -l" -x -v -i -o ${TARGET_NAME} && cd - -else - # -s去掉符号表(然后panic时候的stack trace就没有任何文件名/行号信息了,这个等价于普通C/C++程序被strip的效果), - # -w去掉DWARF调试信息,得到的程序就不能用gdb调试了。-s和-w也可以分开使用,一般来说如果不打算用gdb调试, - # -w基本没啥损失。-s的损失就有点大了。 - cd ${BUILD_PACKAGE} && GOOS=$GOOS GOARCH=$GOARCH go build -ldflags "-w" -x -v -i -o ${TARGET_NAME} && cd - -fi - -TAR_NAME=${TARGET_EXEC_NAME}-${version}-`date "+%Y%m%d-%H%M"`-${PROFILE} - -mkdir -p ${TARGET_FOLDER}/${TAR_NAME} - -SBIN_DIR=${TARGET_FOLDER}/${TAR_NAME}/sbin -BIN_DIR=${TARGET_FOLDER}/${TAR_NAME} -CONF_DIR=${TARGET_FOLDER}/${TAR_NAME}/conf - -mkdir -p ${SBIN_DIR} -mkdir -p ${CONF_DIR} - -mv ${TARGET_NAME} ${SBIN_DIR} -cp -r assembly/bin ${BIN_DIR} -cd ${BIN_DIR}/bin/ && mv load.sh load_${TARGET_EXEC_NAME}.sh && cd - - -platform=$(uname) -# modify APPLICATION_NAME -if [ ${platform} == "Darwin" ]; then - sed -i "" "s~APPLICATION_NAME~${TARGET_EXEC_NAME}~g" ${BIN_DIR}/bin/* -else - sed -i "s~APPLICATION_NAME~${TARGET_EXEC_NAME}~g" ${BIN_DIR}/bin/* -fi - -# modify TARGET_CONF_FILE -if [ ${platform} == "Darwin" ]; then - sed -i "" "s~TARGET_CONF_FILE~${TARGET_CONF_FILE}~g" ${BIN_DIR}/bin/* -else - sed -i "s~TARGET_CONF_FILE~${TARGET_CONF_FILE}~g" ${BIN_DIR}/bin/* -fi - -# modify TARGET_LOG_CONF_FILE -if [ ${platform} == "Darwin" ]; then - sed -i "" "s~TARGET_LOG_CONF_FILE~${TARGET_LOG_CONF_FILE}~g" ${BIN_DIR}/bin/* -else - sed -i "s~TARGET_LOG_CONF_FILE~${TARGET_LOG_CONF_FILE}~g" ${BIN_DIR}/bin/* -fi - -cp -r profiles/${PROFILE}/* ${CONF_DIR} - -cd ${TARGET_FOLDER} - -tar czf ${TAR_NAME}.tar.gz ${TAR_NAME}/* - diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/linux/dev.sh b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/linux/dev.sh deleted file mode 100644 index eada737c8d..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/linux/dev.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=linux -export GOARCH=amd64 - -export PROFILE="dev" - -PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then - . ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then - sh ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/linux/release.sh b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/linux/release.sh deleted file mode 100644 index 10eb3d73f8..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/linux/release.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=linux -export GOARCH=amd64 - -export PROFILE="release" -export PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then - . ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then - sh ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/linux/test.sh b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/linux/test.sh deleted file mode 100644 index 78b650c0d4..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/linux/test.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=linux -export GOARCH=amd64 - -export PROFILE="test" -export PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then - . ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then - sh ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/mac/dev.sh b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/mac/dev.sh deleted file mode 100644 index c828476990..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/mac/dev.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=darwin -export GOARCH=amd64 - -export PROFILE="dev" - -export PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then - . ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then - sh ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/mac/release.sh b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/mac/release.sh deleted file mode 100644 index 91c2dfee79..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/mac/release.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=darwin -export GOARCH=amd64 - -export PROFILE="release" -export PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then - . ${PROJECT_HOME}/assembly/common/app.properties -fi - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then - sh ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/mac/test.sh b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/mac/test.sh deleted file mode 100644 index a7853f5e2d..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/mac/test.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -set -e - -export GOOS=darwin -export GOARCH=amd64 - -export PROFILE="test" -export PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then - . ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then - sh ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/windows/dev.sh b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/windows/dev.sh deleted file mode 100644 index 10a3866c0f..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/windows/dev.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=linux -export GOARCH=amd64 - -export PROFILE="dev" -PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then - . ${PROJECT_HOME}/assembly/common/app.properties -fi - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then - sh ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/windows/release.sh b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/windows/release.sh deleted file mode 100644 index 21af573fa3..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/windows/release.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=windows -export GOARCH=amd64 - -export PROFILE="release" -export PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then - . ${PROJECT_HOME}/assembly/common/app.properties -fi - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then - sh ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/windows/test.sh b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/windows/test.sh deleted file mode 100644 index 2104da8b59..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/assembly/windows/test.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=windows -export GOARCH=amd64 - -export PROFILE="test" -export PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then - . ${PROJECT_HOME}/assembly/common/app.properties -fi - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then - sh ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/profiles/dev/client.yml b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/profiles/dev/client.yml deleted file mode 100644 index 3770f52b83..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/profiles/dev/client.yml +++ /dev/null @@ -1,16 +0,0 @@ -# dubbo client yaml configure file - -config_center: - protocol: "zookeeper" - address: "127.0.0.1:2181" - group: "dubbo" - config_file: "dubbo.client.properties" - -references: - "UserProvider": - protocol : "jsonrpc" - interface : "com.ikurento.user.UserProvider" - cluster: "failover" - methods : - - name: "GetUser" - retries: 3 diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/profiles/dev/log.yml b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/profiles/dev/log.yml deleted file mode 100644 index 59fa4279ad..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/profiles/dev/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "debug" -development: true -disableCaller: false -disableStacktrace: false -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/profiles/release/client.yml b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/profiles/release/client.yml deleted file mode 100644 index 3770f52b83..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/profiles/release/client.yml +++ /dev/null @@ -1,16 +0,0 @@ -# dubbo client yaml configure file - -config_center: - protocol: "zookeeper" - address: "127.0.0.1:2181" - group: "dubbo" - config_file: "dubbo.client.properties" - -references: - "UserProvider": - protocol : "jsonrpc" - interface : "com.ikurento.user.UserProvider" - cluster: "failover" - methods : - - name: "GetUser" - retries: 3 diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/profiles/release/log.yml b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/profiles/release/log.yml deleted file mode 100644 index e0514be020..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/profiles/release/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "warn" -development: true -disableCaller: true -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/profiles/test/client.yml b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/profiles/test/client.yml deleted file mode 100644 index 3770f52b83..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/profiles/test/client.yml +++ /dev/null @@ -1,16 +0,0 @@ -# dubbo client yaml configure file - -config_center: - protocol: "zookeeper" - address: "127.0.0.1:2181" - group: "dubbo" - config_file: "dubbo.client.properties" - -references: - "UserProvider": - protocol : "jsonrpc" - interface : "com.ikurento.user.UserProvider" - cluster: "failover" - methods : - - name: "GetUser" - retries: 3 diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/profiles/test/log.yml b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/profiles/test/log.yml deleted file mode 100644 index baee0b7248..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-client/profiles/test/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "info" -development: false -disableCaller: false -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/app/server.go b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/app/server.go deleted file mode 100644 index 23cfd41553..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/app/server.go +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -import ( - "fmt" - "os" - "os/signal" - "syscall" - "time" -) - -import ( - _ "github.com/apache/dubbo-go/cluster/cluster_impl" - _ "github.com/apache/dubbo-go/cluster/loadbalance" - "github.com/apache/dubbo-go/common/logger" - _ "github.com/apache/dubbo-go/common/proxy/proxy_factory" - "github.com/apache/dubbo-go/config" - _ "github.com/apache/dubbo-go/config_center/zookeeper" - _ "github.com/apache/dubbo-go/filter/impl" - _ "github.com/apache/dubbo-go/protocol/jsonrpc" - _ "github.com/apache/dubbo-go/registry/protocol" - _ "github.com/apache/dubbo-go/registry/zookeeper" -) - -var ( - survivalTimeout = int(3e9) -) - -// they are necessary: -// export CONF_PROVIDER_FILE_PATH="xxx" -// export APP_LOG_CONF_FILE="xxx" -func main() { - config.Load() - - initSignal() -} - -func initSignal() { - signals := make(chan os.Signal, 1) - // It is not possible to block SIGKILL or syscall.SIGSTOP - signal.Notify(signals, os.Interrupt, os.Kill, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT) - for { - sig := <-signals - logger.Infof("get signal %s", sig.String()) - switch sig { - case syscall.SIGHUP: - // reload() - default: - time.AfterFunc(time.Duration(float64(survivalTimeout)*float64(time.Second)), func() { - logger.Warnf("app exit now by force...") - os.Exit(1) - }) - - // The program exits normally or timeout forcibly exits. - fmt.Println("provider app exit now...") - return - } - } -} diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/app/user.go b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/app/user.go deleted file mode 100644 index 9ab9e58cb4..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/app/user.go +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -import ( - "context" - "fmt" - "time" -) - -import ( - perrors "github.com/pkg/errors" -) - -import ( - "github.com/apache/dubbo-go/config" -) - -type Gender int - -func init() { - config.SetProviderService(new(UserProvider)) -} - -const ( - MAN = iota - WOMAN -) - -var genderStrings = [...]string{ - "MAN", - "WOMAN", -} - -func (g Gender) String() string { - return genderStrings[g] -} - -type ( - User struct { - Id string `json:"id"` - Name string `json:"name"` - Age int `json:"age"` - sex Gender - Birth int `json:"time"` - Sex string `json:"sex"` - } - - UserProvider struct { - user map[string]User - } -) - -var ( - DefaultUser = User{ - Id: "0", Name: "Alex Stocks", Age: 31, - // Birth: int(time.Date(1985, time.November, 10, 23, 0, 0, 0, time.UTC).Unix()), - Birth: int(time.Date(1985, 11, 24, 15, 15, 0, 0, time.Local).Unix()), - sex: Gender(MAN), - } - - userMap = UserProvider{user: make(map[string]User)} -) - -func init() { - DefaultUser.Sex = DefaultUser.sex.String() - userMap.user["A000"] = DefaultUser - userMap.user["A001"] = User{Id: "001", Name: "ZhangSheng", Age: 18, sex: MAN} - userMap.user["A002"] = User{Id: "002", Name: "Lily", Age: 20, sex: WOMAN} - userMap.user["A003"] = User{Id: "113", Name: "Moorse", Age: 30, sex: MAN} - for k, v := range userMap.user { - v.Birth = int(time.Now().AddDate(-1*v.Age, 0, 0).Unix()) - v.Sex = userMap.user[k].sex.String() - userMap.user[k] = v - } -} - -func (u *UserProvider) getUser(userId string) (*User, error) { - if user, ok := userMap.user[userId]; ok { - return &user, nil - } - - return nil, fmt.Errorf("invalid user id:%s", userId) -} - -func (u *UserProvider) GetUser(ctx context.Context, req []interface{}, rsp *User) error { - var ( - err error - user *User - ) - - println("req:%#v", req) - user, err = u.getUser(req[0].(string)) - if err == nil { - *rsp = *user - println("rsp:%#v", rsp) - } - return err -} - -func (u *UserProvider) GetUser0(id string, name string) (User, error) { - var err error - - println("id:%s, name:%s", id, name) - user, err := u.getUser(id) - if err != nil { - return User{}, err - } - if user.Name != name { - return User{}, perrors.New("name is not " + user.Name) - } - return *user, err -} - -func (u *UserProvider) GetUsers(req []interface{}) ([]User, error) { - var err error - - println("req:%s", req) - t := req[0].([]interface{}) - user, err := u.getUser(t[0].(string)) - if err != nil { - return nil, err - } - println("user:%v", user) - user1, err := u.getUser(t[1].(string)) - if err != nil { - return nil, err - } - println("user1:%v", user1) - - return []User{*user, *user1}, err -} - -func (u *UserProvider) Reference() string { - return "UserProvider" -} - -func println(format string, args ...interface{}) { - fmt.Printf("\033[32;40m"+format+"\033[0m\n", args...) -} diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/bin/load.sh b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/bin/load.sh deleted file mode 100644 index 90077c2471..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/bin/load.sh +++ /dev/null @@ -1,151 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -APP_NAME="APPLICATION_NAME" -APP_ARGS="" - - -PROJECT_HOME="" -OS_NAME=`uname` -if [[ ${OS_NAME} != "Windows" ]]; then - PROJECT_HOME=`pwd` - PROJECT_HOME=${PROJECT_HOME}"/" -fi - -export CONF_PROVIDER_FILE_PATH=${PROJECT_HOME}"TARGET_CONF_FILE" -export APP_LOG_CONF_FILE=${PROJECT_HOME}"TARGET_LOG_CONF_FILE" - -usage() { - echo "Usage: $0 start [conf suffix]" - echo " $0 stop" - echo " $0 term" - echo " $0 restart" - echo " $0 list" - echo " $0 monitor" - echo " $0 crontab" - exit -} - -start() { - arg=$1 - if [ "$arg" = "" ];then - echo "No registry type! Default server.yml!" - else - export CONF_PROVIDER_FILE_PATH=${CONF_PROVIDER_FILE_PATH//\.yml/\_$arg\.yml} - fi - if [ ! -f "${CONF_PROVIDER_FILE_PATH}" ];then - echo $CONF_PROVIDER_FILE_PATH" is not existing!" - return - fi - APP_LOG_PATH="${PROJECT_HOME}logs/" - mkdir -p ${APP_LOG_PATH} - APP_BIN=${PROJECT_HOME}sbin/${APP_NAME} - chmod u+x ${APP_BIN} - # CMD="nohup ${APP_BIN} ${APP_ARGS} >>${APP_NAME}.nohup.out 2>&1 &" - CMD="${APP_BIN}" - eval ${CMD} - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $2}'` - if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $1}'` - fi - CUR=`date +%FT%T` - if [ "${PID}" != "" ]; then - for p in ${PID} - do - echo "start ${APP_NAME} ( pid =" ${p} ") at " ${CUR} - done - fi -} - -stop() { - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $2}'` - if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $1}'` - fi - if [ "${PID}" != "" ]; - then - for ps in ${PID} - do - echo "kill -SIGINT ${APP_NAME} ( pid =" ${ps} ")" - kill -2 ${ps} - done - fi -} - - -term() { - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $2}'` - if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $1}'` - fi - if [ "${PID}" != "" ]; - then - for ps in ${PID} - do - echo "kill -9 ${APP_NAME} ( pid =" ${ps} ")" - kill -9 ${ps} - done - fi -} - -list() { - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{printf("%s,%s,%s,%s\n", $1, $2, $9, $10)}'` - if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then - PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{printf("%s,%s,%s,%s,%s\n", $1, $4, $6, $7, $8)}'` - fi - - if [ "${PID}" != "" ]; then - echo "list ${APP_NAME}" - - if [[ ${OS_NAME} == "Linux" || ${OS_NAME} == "Darwin" ]]; then - echo "index: user, pid, start, duration" - else - echo "index: PID, WINPID, UID, STIME, COMMAND" - fi - idx=0 - for ps in ${PID} - do - echo "${idx}: ${ps}" - ((idx ++)) - done - fi -} - -opt=$1 -case C"$opt" in - Cstart) - start $2 - ;; - Cstop) - stop - ;; - Cterm) - term - ;; - Crestart) - term - start $2 - ;; - Clist) - list - ;; - C*) - usage - ;; -esac - diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/common/app.properties b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/common/app.properties deleted file mode 100644 index 1f0827eb51..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/common/app.properties +++ /dev/null @@ -1,23 +0,0 @@ -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -TARGET_EXEC_NAME="user_info_server" -# BUILD_PACKAGE="dubbogo-examples/user-info/server/app" -BUILD_PACKAGE="app" - -TARGET_CONF_FILE="conf/server.yml" -TARGET_LOG_CONF_FILE="conf/log.yml" diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/common/build.sh b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/common/build.sh deleted file mode 100644 index 89a95ce679..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/common/build.sh +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -rm -rf target/ - -PROJECT_HOME=`pwd` -TARGET_FOLDER=${PROJECT_HOME}/target/${GOOS} - -TARGET_SBIN_NAME=${TARGET_EXEC_NAME} -version=`cat app/version.go | grep Version | grep -v "Apache" | awk -F '=' '{print $2}' | awk -F '"' '{print $2}'` -if [[ ${GOOS} == "windows" ]]; then - TARGET_SBIN_NAME=${TARGET_SBIN_NAME}.exe -fi -TARGET_NAME=${TARGET_FOLDER}/${TARGET_SBIN_NAME} -if [[ $PROFILE = "test" ]]; then - # GFLAGS=-gcflags "-N -l" -race -x -v # -x会把go build的详细过程输出 - # GFLAGS=-gcflags "-N -l" -race -v - # GFLAGS="-gcflags \"-N -l\" -v" - cd ${BUILD_PACKAGE} && go build -gcflags "-N -l" -x -v -i -o ${TARGET_NAME} && cd - -else - # -s去掉符号表(然后panic时候的stack trace就没有任何文件名/行号信息了,这个等价于普通C/C++程序被strip的效果), - # -w去掉DWARF调试信息,得到的程序就不能用gdb调试了。-s和-w也可以分开使用,一般来说如果不打算用gdb调试, - # -w基本没啥损失。-s的损失就有点大了。 - cd ${BUILD_PACKAGE} && go build -ldflags "-w" -x -v -i -o ${TARGET_NAME} && cd - -fi - -TAR_NAME=${TARGET_EXEC_NAME}-${version}-`date "+%Y%m%d-%H%M"`-${PROFILE} - -mkdir -p ${TARGET_FOLDER}/${TAR_NAME} - -SBIN_DIR=${TARGET_FOLDER}/${TAR_NAME}/sbin -BIN_DIR=${TARGET_FOLDER}/${TAR_NAME} -CONF_DIR=${TARGET_FOLDER}/${TAR_NAME}/conf - -mkdir -p ${SBIN_DIR} -mkdir -p ${CONF_DIR} - -mv ${TARGET_NAME} ${SBIN_DIR} -cp -r assembly/bin ${BIN_DIR} -# modify APPLICATION_NAME -# OS=`uname` -# if [[ $OS=="Darwin" ]]; then -if [ "$(uname)" == "Darwin" ]; then - sed -i "" "s~APPLICATION_NAME~${TARGET_EXEC_NAME}~g" ${BIN_DIR}/bin/* -else - sed -i "s~APPLICATION_NAME~${TARGET_EXEC_NAME}~g" ${BIN_DIR}/bin/* -fi -# modify TARGET_CONF_FILE -if [ "$(uname)" == "Darwin" ]; then - sed -i "" "s~TARGET_CONF_FILE~${TARGET_CONF_FILE}~g" ${BIN_DIR}/bin/* -else - sed -i "s~TARGET_CONF_FILE~${TARGET_CONF_FILE}~g" ${BIN_DIR}/bin/* -fi -# modify TARGET_LOG_CONF_FILE -if [ "$(uname)" == "Darwin" ]; then - sed -i "" "s~TARGET_LOG_CONF_FILE~${TARGET_LOG_CONF_FILE}~g" ${BIN_DIR}/bin/* -else - sed -i "s~TARGET_LOG_CONF_FILE~${TARGET_LOG_CONF_FILE}~g" ${BIN_DIR}/bin/* -fi - -cp -r profiles/${PROFILE}/* ${CONF_DIR} - -cd ${TARGET_FOLDER} - -tar czf ${TAR_NAME}.tar.gz ${TAR_NAME}/* - diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/linux/dev.sh b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/linux/dev.sh deleted file mode 100644 index d830ac98c2..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/linux/dev.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=linux -export GOARCH=amd64 - -PROFILE=dev - -PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then -. ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then -. ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/linux/release.sh b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/linux/release.sh deleted file mode 100644 index 99303800b0..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/linux/release.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=linux -export GOARCH=amd64 - -PROFILE=release - -PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then -. ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then -. ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/linux/test.sh b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/linux/test.sh deleted file mode 100644 index 87144bb973..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/linux/test.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=linux -export GOARCH=amd64 - -PROFILE=test - -PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then -. ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then -. ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/mac/dev.sh b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/mac/dev.sh deleted file mode 100644 index 3a7659b2d5..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/mac/dev.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=darwin -export GOARCH=amd64 - -PROFILE=dev - -PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then -. ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then -. ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/mac/release.sh b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/mac/release.sh deleted file mode 100644 index 1c4bce4bf8..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/mac/release.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=darwin -export GOARCH=amd64 - -PROFILE=release - -PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then -. ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then -. ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/mac/test.sh b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/mac/test.sh deleted file mode 100644 index 69206e32fe..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/mac/test.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -set -e - -export GOOS=darwin -export GOARCH=amd64 - -PROFILE=test - -PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then -. ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then -. ${PROJECT_HOME}/assembly/common/build.sh -fi - diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/windows/dev.sh b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/windows/dev.sh deleted file mode 100644 index 011fb41148..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/windows/dev.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=windows -export GOARCH=amd64 - -PROFILE=dev - -PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then -. ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then -. ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/windows/release.sh b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/windows/release.sh deleted file mode 100644 index 679a26a7dc..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/windows/release.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=windows -export GOARCH=amd64 - -PROFILE=release - -PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then -. ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then -. ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/windows/test.sh b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/windows/test.sh deleted file mode 100644 index 4a36de0f3a..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/assembly/windows/test.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - - -set -e - -export GOOS=windows -export GOARCH=amd64 - -PROFILE=test - -PROJECT_HOME=`pwd` - -if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then -. ${PROJECT_HOME}/assembly/common/app.properties -fi - - -if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then -. ${PROJECT_HOME}/assembly/common/build.sh -fi diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/profiles/dev/log.yml b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/profiles/dev/log.yml deleted file mode 100644 index 59fa4279ad..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/profiles/dev/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "debug" -development: true -disableCaller: false -disableStacktrace: false -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/profiles/dev/server.yml b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/profiles/dev/server.yml deleted file mode 100644 index 5c2a2fe2cb..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/profiles/dev/server.yml +++ /dev/null @@ -1,22 +0,0 @@ -# dubbo server yaml configure file - -# application config - -services: - "UserProvider": - protocol : "jsonrpc" - # 相当于dubbo.xml中的interface - interface : "com.ikurento.user.UserProvider" - loadbalance: "random" - warmup: "100" - cluster: "failover" - methods: - - name: "GetUser" - retries: 1 - loadbalance: "random" - -config_center: - protocol: "zookeeper" - address: "127.0.0.1:2181" - group: "dubbo" - config_file: "dubbo.properties" diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/profiles/release/log.yml b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/profiles/release/log.yml deleted file mode 100644 index e0514be020..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/profiles/release/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "warn" -development: true -disableCaller: true -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/profiles/release/server.yml b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/profiles/release/server.yml deleted file mode 100644 index 82c9fa66ad..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/profiles/release/server.yml +++ /dev/null @@ -1,25 +0,0 @@ -# dubbo server yaml configure file - -# application config - -services: - "UserProvider": - protocol : "jsonrpc" - # 相当于dubbo.xml中的interface - interface : "com.ikurento.user.UserProvider" - loadbalance: "random" - warmup: "100" - cluster: "failover" - methods: - - name: "GetUser" - retries: 1 - loadbalance: "random" - -config_center: - protocol: "zookeeper" - address: "127.0.0.1:2181" - group: "dubbo" - config_file: "dubbo.properties" - - - diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/profiles/test/log.yml b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/profiles/test/log.yml deleted file mode 100644 index baee0b7248..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/profiles/test/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "info" -development: false -disableCaller: false -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/profiles/test/server.yml b/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/profiles/test/server.yml deleted file mode 100644 index 82c9fa66ad..0000000000 --- a/examples/configcenter/zookeeper/jsonrpc/with-configcenter-go-server/profiles/test/server.yml +++ /dev/null @@ -1,25 +0,0 @@ -# dubbo server yaml configure file - -# application config - -services: - "UserProvider": - protocol : "jsonrpc" - # 相当于dubbo.xml中的interface - interface : "com.ikurento.user.UserProvider" - loadbalance: "random" - warmup: "100" - cluster: "failover" - methods: - - name: "GetUser" - retries: 1 - loadbalance: "random" - -config_center: - protocol: "zookeeper" - address: "127.0.0.1:2181" - group: "dubbo" - config_file: "dubbo.properties" - - - diff --git a/examples/consul/go-client/config/client.yml b/examples/consul/go-client/config/client.yml index 4c0acde0d5..556ac2b112 100644 --- a/examples/consul/go-client/config/client.yml +++ b/examples/consul/go-client/config/client.yml @@ -1,4 +1,4 @@ -application_config: +application: organization : "ikurento.com" name : "BDTService" module : "dubbogo user-info client" diff --git a/examples/consul/go-server/config/server.yml b/examples/consul/go-server/config/server.yml index aa105327f8..f3c169ab78 100644 --- a/examples/consul/go-server/config/server.yml +++ b/examples/consul/go-server/config/server.yml @@ -1,4 +1,4 @@ -application_config: +application: organization : "ikurento.com" name : "BDTService" module : "dubbogo user-info server" diff --git a/examples/general/dubbo/go-client/profiles/dev/client.yml b/examples/general/dubbo/go-client/profiles/dev/client.yml index 4c2ad17cb3..002da1ddb3 100644 --- a/examples/general/dubbo/go-client/profiles/dev/client.yml +++ b/examples/general/dubbo/go-client/profiles/dev/client.yml @@ -8,7 +8,7 @@ request_timeout : "3s" connect_timeout : "3s" # application config -application_config: +application: organization : "ikurento.com" name : "BDTService" module : "dubbogo user-info client" diff --git a/examples/general/dubbo/go-client/profiles/release/log.yml b/examples/general/dubbo/go-client/profiles/release/log.yml deleted file mode 100644 index e0514be020..0000000000 --- a/examples/general/dubbo/go-client/profiles/release/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "warn" -development: true -disableCaller: true -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/general/dubbo/go-client/profiles/test/client.yml b/examples/general/dubbo/go-client/profiles/test/client.yml deleted file mode 100644 index a9ebe3bb31..0000000000 --- a/examples/general/dubbo/go-client/profiles/test/client.yml +++ /dev/null @@ -1,83 +0,0 @@ -# dubbo client yaml configure file - - -check: true -# client -request_timeout : "3s" -# connect timeout -connect_timeout : "3s" - -# application config -application_config: - organization : "ikurento.com" - name : "BDTService" - module : "dubbogo user-info client" - version : "0.0.1" - owner : "ZX" - environment : "test" - -registries : - "hangzhouzk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2181" - username: "" - password: "" - "shanghaizk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2182" - username: "" - password: "" - -references: - "UserProvider": - # 可以指定多个registry,使用逗号隔开;不指定默认向所有注册中心注册 - registry: "hangzhouzk" - protocol : "dubbo" - interface : "com.ikurento.user.UserProvider" - cluster: "failover" - methods : - - name: "GetUser" - retries: "3" - "UserProvider1": - registry: "hangzhouzk" - protocol: "dubbo" - version: "2.0" - interface: "com.ikurento.user.UserProvider" - cluster: "failover" - methods: - - name: "GetUser" - retries: "3" - "UserProvider2": - registry: "hangzhouzk" - protocol: "dubbo" - version: "2.0" - group: "as" - interface: "com.ikurento.user.UserProvider" - cluster: "failover" - methods: - - name: "GetUser" - retries: "3" - -protocol_conf: - dubbo: - reconnect_interval: 0 - connection_number: 2 - heartbeat_period: "5s" - session_timeout: "20s" - pool_size: 64 - pool_ttl: 600 - getty_session_param: - compress_encoding: false - tcp_no_delay: true - tcp_keep_alive: true - keep_alive_period: "120s" - tcp_r_buf_size: 262144 - tcp_w_buf_size: 65536 - pkg_wq_size: 512 - tcp_read_timeout: "1s" - tcp_write_timeout: "5s" - wait_timeout: "1s" - max_msg_len: 10240 - session_name: "client" diff --git a/examples/general/dubbo/go-client/profiles/test/log.yml b/examples/general/dubbo/go-client/profiles/test/log.yml deleted file mode 100644 index baee0b7248..0000000000 --- a/examples/general/dubbo/go-client/profiles/test/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "info" -development: false -disableCaller: false -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/general/dubbo/go-server/profiles/dev/server.yml b/examples/general/dubbo/go-server/profiles/dev/server.yml index 576a944754..c936e12828 100644 --- a/examples/general/dubbo/go-server/profiles/dev/server.yml +++ b/examples/general/dubbo/go-server/profiles/dev/server.yml @@ -2,7 +2,7 @@ # application config -application_config: +application: organization : "ikurento.com" name : "BDTService" module : "dubbogo user-info server" diff --git a/examples/general/dubbo/go-server/profiles/release/log.yml b/examples/general/dubbo/go-server/profiles/release/log.yml deleted file mode 100644 index e0514be020..0000000000 --- a/examples/general/dubbo/go-server/profiles/release/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "warn" -development: true -disableCaller: true -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/general/dubbo/go-server/profiles/test/log.yml b/examples/general/dubbo/go-server/profiles/test/log.yml deleted file mode 100644 index baee0b7248..0000000000 --- a/examples/general/dubbo/go-server/profiles/test/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "info" -development: false -disableCaller: false -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/general/dubbo/go-server/profiles/test/server.yml b/examples/general/dubbo/go-server/profiles/test/server.yml deleted file mode 100644 index 0aab159b15..0000000000 --- a/examples/general/dubbo/go-server/profiles/test/server.yml +++ /dev/null @@ -1,91 +0,0 @@ -# dubbo server yaml configure file - - -# application config -application_config: - organization : "ikurento.com" - name : "BDTService" - module : "dubbogo user-info server" - version : "0.0.1" - owner : "ZX" - environment : "test" - -registries : - "hangzhouzk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2181" - username: "" - password: "" - "shanghaizk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2182" - username: "" - password: "" - - -services: - "UserProvider": - # 可以指定多个registry,使用逗号隔开;不指定默认向所有注册中心注册 - registry: "hangzhouzk" - protocol : "dubbo" - # 相当于dubbo.xml中的interface - interface : "com.ikurento.user.UserProvider" - loadbalance: "random" - warmup: "100" - cluster: "failover" - methods: - - name: "GetUser" - retries: "1" - loadbalance: "random" - "UserProvider1": - registry: "hangzhouzk" - protocol: "dubbo" - version: "2.0" - interface: "com.ikurento.user.UserProvider" - loadbalance: "random" - warmup: "100" - cluster: "failover" - methods: - - name: "GetUser" - retries: "1" - loadbalance: "random" - "UserProvider2": - registry: "hangzhouzk" - protocol: "dubbo" - version: "2.0" - group: "as" - interface: "com.ikurento.user.UserProvider" - loadbalance: "random" - warmup: "100" - cluster: "failover" - methods: - - name: "GetUser" - retries: "1" - loadbalance: "random" - -protocols: - "dubbo1": - name: "dubbo" - # ip : "127.0.0.1" - port: 20000 - - -protocol_conf: - dubbo: - session_number: 700 - session_timeout: "20s" - getty_session_param: - compress_encoding: false - tcp_no_delay: true - tcp_keep_alive: true - keep_alive_period: "120s" - tcp_r_buf_size: 262144 - tcp_w_buf_size: 65536 - pkg_wq_size: 512 - tcp_read_timeout: "1s" - tcp_write_timeout: "5s" - wait_timeout: "1s" - max_msg_len: 1024 - session_name: "server" diff --git a/examples/general/jsonrpc/go-client/app/client.go b/examples/general/jsonrpc/go-client/app/client.go index c281794df9..0248af70cc 100644 --- a/examples/general/jsonrpc/go-client/app/client.go +++ b/examples/general/jsonrpc/go-client/app/client.go @@ -98,7 +98,7 @@ func test() { println("res: %v", res) } - time.Sleep(3e9) + time.Sleep(10e9) println("\n\n\nstart to test jsonrpc") user := &JsonRPCUser{} diff --git a/examples/general/jsonrpc/go-client/profiles/dev/client.yml b/examples/general/jsonrpc/go-client/profiles/dev/client.yml index 8d2482f1b4..98c5c820e1 100644 --- a/examples/general/jsonrpc/go-client/profiles/dev/client.yml +++ b/examples/general/jsonrpc/go-client/profiles/dev/client.yml @@ -7,7 +7,7 @@ request_timeout : "3s" connect_timeout : "3s" # application config -application_config: +application: organization : "ikurento.com" name : "BDTService" module : "dubbogo user-info client" diff --git a/examples/general/jsonrpc/go-client/profiles/release/client.yml b/examples/general/jsonrpc/go-client/profiles/release/client.yml deleted file mode 100644 index 0084e5b04d..0000000000 --- a/examples/general/jsonrpc/go-client/profiles/release/client.yml +++ /dev/null @@ -1,60 +0,0 @@ -# dubbo client yaml configure file - -check: true -# client -request_timeout : "3s" -# connect timeout -connect_timeout : "3s" - -# application config -application_config: - organization : "ikurento.com" - name : "BDTService" - module : "dubbogo user-info client" - version : "0.0.1" - owner : "ZX" - environment : "release" - -registries : - "hangzhouzk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2181" - username: "" - password: "" - "shanghaizk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2182" - username: "" - password: "" - -references: - "UserProvider": - # 可以指定多个registry,使用逗号隔开;不指定默认向所有注册中心注册 - registry: "hangzhouzk" - protocol : "jsonrpc" - interface : "com.ikurento.user.UserProvider" - cluster: "failover" - methods : - - name: "GetUser" - retries: 3 - "UserProvider1": - registry: "hangzhouzk" - protocol: "jsonrpc" - version : "2.0" - interface: "com.ikurento.user.UserProvider" - cluster: "failover" - methods: - - name: "GetUser" - retries: 3 - "UserProvider2": - registry: "hangzhouzk" - protocol: "jsonrpc" - version : "2.0" - group: "as" - interface: "com.ikurento.user.UserProvider" - cluster: "failover" - methods: - - name: "GetUser" - retries: 3 diff --git a/examples/general/jsonrpc/go-client/profiles/release/log.yml b/examples/general/jsonrpc/go-client/profiles/release/log.yml deleted file mode 100644 index e0514be020..0000000000 --- a/examples/general/jsonrpc/go-client/profiles/release/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "warn" -development: true -disableCaller: true -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/general/jsonrpc/go-client/profiles/test/client.yml b/examples/general/jsonrpc/go-client/profiles/test/client.yml deleted file mode 100644 index 3efdedad4a..0000000000 --- a/examples/general/jsonrpc/go-client/profiles/test/client.yml +++ /dev/null @@ -1,60 +0,0 @@ -# dubbo client yaml configure file - -check: true -# client -request_timeout : "3s" -# connect timeout -connect_timeout : "3s" - -# application config -application_config: - organization : "ikurento.com" - name : "BDTService" - module : "dubbogo user-info client" - version : "0.0.1" - owner : "ZX" - environment : "test" - -registries : - "hangzhouzk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2181" - username: "" - password: "" - "shanghaizk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2182" - username: "" - password: "" - -references: - "UserProvider": - # 可以指定多个registry,使用逗号隔开;不指定默认向所有注册中心注册 - registry: "hangzhouzk" - protocol : "jsonrpc" - interface : "com.ikurento.user.UserProvider" - cluster: "failover" - methods : - - name: "GetUser" - retries: 3 - "UserProvider1": - registry: "hangzhouzk" - protocol: "jsonrpc" - version : "2.0" - interface: "com.ikurento.user.UserProvider" - cluster: "failover" - methods: - - name: "GetUser" - retries: 3 - "UserProvider2": - registry: "hangzhouzk" - protocol: "jsonrpc" - version : "2.0" - group: "as" - interface: "com.ikurento.user.UserProvider" - cluster: "failover" - methods: - - name: "GetUser" - retries: 3 diff --git a/examples/general/jsonrpc/go-client/profiles/test/log.yml b/examples/general/jsonrpc/go-client/profiles/test/log.yml deleted file mode 100644 index baee0b7248..0000000000 --- a/examples/general/jsonrpc/go-client/profiles/test/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "info" -development: false -disableCaller: false -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/general/jsonrpc/go-server/profiles/dev/server.yml b/examples/general/jsonrpc/go-server/profiles/dev/server.yml index 10a0898b26..f4a2766f48 100644 --- a/examples/general/jsonrpc/go-server/profiles/dev/server.yml +++ b/examples/general/jsonrpc/go-server/profiles/dev/server.yml @@ -1,7 +1,7 @@ # dubbo server yaml configure file # application config -application_config: +application: organization : "ikurento.com" name : "BDTService" module : "dubbogo user-info server" diff --git a/examples/general/jsonrpc/go-server/profiles/release/log.yml b/examples/general/jsonrpc/go-server/profiles/release/log.yml deleted file mode 100644 index e0514be020..0000000000 --- a/examples/general/jsonrpc/go-server/profiles/release/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "warn" -development: true -disableCaller: true -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/general/jsonrpc/go-server/profiles/release/server.yml b/examples/general/jsonrpc/go-server/profiles/release/server.yml deleted file mode 100644 index 3f7d2fdfff..0000000000 --- a/examples/general/jsonrpc/go-server/profiles/release/server.yml +++ /dev/null @@ -1,75 +0,0 @@ -# dubbo server yaml configure file - -# application config -application_config: - organization : "ikurento.com" - name : "BDTService" - module : "dubbogo user-info server" - version : "0.0.1" - owner : "ZX" - environment : "release" - -registries : - "hangzhouzk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2181" - username: "" - password: "" - "shanghaizk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2182" - username: "" - password: "" - - -services: - "UserProvider": - # 可以指定多个registry,使用逗号隔开;不指定默认向所有注册中心注册 - registry: "hangzhouzk" - protocol : "jsonrpc" - # 相当于dubbo.xml中的interface - interface : "com.ikurento.user.UserProvider" - loadbalance: "random" - warmup: "100" - cluster: "failover" - methods: - - name: "GetUser" - retries: 1 - loadbalance: "random" - "UserProvider1": - registry: "hangzhouzk" - protocol: "jsonrpc" - interface: "com.ikurento.user.UserProvider" - loadbalance: "random" - version: "2.0" - warmup: "100" - cluster: "failover" - methods: - - name: "GetUser" - retries: 1 - loadbalance: "random" - "UserProvider2": - registry: "hangzhouzk" - protocol: "jsonrpc" - interface: "com.ikurento.user.UserProvider" - loadbalance: "random" - version: "2.0" - group: "as" - warmup: "100" - cluster: "failover" - methods: - - name: "GetUser" - retries: 1 - loadbalance: "random" - -protocols: - #- name: "dubbo" - # ip : "127.0.0.1" - # port : 20000 - "jsonrpc1": - name: "jsonrpc" - ip: "127.0.0.1" - port: 20001 - diff --git a/examples/general/jsonrpc/go-server/profiles/test/log.yml b/examples/general/jsonrpc/go-server/profiles/test/log.yml deleted file mode 100644 index baee0b7248..0000000000 --- a/examples/general/jsonrpc/go-server/profiles/test/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "info" -development: false -disableCaller: false -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/general/jsonrpc/go-server/profiles/test/server.yml b/examples/general/jsonrpc/go-server/profiles/test/server.yml deleted file mode 100644 index dd0637e797..0000000000 --- a/examples/general/jsonrpc/go-server/profiles/test/server.yml +++ /dev/null @@ -1,75 +0,0 @@ -# dubbo server yaml configure file - -# application config -application_config: - organization : "ikurento.com" - name : "BDTService" - module : "dubbogo user-info server" - version : "0.0.1" - owner : "ZX" - environment : "test" - -registries : - "hangzhouzk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2181" - username: "" - password: "" - "shanghaizk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2182" - username: "" - password: "" - - -services: - "UserProvider": - # 可以指定多个registry,使用逗号隔开;不指定默认向所有注册中心注册 - registry: "hangzhouzk" - protocol : "jsonrpc" - # 相当于dubbo.xml中的interface - interface : "com.ikurento.user.UserProvider" - loadbalance: "random" - warmup: "100" - cluster: "failover" - methods: - - name: "GetUser" - retries: 1 - loadbalance: "random" - "UserProvider1": - registry: "hangzhouzk" - protocol: "jsonrpc" - interface: "com.ikurento.user.UserProvider" - loadbalance: "random" - version: "2.0" - warmup: "100" - cluster: "failover" - methods: - - name: "GetUser" - retries: 1 - loadbalance: "random" - "UserProvider2": - registry: "hangzhouzk" - protocol: "jsonrpc" - interface: "com.ikurento.user.UserProvider" - loadbalance: "random" - version: "2.0" - group: "as" - warmup: "100" - cluster: "failover" - methods: - - name: "GetUser" - retries: 1 - loadbalance: "random" - -protocols: - #- name: "dubbo" - # ip : "127.0.0.1" - # port : 20000 - "jsonrpc1": - name: "jsonrpc" - ip: "127.0.0.1" - port: 20001 - diff --git a/examples/generic/go-client/profiles/dev/client.yml b/examples/generic/go-client/profiles/dev/client.yml index f4e3180aa8..26752fb256 100644 --- a/examples/generic/go-client/profiles/dev/client.yml +++ b/examples/generic/go-client/profiles/dev/client.yml @@ -8,7 +8,7 @@ request_timeout : "3s" connect_timeout : "3s" # application config -application_config: +application: organization : "ikurento.com" name : "BDTService" module : "dubbogo genric client" diff --git a/examples/generic/go-client/profiles/release/client.yml b/examples/generic/go-client/profiles/release/client.yml deleted file mode 100644 index 5a21bca6c9..0000000000 --- a/examples/generic/go-client/profiles/release/client.yml +++ /dev/null @@ -1,55 +0,0 @@ -# dubbo client yaml configure file - - -check: true -# client -request_timeout : "3s" -# connect timeout -connect_timeout : "3s" - -# application config -application_config: - organization : "ikurento.com" - name : "BDTService" - module : "dubbogo generic client" - version : "0.0.1" - owner : "ZX" - environment : "release" - -registries : - "hangzhouzk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2181" - username: "" - password: "" - "shanghaizk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2182" - username: "" - password: "" - -references: - -protocol_conf: - dubbo: - reconnect_interval: 0 - connection_number: 2 - heartbeat_period: "5s" - session_timeout: "20s" - pool_size: 64 - pool_ttl: 600 - getty_session_param: - compress_encoding: false - tcp_no_delay: true - tcp_keep_alive: true - keep_alive_period: "120s" - tcp_r_buf_size: 262144 - tcp_w_buf_size: 65536 - pkg_wq_size: 512 - tcp_read_timeout: "1s" - tcp_write_timeout: "5s" - wait_timeout: "1s" - max_msg_len: 10240 - session_name: "client" diff --git a/examples/generic/go-client/profiles/release/log.yml b/examples/generic/go-client/profiles/release/log.yml deleted file mode 100644 index e0514be020..0000000000 --- a/examples/generic/go-client/profiles/release/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "warn" -development: true -disableCaller: true -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/generic/go-client/profiles/test/client.yml b/examples/generic/go-client/profiles/test/client.yml deleted file mode 100644 index 7442c64c71..0000000000 --- a/examples/generic/go-client/profiles/test/client.yml +++ /dev/null @@ -1,55 +0,0 @@ -# dubbo client yaml configure file - - -check: true -# client -request_timeout : "3s" -# connect timeout -connect_timeout : "3s" - -# application config -application_config: - organization : "ikurento.com" - name : "BDTService" - module : "dubbogo user-info client" - version : "0.0.1" - owner : "ZX" - environment : "test" - -registries : - "hangzhouzk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2181" - username: "" - password: "" - "shanghaizk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2182" - username: "" - password: "" - -references: - -protocol_conf: - dubbo: - reconnect_interval: 0 - connection_number: 2 - heartbeat_period: "5s" - session_timeout: "20s" - pool_size: 64 - pool_ttl: 600 - getty_session_param: - compress_encoding: false - tcp_no_delay: true - tcp_keep_alive: true - keep_alive_period: "120s" - tcp_r_buf_size: 262144 - tcp_w_buf_size: 65536 - pkg_wq_size: 512 - tcp_read_timeout: "1s" - tcp_write_timeout: "5s" - wait_timeout: "1s" - max_msg_len: 10240 - session_name: "client" diff --git a/examples/generic/go-client/profiles/test/log.yml b/examples/generic/go-client/profiles/test/log.yml deleted file mode 100644 index baee0b7248..0000000000 --- a/examples/generic/go-client/profiles/test/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "info" -development: false -disableCaller: false -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/helloworld/dubbo/go-client/profiles/dev/client.yml b/examples/helloworld/dubbo/go-client/profiles/dev/client.yml index 226fbddd1a..6fcc678342 100644 --- a/examples/helloworld/dubbo/go-client/profiles/dev/client.yml +++ b/examples/helloworld/dubbo/go-client/profiles/dev/client.yml @@ -8,7 +8,7 @@ request_timeout : "3s" connect_timeout : "3s" # application config -application_config: +application: organization : "ikurento.com" name : "BDTService" module : "dubbogo user-info client" diff --git a/examples/helloworld/dubbo/go-client/profiles/release/client.yml b/examples/helloworld/dubbo/go-client/profiles/release/client.yml deleted file mode 100644 index 02bf722754..0000000000 --- a/examples/helloworld/dubbo/go-client/profiles/release/client.yml +++ /dev/null @@ -1,60 +0,0 @@ -# dubbo client yaml configure file - - -check: true -# client -request_timeout : "3s" -# connect timeout -connect_timeout : "3s" - -# application config -application_config: - organization : "ikurento.com" - name : "BDTService" - module : "dubbogo user-info client" - version : "0.0.1" - owner : "ZX" - environment : "release" - -registries : - "hangzhouzk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2181" - username: "" - password: "" - - -references: - "UserProvider": - # 可以指定多个registry,使用逗号隔开;不指定默认向所有注册中心注册 - registry: "hangzhouzk" - protocol : "dubbo" - interface : "com.ikurento.user.UserProvider" - cluster: "failover" - methods : - - name: "GetUser" - retries: 3 - -protocol_conf: - dubbo: - reconnect_interval: 0 - connection_number: 2 - heartbeat_period: "5s" - session_timeout: "20s" - pool_size: 64 - pool_ttl: 600 - getty_session_param: - compress_encoding: false - tcp_no_delay: true - tcp_keep_alive: true - keep_alive_period: "120s" - tcp_r_buf_size: 262144 - tcp_w_buf_size: 65536 - pkg_rq_size: 1024 - pkg_wq_size: 512 - tcp_read_timeout: "1s" - tcp_write_timeout: "5s" - wait_timeout: "1s" - max_msg_len: 10240 - session_name: "client" diff --git a/examples/helloworld/dubbo/go-client/profiles/release/log.yml b/examples/helloworld/dubbo/go-client/profiles/release/log.yml deleted file mode 100644 index e0514be020..0000000000 --- a/examples/helloworld/dubbo/go-client/profiles/release/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "warn" -development: true -disableCaller: true -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/helloworld/dubbo/go-client/profiles/test/client.yml b/examples/helloworld/dubbo/go-client/profiles/test/client.yml deleted file mode 100644 index 417a388c6c..0000000000 --- a/examples/helloworld/dubbo/go-client/profiles/test/client.yml +++ /dev/null @@ -1,59 +0,0 @@ -# dubbo client yaml configure file - - -check: true -# client -request_timeout : "3s" -# connect timeout -connect_timeout : "3s" - -# application config -application_config: - organization : "ikurento.com" - name : "BDTService" - module : "dubbogo user-info client" - version : "0.0.1" - owner : "ZX" - environment : "test" - -registries : - "hangzhouzk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2181" - username: "" - password: "" - -references: - "UserProvider": - # 可以指定多个registry,使用逗号隔开;不指定默认向所有注册中心注册 - registry: "hangzhouzk" - protocol : "dubbo" - interface : "com.ikurento.user.UserProvider" - cluster: "failover" - methods : - - name: "GetUser" - retries: 3 - -protocol_conf: - dubbo: - reconnect_interval: 0 - connection_number: 2 - heartbeat_period: "5s" - session_timeout: "20s" - pool_size: 64 - pool_ttl: 600 - getty_session_param: - compress_encoding: false - tcp_no_delay: true - tcp_keep_alive: true - keep_alive_period: "120s" - tcp_r_buf_size: 262144 - tcp_w_buf_size: 65536 - pkg_rq_size: 1024 - pkg_wq_size: 512 - tcp_read_timeout: "1s" - tcp_write_timeout: "5s" - wait_timeout: "1s" - max_msg_len: 10240 - session_name: "client" diff --git a/examples/helloworld/dubbo/go-client/profiles/test/log.yml b/examples/helloworld/dubbo/go-client/profiles/test/log.yml deleted file mode 100644 index baee0b7248..0000000000 --- a/examples/helloworld/dubbo/go-client/profiles/test/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "info" -development: false -disableCaller: false -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/helloworld/dubbo/go-server/profiles/dev/server.yml b/examples/helloworld/dubbo/go-server/profiles/dev/server.yml index 7df17934f6..8e8594a1ce 100644 --- a/examples/helloworld/dubbo/go-server/profiles/dev/server.yml +++ b/examples/helloworld/dubbo/go-server/profiles/dev/server.yml @@ -2,7 +2,7 @@ # application config -application_config: +application: organization : "ikurento.com" name : "BDTService" module : "dubbogo user-info server" @@ -30,6 +30,7 @@ services: - name: "GetUser" retries: "1" loadbalance: "random" + token: "true" protocols: "dubbo": diff --git a/examples/helloworld/dubbo/go-server/profiles/release/log.yml b/examples/helloworld/dubbo/go-server/profiles/release/log.yml deleted file mode 100644 index e0514be020..0000000000 --- a/examples/helloworld/dubbo/go-server/profiles/release/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "warn" -development: true -disableCaller: true -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/helloworld/dubbo/go-server/profiles/release/server.yml b/examples/helloworld/dubbo/go-server/profiles/release/server.yml deleted file mode 100644 index 4786e83669..0000000000 --- a/examples/helloworld/dubbo/go-server/profiles/release/server.yml +++ /dev/null @@ -1,62 +0,0 @@ -# dubbo server yaml configure file - - -# application config -application_config: - organization : "ikurento.com" - name : "BDTService" - module : "dubbogo user-info server" - version : "0.0.1" - owner : "ZX" - environment : "release" - -registries : - "hangzhouzk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2181" - username: "" - password: "" - - -services: - "UserProvider": - # 可以指定多个registry,使用逗号隔开;不指定默认向所有注册中心注册 - registry: "hangzhouzk" - protocol : "dubbo" - # 相当于dubbo.xml中的interface - interface : "com.ikurento.user.UserProvider" - loadbalance: "random" - warmup: "100" - cluster: "failover" - methods: - - name: "GetUser" - retries: 1 - loadbalance: "random" - - -protocols: - "dubbo1": - name: "dubbo" - # ip : "127.0.0.1" - port: 20000 - - -protocol_conf: - dubbo: - session_number: 700 - session_timeout: "20s" - getty_session_param: - compress_encoding: false - tcp_no_delay: true - tcp_keep_alive: true - keep_alive_period: "120s" - tcp_r_buf_size: 262144 - tcp_w_buf_size: 65536 - pkg_rq_size: 1024 - pkg_wq_size: 512 - tcp_read_timeout: "1s" - tcp_write_timeout: "5s" - wait_timeout: "1s" - max_msg_len: 1024 - session_name: "server" diff --git a/examples/helloworld/dubbo/go-server/profiles/test/log.yml b/examples/helloworld/dubbo/go-server/profiles/test/log.yml deleted file mode 100644 index baee0b7248..0000000000 --- a/examples/helloworld/dubbo/go-server/profiles/test/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "info" -development: false -disableCaller: false -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/helloworld/dubbo/go-server/profiles/test/server.yml b/examples/helloworld/dubbo/go-server/profiles/test/server.yml deleted file mode 100644 index ba6eb2b800..0000000000 --- a/examples/helloworld/dubbo/go-server/profiles/test/server.yml +++ /dev/null @@ -1,62 +0,0 @@ -# dubbo server yaml configure file - - -# application config -application_config: - organization : "ikurento.com" - name : "BDTService" - module : "dubbogo user-info server" - version : "0.0.1" - owner : "ZX" - environment : "test" - -registries : - "hangzhouzk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2181" - username: "" - password: "" - - - -services: - "UserProvider": - # 可以指定多个registry,使用逗号隔开;不指定默认向所有注册中心注册 - registry: "hangzhouzk" - protocol : "dubbo" - # 相当于dubbo.xml中的interface - interface : "com.ikurento.user.UserProvider" - loadbalance: "random" - warmup: "100" - cluster: "failover" - methods: - - name: "GetUser" - retries: 1 - loadbalance: "random" - -protocols: - "dubbo1": - name: "dubbo" - # ip : "127.0.0.1" - port: 20000 - - -protocol_conf: - dubbo: - session_number: 700 - session_timeout: "20s" - getty_session_param: - compress_encoding: false - tcp_no_delay: true - tcp_keep_alive: true - keep_alive_period: "120s" - tcp_r_buf_size: 262144 - tcp_w_buf_size: 65536 - pkg_rq_size: 1024 - pkg_wq_size: 512 - tcp_read_timeout: "1s" - tcp_write_timeout: "5s" - wait_timeout: "1s" - max_msg_len: 1024 - session_name: "server" diff --git a/examples/hystrixfilter/dubbo/with-hystrix-go-client/profiles/dev/client.yml b/examples/hystrixfilter/dubbo/with-hystrix-go-client/profiles/dev/client.yml index 4a438cc953..8602b3a190 100644 --- a/examples/hystrixfilter/dubbo/with-hystrix-go-client/profiles/dev/client.yml +++ b/examples/hystrixfilter/dubbo/with-hystrix-go-client/profiles/dev/client.yml @@ -8,7 +8,7 @@ request_timeout : "3s" connect_timeout : "3s" # application config -application_config: +application: organization : "ikurento.com" name : "BDTService" module : "dubbogo user-info client" diff --git a/examples/hystrixfilter/dubbo/with-hystrix-go-client/profiles/release/client.yml b/examples/hystrixfilter/dubbo/with-hystrix-go-client/profiles/release/client.yml deleted file mode 100644 index 9263f2d01f..0000000000 --- a/examples/hystrixfilter/dubbo/with-hystrix-go-client/profiles/release/client.yml +++ /dev/null @@ -1,98 +0,0 @@ -# dubbo client yaml configure file - - -check: true -# client -request_timeout : "3s" -# connect timeout -connect_timeout : "3s" - -# application config -application_config: - organization : "ikurento.com" - name : "BDTService" - module : "dubbogo user-info client" - version : "0.0.1" - owner : "ZX" - environment : "release" - -registries : - "hangzhouzk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2181" - username: "" - password: "" - "shanghaizk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2182" - username: "" - password: "" - -references: - "UserProvider": - # 可以指定多个registry,使用逗号隔开;不指定默认向所有注册中心注册 - registry: "hangzhouzk" - filter: "example_fallback,hystrix_consumer" - protocol : "dubbo" -# version: "2.0" -# group: "as" - interface : "com.ikurento.user.UserProvider" - cluster: "failover" - methods : - - name: "GetUser" - retries: 3 - -protocol_conf: - dubbo: - reconnect_interval: 0 - connection_number: 2 - heartbeat_period: "5s" - session_timeout: "20s" - fail_fast_timeout: "5s" - pool_size: 64 - pool_ttl: 600 - getty_session_param: - compress_encoding: false - tcp_no_delay: true - tcp_keep_alive: true - keep_alive_period: "120s" - tcp_r_buf_size: 262144 - tcp_w_buf_size: 65536 - pkg_rq_size: 1024 - pkg_wq_size: 512 - tcp_read_timeout: "1s" - tcp_write_timeout: "5s" - wait_timeout: "1s" - max_msg_len: 10240 - session_name: "client" - -filter_conf: - hystrix: - configs: - "Default": - timeout : 1000 - max_concurrent_requests : 10 - sleep_window : 5000 - error_percent_threshold : 50 - request_volume_threshold: 20 - "userp": - timeout: 1200 - max_concurrent_requests: 8 - sleep_window: 4000 - error_percent_threshold: 45 - request_volume_threshold: 15 - "userp_m": - timeout : 1200 - max_concurrent_requests : 12 - sleep_window : 6000 - error_percent_threshold : 60 - request_volume_threshold: 30 - fallback: "exampleFallback" - default: "Default" - services: - "com.ikurento.user.UserProvider": - service_config: "userp" - methods: - "GetUser": "userp_m" diff --git a/examples/hystrixfilter/dubbo/with-hystrix-go-client/profiles/release/log.yml b/examples/hystrixfilter/dubbo/with-hystrix-go-client/profiles/release/log.yml deleted file mode 100644 index d8606247b8..0000000000 --- a/examples/hystrixfilter/dubbo/with-hystrix-go-client/profiles/release/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "warn" -development: true -disableCaller: true -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/examples/hystrixfilter/dubbo/with-hystrix-go-client/profiles/test/client.yml b/examples/hystrixfilter/dubbo/with-hystrix-go-client/profiles/test/client.yml deleted file mode 100644 index 048703b6bb..0000000000 --- a/examples/hystrixfilter/dubbo/with-hystrix-go-client/profiles/test/client.yml +++ /dev/null @@ -1,99 +0,0 @@ -# dubbo client yaml configure file - - -check: true -# client -request_timeout : "3s" -# connect timeout -connect_timeout : "3s" - -# application config -application_config: - organization : "ikurento.com" - name : "BDTService" - module : "dubbogo user-info client" - version : "0.0.1" - owner : "ZX" - environment : "test" - -registries : - "hangzhouzk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2181" - username: "" - password: "" - "shanghaizk": - protocol: "zookeeper" - timeout : "3s" - address: "127.0.0.1:2182" - username: "" - password: "" - -references: - "UserProvider": - # 可以指定多个registry,使用逗号隔开;不指定默认向所有注册中心注册 - registry: "hangzhouzk" - filter: "example_fallback,hystrix_consumer" - protocol : "dubbo" -# version: "2.0" -# group: "as" - interface : "com.ikurento.user.UserProvider" - cluster: "failover" - methods : - - name: "GetUser" - retries: 3 - -protocol_conf: - dubbo: - reconnect_interval: 0 - connection_number: 2 - heartbeat_period: "5s" - session_timeout: "20s" - fail_fast_timeout: "5s" - pool_size: 64 - pool_ttl: 600 - getty_session_param: - compress_encoding: false - tcp_no_delay: true - tcp_keep_alive: true - keep_alive_period: "120s" - tcp_r_buf_size: 262144 - tcp_w_buf_size: 65536 - pkg_rq_size: 1024 - pkg_wq_size: 512 - tcp_read_timeout: "1s" - tcp_write_timeout: "5s" - wait_timeout: "1s" - max_msg_len: 10240 - session_name: "client" - -filter_conf: - hystrix: - configs: - "Default": - timeout : 1000 - max_concurrent_requests : 25 - sleep_window : 5000 - error_percent_threshold : 50 - request_volume_threshold: 20 - "userp": - timeout: 2000 - max_concurrent_requests: 512 - sleep_window: 4000 - error_percent_threshold: 35 - request_volume_threshold: 6 - "userp_m": - timeout : 1200 - max_concurrent_requests : 512 - sleep_window : 6000 - error_percent_threshold : 60 - request_volume_threshold: 16 - error_whitelist: [".*exception.*"] - default: "Default" - services: - "com.ikurento.user.UserProvider": - service_config: "userp" - methods: - "GetUser": "userp_m" - "GetUser1": "userp_m" \ No newline at end of file diff --git a/examples/hystrixfilter/dubbo/with-hystrix-go-client/profiles/test/log.yml b/examples/hystrixfilter/dubbo/with-hystrix-go-client/profiles/test/log.yml deleted file mode 100644 index f93d3c7fcc..0000000000 --- a/examples/hystrixfilter/dubbo/with-hystrix-go-client/profiles/test/log.yml +++ /dev/null @@ -1,28 +0,0 @@ - -level: "info" -development: false -disableCaller: false -disableStacktrace: true -sampling: -encoding: "console" - -# encoder -encoderConfig: - messageKey: "message" - levelKey: "level" - timeKey: "time" - nameKey: "logger" - callerKey: "caller" - stacktraceKey: "stacktrace" - lineEnding: "" - levelEncoder: "capitalColor" - timeEncoder: "iso8601" - durationEncoder: "seconds" - callerEncoder: "short" - nameEncoder: "" - -outputPaths: - - "stderr" -errorOutputPaths: - - "stderr" -initialFields: diff --git a/filter/impl/token_filter.go b/filter/impl/token_filter.go new file mode 100644 index 0000000000..d10dff5b76 --- /dev/null +++ b/filter/impl/token_filter.go @@ -0,0 +1,66 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package impl + +import ( + "strings" +) + +import ( + perrors "github.com/pkg/errors" +) + +import ( + "github.com/apache/dubbo-go/common/constant" + "github.com/apache/dubbo-go/common/extension" + "github.com/apache/dubbo-go/filter" + "github.com/apache/dubbo-go/protocol" +) + +const ( + TOKEN = "token" +) + +func init() { + extension.SetFilter(TOKEN, GetTokenFilter) +} + +type TokenFilter struct{} + +func (tf *TokenFilter) Invoke(invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result { + invokerTkn := invoker.GetUrl().GetParam(constant.TOKEN_KEY, "") + if len(invokerTkn) > 0 { + attachs := invocation.Attachments() + remoteTkn, exist := attachs[constant.TOKEN_KEY] + if exist && strings.EqualFold(invokerTkn, remoteTkn) { + return invoker.Invoke(invocation) + } + return &protocol.RPCResult{Err: perrors.Errorf("Invalid token! Forbid invoke remote service %v method %s ", + invoker, invocation.MethodName())} + } + + return invoker.Invoke(invocation) +} + +func (tf *TokenFilter) OnResponse(result protocol.Result, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result { + return result +} + +func GetTokenFilter() filter.Filter { + return &TokenFilter{} +} diff --git a/filter/impl/token_filter_test.go b/filter/impl/token_filter_test.go new file mode 100644 index 0000000000..1473f27403 --- /dev/null +++ b/filter/impl/token_filter_test.go @@ -0,0 +1,85 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package impl + +import ( + "net/url" + "testing" +) + +import ( + "github.com/stretchr/testify/assert" +) + +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" +) + +func TestTokenFilter_Invoke(t *testing.T) { + filter := GetTokenFilter() + + url := common.NewURLWithOptions( + common.WithParams(url.Values{}), + common.WithParamsValue(constant.TOKEN_KEY, "ori_key")) + attch := make(map[string]string, 0) + attch[constant.TOKEN_KEY] = "ori_key" + result := filter.Invoke(protocol.NewBaseInvoker(*url), + invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch)) + assert.Nil(t, result.Error()) + assert.Nil(t, result.Result()) +} + +func TestTokenFilter_InvokeEmptyToken(t *testing.T) { + filter := GetTokenFilter() + + url := common.URL{} + attch := make(map[string]string, 0) + attch[constant.TOKEN_KEY] = "ori_key" + result := filter.Invoke(protocol.NewBaseInvoker(url), + invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch)) + assert.Nil(t, result.Error()) + assert.Nil(t, result.Result()) +} + +func TestTokenFilter_InvokeEmptyAttach(t *testing.T) { + filter := GetTokenFilter() + + url := common.NewURLWithOptions( + common.WithParams(url.Values{}), + common.WithParamsValue(constant.TOKEN_KEY, "ori_key")) + attch := make(map[string]string, 0) + result := filter.Invoke(protocol.NewBaseInvoker(*url), + invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch)) + assert.NotNil(t, result.Error()) +} + +func TestTokenFilter_InvokeNotEqual(t *testing.T) { + filter := GetTokenFilter() + + url := common.NewURLWithOptions( + common.WithParams(url.Values{}), + common.WithParamsValue(constant.TOKEN_KEY, "ori_key")) + attch := make(map[string]string, 0) + attch[constant.TOKEN_KEY] = "err_key" + result := filter.Invoke(protocol.NewBaseInvoker(*url), + invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch)) + assert.NotNil(t, result.Error()) +} diff --git a/go.mod b/go.mod index 2645590296..09948c93c5 100644 --- a/go.mod +++ b/go.mod @@ -11,6 +11,7 @@ require ( github.com/coreos/go-semver v0.3.0 // indirect github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f // indirect github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f // indirect + github.com/creasty/defaults v1.3.0 github.com/dubbogo/getty v1.2.2 github.com/dubbogo/gost v1.1.1 github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239 // indirect @@ -24,6 +25,7 @@ require ( github.com/hashicorp/consul v1.5.3 github.com/hashicorp/consul/api v1.1.0 github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869 // indirect + github.com/jinzhu/copier v0.0.0-20190625015134-976e0346caa8 github.com/jonboulle/clockwork v0.1.0 // indirect github.com/lestrrat/go-envload v0.0.0-20180220120943-6ed08b54a570 // indirect github.com/lestrrat/go-file-rotatelogs v0.0.0-20180223000712-d3151e2a480f // indirect @@ -33,6 +35,7 @@ require ( github.com/pkg/errors v0.8.1 github.com/prometheus/client_golang v1.1.0 // indirect github.com/samuel/go-zookeeper v0.0.0-20180130194729-c4fab1ac1bec + github.com/satori/go.uuid v1.2.0 github.com/smartystreets/goconvey v0.0.0-20190710185942-9d28bd7c0945 // indirect github.com/soheilhy/cmux v0.1.4 // indirect github.com/stretchr/testify v1.3.0 diff --git a/go.sum b/go.sum index b04deb3169..1452a76298 100644 --- a/go.sum +++ b/go.sum @@ -39,7 +39,6 @@ github.com/apache/dubbo-go-hessian2 v1.2.5-0.20190909140437-80cbb25cbb22 h1:Ku+3 github.com/apache/dubbo-go-hessian2 v1.2.5-0.20190909140437-80cbb25cbb22/go.mod h1:LWnndnrFXZmJLAzoyNAPNHSIJ1KOHVkTSsHgC3YYWlo= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e h1:QEF07wC0T1rKkctt1RINW/+RMTVmiwxETico2l3gxJA= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= -github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da h1:8GUt8eRujhVEGZFFEjBj46YV4rDjvGrNxb0KMWYkL2I= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-metrics v0.0.0-20190430140413-ec5e00d3c878 h1:EFSB7Zo9Eg91v7MJPVsifUysc/wPdN+NOnVe6bWbdBM= github.com/armon/go-metrics v0.0.0-20190430140413-ec5e00d3c878/go.mod h1:3AMJUQhVx52RsWOnlkpikZr01T/yAVN2gn0861vByNg= @@ -85,6 +84,8 @@ github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f h1:JOrtw2xFKzlg+ github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f h1:lBNOc5arjvs8E5mO2tbpBpLoyyu8B6e44T7hJy6potg= github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= +github.com/creasty/defaults v1.3.0 h1:uG+RAxYbJgOPCOdKEcec9ZJXeva7Y6mj/8egdzwmLtw= +github.com/creasty/defaults v1.3.0/go.mod h1:CIEEvs7oIVZm30R8VxtFJs+4k201gReYyuYHJxZc68I= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -183,7 +184,7 @@ github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGa github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= -github.com/gotestyourself/gotestyourself v2.2.0+incompatible h1:AQwinXlbQR2HvPjQZOmDhRqsv5mZf+Jb1RnSLxcqZcI= +github.com/gotestyourself/gotestyourself v2.2.0+incompatible h1:1yOKgt0XYKUg1HOKunGOSt2ocU4bxLCjmIHt0vRtVHM= github.com/gotestyourself/gotestyourself v2.2.0+incompatible/go.mod h1:zZKM6oeNM8k+FRljX1mnzVYeS8wiGgQyvST1/GafPbY= github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7 h1:pdN6V1QBWetyv/0+wjACpqVH+eVULgEjkurDLq3goeM= github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= @@ -217,7 +218,6 @@ github.com/hashicorp/go-immutable-radix v1.0.0 h1:AKDB1HM5PWEA7i4nhcpwOrO2byshxB github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= github.com/hashicorp/go-memdb v0.0.0-20180223233045-1289e7fffe71 h1:yxxFgVz31vFoKKTtRUNbXLNe4GFnbLKqg+0N7yG42L8= github.com/hashicorp/go-memdb v0.0.0-20180223233045-1289e7fffe71/go.mod h1:kbfItVoBJwCfKXDXN4YoAXjxcFVZ7MRrJzyTX6H4giE= -github.com/hashicorp/go-msgpack v0.5.3 h1:zKjpN5BK/P5lMYrLmBHdBULWbJ0XpYR+7NGzqkZzoD4= github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= github.com/hashicorp/go-msgpack v0.5.5 h1:i9R9JSrqIz0QVLz3sz+i3YJdT7TTSLcfLLzJi9aZTuI= github.com/hashicorp/go-msgpack v0.5.5/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= @@ -252,7 +252,6 @@ github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= github.com/hashicorp/mdns v1.0.1 h1:XFSOubp8KWB+Jd2PDyaX5xUd5bhSP/+pTDZVDMzZJM8= github.com/hashicorp/mdns v1.0.1/go.mod h1:4gW7WsVCke5TE7EPeYliwHlRUyBtfCwuFwuMg2DmyNY= -github.com/hashicorp/memberlist v0.1.3 h1:EmmoJme1matNzb+hMpDuR/0sbJSUisxyqBGG676r31M= github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= github.com/hashicorp/memberlist v0.1.4 h1:gkyML/r71w3FL8gUi74Vk76avkj/9lYAY9lvg0OcoGs= github.com/hashicorp/memberlist v0.1.4/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= @@ -281,6 +280,8 @@ github.com/jefferai/jsonx v0.0.0-20160721235117-9cc31c3135ee h1:AQ/QmCk6x8ECPpf2 github.com/jefferai/jsonx v0.0.0-20160721235117-9cc31c3135ee/go.mod h1:N0t2vlmpe8nyZB5ouIbJQPDSR+mH6oe7xHB9VZHSUzM= github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869 h1:IPJ3dvxmJ4uczJe5YQdrYB16oTJlGSC/OyZDqUk9xX4= github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869/go.mod h1:cJ6Cj7dQo+O6GJNiMx+Pa94qKj+TG8ONdKHgMNIyyag= +github.com/jinzhu/copier v0.0.0-20190625015134-976e0346caa8 h1:mGIXW/lubQ4B+3bXTLxcTMTjUNDqoF6T/HUW9LbFx9s= +github.com/jinzhu/copier v0.0.0-20190625015134-976e0346caa8/go.mod h1:yL958EeXv8Ylng6IfnvG4oflryUi3vgA3xPs9hmII1s= github.com/jmespath/go-jmespath v0.0.0-20160202185014-0b12d6b521d8/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= @@ -294,8 +295,6 @@ github.com/json-iterator/go v1.1.7 h1:KfgG9LzI+pYjr4xvmz/5H4FXjokeP+rlHLhv3iH62F github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/jtolds/gls v4.2.1+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= -github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= -github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/keybase/go-crypto v0.0.0-20180614160407-5114a9a81e1b h1:VE6r2OwP5gj+Z9aCkSKl3MlmnZbfMAjhvR5T7abKHEo= @@ -372,7 +371,6 @@ github.com/ory/dockertest v3.3.4+incompatible h1:VrpM6Gqg7CrPm3bL4Wm1skO+zFWLbh7 github.com/ory/dockertest v3.3.4+incompatible/go.mod h1:1vX4m9wsvi00u5bseYwXaSnhNrne+V0E6LAcBILJdPs= github.com/packethost/packngo v0.1.1-0.20180711074735-b9cb5096f54c h1:vwpFWvAO8DeIZfFeqASzZfsxuWPno9ncAebBEP0N3uE= github.com/packethost/packngo v0.1.1-0.20180711074735-b9cb5096f54c/go.mod h1:otzZQXgoO96RTzDB/Hycg0qZcXZsWJGJRSXbmEIJ+4M= -github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c h1:Lgl0gzECD8GnQ5QCWA8o6BtfL6mDH5rQgM4/fX3avOs= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY= github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= @@ -425,8 +423,6 @@ github.com/sirupsen/logrus v1.2.0 h1:juTguoYk5qI21pwyTXY3B3Y5cOTH3ZUyZCg1v/mihuo github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/smartystreets/assertions v0.0.0-20180820201707-7c9eb446e3cf/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= -github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= -github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v0.0.0-20180222194500-ef6db91d284a/go.mod h1:XDJAKZRPZ1CvBcN2aX5YOUTYGHki24fSF0Iv48Ibg0s= github.com/smartystreets/goconvey v0.0.0-20190330032615-68dc04aab96a h1:pa8hGb/2YqsZKovtsgrwcDH1RZhVbTKCjLp47XpqCDs= @@ -557,7 +553,7 @@ gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bl gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= +gotest.tools v2.2.0+incompatible h1:y0IMTfclpMdsdIbr6uwmJn5/WZ7vFuObxDMdrylFM3A= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/protocol/dubbo/dubbo_invoker.go b/protocol/dubbo/dubbo_invoker.go index 4bfc1324cf..bc321a97a4 100644 --- a/protocol/dubbo/dubbo_invoker.go +++ b/protocol/dubbo/dubbo_invoker.go @@ -36,6 +36,10 @@ import ( var Err_No_Reply = perrors.New("request need @response") +var ( + attachmentKey = []string{constant.INTERFACE_KEY, constant.GROUP_KEY, constant.TOKEN_KEY, constant.TIMEOUT_KEY} +) + type DubboInvoker struct { protocol.BaseInvoker client *Client @@ -57,6 +61,11 @@ func (di *DubboInvoker) Invoke(invocation protocol.Invocation) protocol.Result { ) inv := invocation.(*invocation_impl.RPCInvocation) + for _, k := range attachmentKey { + if v := di.GetUrl().GetParam(k, ""); len(v) > 0 { + inv.SetAttachments(k, v) + } + } url := di.GetUrl() // async async, err := strconv.ParseBool(inv.AttachmentsByKey(constant.ASYNC_KEY, "false")) diff --git a/registry/base_configuration_listener.go b/registry/base_configuration_listener.go new file mode 100644 index 0000000000..925baa2198 --- /dev/null +++ b/registry/base_configuration_listener.go @@ -0,0 +1,99 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package registry + +import ( + perrors "github.com/pkg/errors" +) +import ( + "github.com/apache/dubbo-go/common" + "github.com/apache/dubbo-go/common/config" + "github.com/apache/dubbo-go/common/constant" + "github.com/apache/dubbo-go/common/logger" + "github.com/apache/dubbo-go/config_center" + "github.com/apache/dubbo-go/remoting" +) + +type BaseConfigurationListener struct { + configurators []config_center.Configurator + dynamicConfiguration config_center.DynamicConfiguration + defaultConfiguratorFunc func(url *common.URL) config_center.Configurator +} + +func (bcl *BaseConfigurationListener) Configurators() []config_center.Configurator { + return bcl.configurators +} +func (bcl *BaseConfigurationListener) InitWith(key string, listener config_center.ConfigurationListener, f func(url *common.URL) config_center.Configurator) { + bcl.dynamicConfiguration = config.GetEnvInstance().GetDynamicConfiguration() + if bcl.dynamicConfiguration == nil { + //set configurators to empty + bcl.configurators = []config_center.Configurator{} + return + } + bcl.defaultConfiguratorFunc = f + bcl.dynamicConfiguration.AddListener(key, listener) + if rawConfig, err := bcl.dynamicConfiguration.GetConfig(key, config_center.WithGroup(constant.DUBBO)); err != nil { + //set configurators to empty + bcl.configurators = []config_center.Configurator{} + return + } else if len(rawConfig) > 0 { + bcl.genConfiguratorFromRawRule(rawConfig) + } +} + +func (bcl *BaseConfigurationListener) Process(event *config_center.ConfigChangeEvent) { + logger.Infof("Notification of overriding rule, change type is: %v , raw config content is:%v", event.ConfigType, event.Value) + if event.ConfigType == remoting.EventTypeDel { + bcl.configurators = nil + } else { + if err := bcl.genConfiguratorFromRawRule(event.Value.(string)); err != nil { + logger.Error(perrors.WithStack(err)) + } + } +} + +func (bcl *BaseConfigurationListener) genConfiguratorFromRawRule(rawConfig string) error { + urls, err := bcl.dynamicConfiguration.Parser().ParseToUrls(rawConfig) + if err != nil { + return perrors.WithMessage(err, "Failed to parse raw dynamic config and it will not take effect, the raw config is: "+ + rawConfig) + } + bcl.configurators = ToConfigurators(urls, bcl.defaultConfiguratorFunc) + return nil +} +func (bcl *BaseConfigurationListener) OverrideUrl(url *common.URL) { + for _, v := range bcl.configurators { + v.Configure(url) + } +} + +func ToConfigurators(urls []*common.URL, f func(url *common.URL) config_center.Configurator) []config_center.Configurator { + if len(urls) == 0 { + return nil + } + var configurators []config_center.Configurator + for _, url := range urls { + if url.Protocol == constant.EMPTY_PROTOCOL { + configurators = []config_center.Configurator{} + break + } + //TODO:anyhost_key judage + configurators = append(configurators, f(url)) + } + return configurators +} diff --git a/registry/consul/registry.go b/registry/consul/registry.go index e01879ec2d..73bf3975bc 100644 --- a/registry/consul/registry.go +++ b/registry/consul/registry.go @@ -19,19 +19,26 @@ package consul import ( "strconv" + "time" ) import ( consul "github.com/hashicorp/consul/api" + perrors "github.com/pkg/errors" ) import ( "github.com/apache/dubbo-go/common" "github.com/apache/dubbo-go/common/constant" "github.com/apache/dubbo-go/common/extension" + "github.com/apache/dubbo-go/common/logger" "github.com/apache/dubbo-go/registry" ) +const ( + RegistryConnDelay = 3 +) + func init() { extension.SetRegistry("consul", newConsulRegistry) } @@ -104,20 +111,42 @@ func (r *consulRegistry) unregister(url common.URL) error { return r.client.Agent().ServiceDeregister(buildId(url)) } -func (r *consulRegistry) Subscribe(url common.URL) (registry.Listener, error) { - var ( - listener registry.Listener - err error - ) - +func (r *consulRegistry) Subscribe(url *common.URL, notifyListener registry.NotifyListener) { role, _ := strconv.Atoi(r.URL.GetParam(constant.ROLE_KEY, "")) if role == common.CONSUMER { - listener, err = r.getListener(url) + r.subscribe(url, notifyListener) + } +} + +func (r *consulRegistry) subscribe(url *common.URL, notifyListener registry.NotifyListener) { + for { + if !r.IsAvailable() { + logger.Warnf("event listener game over.") + return + } + + listener, err := r.getListener(*url) if err != nil { - return nil, err + if !r.IsAvailable() { + logger.Warnf("event listener game over.") + return + } + logger.Warnf("getListener() = err:%v", perrors.WithStack(err)) + time.Sleep(time.Duration(RegistryConnDelay) * time.Second) + continue + } + + for { + if serviceEvent, err := listener.Next(); err != nil { + logger.Warnf("Selector.watch() = error{%v}", perrors.WithStack(err)) + listener.Close() + return + } else { + logger.Infof("update begin, service event: %v", serviceEvent.String()) + notifyListener.Notify(serviceEvent) + } } } - return listener, nil } func (r *consulRegistry) getListener(url common.URL) (registry.Listener, error) { diff --git a/registry/consul/registry_test.go b/registry/consul/registry_test.go index 8ec80c83d1..bb6842cd8f 100644 --- a/registry/consul/registry_test.go +++ b/registry/consul/registry_test.go @@ -32,7 +32,7 @@ func (suite *consulRegistryTestSuite) testNewConsumerRegistry() { consumerRegistryUrl := newConsumerRegistryUrl(registryHost, registryPort) consumerRegistry, err := newConsulRegistry(consumerRegistryUrl) assert.NoError(suite.t, err) - suite.consumerRegistry = consumerRegistry + suite.consumerRegistry = consumerRegistry.(*consulRegistry) } func (suite *consulRegistryTestSuite) testRegister() { @@ -51,7 +51,7 @@ func (suite *consulRegistryTestSuite) testUnregister() { func (suite *consulRegistryTestSuite) testSubscribe() { consumerUrl := newConsumerUrl(consumerHost, consumerPort, service, protocol) suite.consumerUrl = consumerUrl - listener, err := suite.consumerRegistry.Subscribe(consumerUrl) + listener, err := suite.consumerRegistry.getListener(consumerUrl) assert.NoError(suite.t, err) suite.listener = listener } diff --git a/registry/consul/utils_test.go b/registry/consul/utils_test.go index 36b2b354ed..d66600b773 100644 --- a/registry/consul/utils_test.go +++ b/registry/consul/utils_test.go @@ -165,7 +165,7 @@ func (server *testServer) close() { type consulRegistryTestSuite struct { t *testing.T providerRegistry registry.Registry - consumerRegistry registry.Registry + consumerRegistry *consulRegistry listener registry.Listener providerUrl common.URL consumerUrl common.URL diff --git a/registry/directory/directory.go b/registry/directory/directory.go index 0ef5023c61..b6794e2ebf 100644 --- a/registry/directory/directory.go +++ b/registry/directory/directory.go @@ -32,14 +32,12 @@ import ( "github.com/apache/dubbo-go/common/constant" "github.com/apache/dubbo-go/common/extension" "github.com/apache/dubbo-go/common/logger" + "github.com/apache/dubbo-go/config" + "github.com/apache/dubbo-go/config_center" + _ "github.com/apache/dubbo-go/config_center/configurator" "github.com/apache/dubbo-go/protocol" "github.com/apache/dubbo-go/protocol/protocolwrapper" "github.com/apache/dubbo-go/registry" - "github.com/apache/dubbo-go/remoting" -) - -const ( - RegistryConnDelay = 3 ) type Options struct { @@ -50,11 +48,15 @@ type Option func(*Options) type registryDirectory struct { directory.BaseDirectory - cacheInvokers []protocol.Invoker - listenerLock sync.Mutex - serviceType string - registry registry.Registry - cacheInvokersMap *sync.Map //use sync.map + cacheInvokers []protocol.Invoker + listenerLock sync.Mutex + serviceType string + registry registry.Registry + cacheInvokersMap *sync.Map //use sync.map + cacheOriginUrl *common.URL + configurators []config_center.Configurator + consumerConfigurationListener *consumerConfigurationListener + referenceConfigurationListener *referenceConfigurationListener Options } @@ -69,49 +71,27 @@ func NewRegistryDirectory(url *common.URL, registry registry.Registry, opts ...O if url.SubURL == nil { return nil, perrors.Errorf("url is invalid, suburl can not be nil") } - return ®istryDirectory{ + dir := ®istryDirectory{ BaseDirectory: directory.NewBaseDirectory(url), cacheInvokers: []protocol.Invoker{}, cacheInvokersMap: &sync.Map{}, serviceType: url.SubURL.Service(), registry: registry, Options: options, - }, nil + } + dir.consumerConfigurationListener = newConsumerConfigurationListener(dir) + return dir, nil } //subscribe from registry -func (dir *registryDirectory) Subscribe(url common.URL) { - for { - if !dir.registry.IsAvailable() { - logger.Warnf("event listener game over.") - return - } - - listener, err := dir.registry.Subscribe(url) - if err != nil { - if !dir.registry.IsAvailable() { - logger.Warnf("event listener game over.") - return - } - logger.Warnf("getListener() = err:%v", perrors.WithStack(err)) - time.Sleep(time.Duration(RegistryConnDelay) * time.Second) - continue - } - - for { - if serviceEvent, err := listener.Next(); err != nil { - logger.Warnf("Selector.watch() = error{%v}", perrors.WithStack(err)) - listener.Close() - time.Sleep(time.Duration(RegistryConnDelay) * time.Second) - return - } else { - logger.Infof("update begin, service event: %v", serviceEvent.String()) - go dir.update(serviceEvent) - } - - } +func (dir *registryDirectory) Subscribe(url *common.URL) { + dir.consumerConfigurationListener.addNotifyListener(dir) + dir.referenceConfigurationListener = newReferenceConfigurationListener(dir, url) + dir.registry.Subscribe(url, dir) +} - } +func (dir *registryDirectory) Notify(event *registry.ServiceEvent) { + go dir.update(event) } //subscribe service from registry, and update the cacheServices @@ -125,21 +105,35 @@ func (dir *registryDirectory) update(res *registry.ServiceEvent) { } func (dir *registryDirectory) refreshInvokers(res *registry.ServiceEvent) { - - switch res.Action { - case remoting.EventTypeAdd: - //dir.cacheService.EventTypeAdd(res.Path, dir.serviceTTL) - dir.cacheInvoker(res.Service) - case remoting.EventTypeDel: - //dir.cacheService.EventTypeDel(res.Path, dir.serviceTTL) - dir.uncacheInvoker(res.Service) - logger.Infof("selector delete service url{%s}", res.Service) - default: - return + var url *common.URL + //judge is override or others + if res != nil { + url = &res.Service + //1.for override url in 2.6.x + if url.Protocol == constant.OVERRIDE_PROTOCOL || + url.GetParam(constant.CATEGORY_KEY, constant.DEFAULT_CATEGORY) == constant.CONFIGURATORS_CATEGORY { + dir.configurators = append(dir.configurators, extension.GetDefaultConfigurator(url)) + url = nil + } else if url.Protocol == constant.ROUTER_PROTOCOL || //2.for router + url.GetParam(constant.CATEGORY_KEY, constant.DEFAULT_CATEGORY) == constant.ROUTER_CATEGORY { + url = nil + //TODO: router + } } - + // + //switch res.Action { + //case remoting.EventTypeAdd: + // //dir.cacheService.EventTypeAdd(res.Path, dir.serviceTTL) + // dir.cacheInvoker(&res.Service) + //case remoting.EventTypeDel: + // //dir.cacheService.EventTypeDel(res.Path, dir.serviceTTL) + // dir.uncacheInvoker(&res.Service) + // logger.Infof("selector delete service url{%s}", res.Service) + //default: + // return + //} + dir.cacheInvoker(url) newInvokers := dir.toGroupInvokers() - dir.listenerLock.Lock() defer dir.listenerLock.Unlock() dir.cacheInvokers = newInvokers @@ -180,22 +174,40 @@ func (dir *registryDirectory) toGroupInvokers() []protocol.Invoker { return groupInvokersList } -func (dir *registryDirectory) uncacheInvoker(url common.URL) { +func (dir *registryDirectory) uncacheInvoker(url *common.URL) { logger.Debugf("service will be deleted in cache invokers: invokers key is %s!", url.Key()) dir.cacheInvokersMap.Delete(url.Key()) } -func (dir *registryDirectory) cacheInvoker(url common.URL) { - referenceUrl := dir.GetUrl().SubURL +func (dir *registryDirectory) cacheInvoker(url *common.URL) { + dir.overrideUrl(dir.GetDirectoryUrl()) + referenceUrl := dir.GetDirectoryUrl().SubURL + + if url == nil && dir.cacheOriginUrl != nil { + url = dir.cacheOriginUrl + } else { + dir.cacheOriginUrl = url + } + if url == nil { + logger.Error("URL is nil ,pls check if service url is subscribe successfully!") + return + } //check the url's protocol is equal to the protocol which is configured in reference config or referenceUrl is not care about protocol if url.Protocol == referenceUrl.Protocol || referenceUrl.Protocol == "" { - url = common.MergeUrl(url, referenceUrl) - - if _, ok := dir.cacheInvokersMap.Load(url.Key()); !ok { - logger.Debugf("service will be added in cache invokers: invokers key is %s!", url.Key()) - newInvoker := extension.GetProtocol(protocolwrapper.FILTER).Refer(url) + newUrl := common.MergeUrl(url, referenceUrl) + dir.overrideUrl(newUrl) + if cacheInvoker, ok := dir.cacheInvokersMap.Load(newUrl.Key()); !ok { + logger.Infof("service will be added in cache invokers: invokers url is %s!", newUrl) + newInvoker := extension.GetProtocol(protocolwrapper.FILTER).Refer(*newUrl) + if newInvoker != nil { + dir.cacheInvokersMap.Store(newUrl.Key(), newInvoker) + } + } else { + logger.Infof("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) if newInvoker != nil { - dir.cacheInvokersMap.Store(url.Key(), newInvoker) + dir.cacheInvokersMap.Store(newUrl.Key(), newInvoker) + cacheInvoker.(protocol.Invoker).Destroy() } } } @@ -229,3 +241,61 @@ func (dir *registryDirectory) Destroy() { dir.cacheInvokers = []protocol.Invoker{} }) } + +func (dir *registryDirectory) overrideUrl(targetUrl *common.URL) { + doOverrideUrl(dir.configurators, targetUrl) + doOverrideUrl(dir.consumerConfigurationListener.Configurators(), targetUrl) + doOverrideUrl(dir.referenceConfigurationListener.Configurators(), targetUrl) +} + +func doOverrideUrl(configurators []config_center.Configurator, targetUrl *common.URL) { + for _, v := range configurators { + v.Configure(targetUrl) + } +} + +type referenceConfigurationListener struct { + registry.BaseConfigurationListener + directory *registryDirectory + url *common.URL +} + +func newReferenceConfigurationListener(dir *registryDirectory, url *common.URL) *referenceConfigurationListener { + listener := &referenceConfigurationListener{directory: dir, url: url} + listener.InitWith( + url.EncodedServiceKey()+constant.CONFIGURATORS_SUFFIX, + listener, + extension.GetDefaultConfiguratorFunc(), + ) + return listener +} + +func (l *referenceConfigurationListener) Process(event *config_center.ConfigChangeEvent) { + l.BaseConfigurationListener.Process(event) + l.directory.refreshInvokers(nil) +} + +type consumerConfigurationListener struct { + registry.BaseConfigurationListener + listeners []registry.NotifyListener + directory *registryDirectory +} + +func newConsumerConfigurationListener(dir *registryDirectory) *consumerConfigurationListener { + listener := &consumerConfigurationListener{directory: dir} + listener.InitWith( + config.GetConsumerConfig().ApplicationConfig.Name+constant.CONFIGURATORS_SUFFIX, + listener, + extension.GetDefaultConfiguratorFunc(), + ) + return listener +} + +func (l *consumerConfigurationListener) addNotifyListener(listener registry.NotifyListener) { + l.listeners = append(l.listeners, listener) +} + +func (l *consumerConfigurationListener) Process(event *config_center.ConfigChangeEvent) { + l.BaseConfigurationListener.Process(event) + l.directory.refreshInvokers(nil) +} diff --git a/registry/directory/directory_test.go b/registry/directory/directory_test.go index 9b48da80df..b3c1d35aaa 100644 --- a/registry/directory/directory_test.go +++ b/registry/directory/directory_test.go @@ -34,12 +34,16 @@ import ( "github.com/apache/dubbo-go/common" "github.com/apache/dubbo-go/common/constant" "github.com/apache/dubbo-go/common/extension" + "github.com/apache/dubbo-go/config" "github.com/apache/dubbo-go/protocol/invocation" "github.com/apache/dubbo-go/protocol/protocolwrapper" "github.com/apache/dubbo-go/registry" "github.com/apache/dubbo-go/remoting" ) +func init() { + config.SetConsumerConfig(config.ConsumerConfig{ApplicationConfig: &config.ApplicationConfig{Name: "test-application"}}) +} func TestSubscribe(t *testing.T) { registryDirectory, _ := normalRegistryDir() @@ -47,14 +51,15 @@ func TestSubscribe(t *testing.T) { assert.Len(t, registryDirectory.cacheInvokers, 3) } -func TestSubscribe_Delete(t *testing.T) { - registryDirectory, mockRegistry := normalRegistryDir() - time.Sleep(1e9) - assert.Len(t, registryDirectory.cacheInvokers, 3) - mockRegistry.MockEvent(®istry.ServiceEvent{Action: remoting.EventTypeDel, Service: *common.NewURLWithOptions(common.WithPath("TEST0"), common.WithProtocol("dubbo"))}) - time.Sleep(1e9) - assert.Len(t, registryDirectory.cacheInvokers, 2) -} +////Deprecated! not support delete +//func TestSubscribe_Delete(t *testing.T) { +// registryDirectory, mockRegistry := normalRegistryDir() +// time.Sleep(1e9) +// assert.Len(t, registryDirectory.cacheInvokers, 3) +// mockRegistry.MockEvent(®istry.ServiceEvent{Action: remoting.EventTypeDel, Service: *common.NewURLWithOptions(common.WithPath("TEST0"), common.WithProtocol("dubbo"))}) +// time.Sleep(1e9) +// assert.Len(t, registryDirectory.cacheInvokers, 2) +//} func TestSubscribe_InvalidUrl(t *testing.T) { url, _ := common.NewURL(context.TODO(), "mock://127.0.0.1:1111") @@ -74,7 +79,7 @@ func TestSubscribe_Group(t *testing.T) { mockRegistry, _ := registry.NewMockRegistry(&common.URL{}) registryDirectory, _ := NewRegistryDirectory(®url, mockRegistry) - go registryDirectory.Subscribe(*common.NewURLWithOptions(common.WithPath("testservice"))) + go registryDirectory.Subscribe(common.NewURLWithOptions(common.WithPath("testservice"))) //for group1 urlmap := url.Values{} @@ -116,20 +121,83 @@ func Test_List(t *testing.T) { assert.Len(t, registryDirectory.List(&invocation.RPCInvocation{}), 3) assert.Equal(t, true, registryDirectory.IsAvailable()) +} +func Test_MergeProviderUrl(t *testing.T) { + registryDirectory, mockRegistry := normalRegistryDir(true) + providerUrl, _ := common.NewURL(context.TODO(), "dubbo://0.0.0.0:20000/org.apache.dubbo-go.mockService", + common.WithParamsValue(constant.CLUSTER_KEY, "mock1"), + common.WithParamsValue(constant.GROUP_KEY, "group"), + common.WithParamsValue(constant.VERSION_KEY, "1.0.0")) + mockRegistry.MockEvent(®istry.ServiceEvent{Action: remoting.EventTypeAdd, Service: providerUrl}) + time.Sleep(1e9) + assert.Len(t, registryDirectory.cacheInvokers, 1) + if len(registryDirectory.cacheInvokers) > 0 { + assert.Equal(t, "mock", registryDirectory.cacheInvokers[0].GetUrl().GetParam(constant.CLUSTER_KEY, "")) + } + +} + +func Test_MergeOverrideUrl(t *testing.T) { + registryDirectory, mockRegistry := normalRegistryDir(true) + providerUrl, _ := common.NewURL(context.TODO(), "dubbo://0.0.0.0:20000/org.apache.dubbo-go.mockService", + common.WithParamsValue(constant.CLUSTER_KEY, "mock"), + common.WithParamsValue(constant.GROUP_KEY, "group"), + common.WithParamsValue(constant.VERSION_KEY, "1.0.0")) + mockRegistry.MockEvent(®istry.ServiceEvent{Action: remoting.EventTypeAdd, Service: providerUrl}) +Loop1: + for { + if len(registryDirectory.cacheInvokers) > 0 { + overrideUrl, _ := common.NewURL(context.TODO(), "override://0.0.0.0:20000/org.apache.dubbo-go.mockService", + common.WithParamsValue(constant.CLUSTER_KEY, "mock1"), + common.WithParamsValue(constant.GROUP_KEY, "group"), + common.WithParamsValue(constant.VERSION_KEY, "1.0.0")) + mockRegistry.MockEvent(®istry.ServiceEvent{Action: remoting.EventTypeAdd, Service: overrideUrl}) + Loop2: + for { + if len(registryDirectory.cacheInvokers) > 0 { + if "mock1" == registryDirectory.cacheInvokers[0].GetUrl().GetParam(constant.CLUSTER_KEY, "") { + assert.Len(t, registryDirectory.cacheInvokers, 1) + assert.True(t, true) + break Loop2 + } else { + time.Sleep(500 * time.Millisecond) + } + } + } + break Loop1 + } + } + } -func normalRegistryDir() (*registryDirectory, *registry.MockRegistry) { +func normalRegistryDir(noMockEvent ...bool) (*registryDirectory, *registry.MockRegistry) { extension.SetProtocol(protocolwrapper.FILTER, protocolwrapper.NewMockProtocolFilter) url, _ := common.NewURL(context.TODO(), "mock://127.0.0.1:1111") - suburl, _ := common.NewURL(context.TODO(), "dubbo://127.0.0.1:20000") + suburl, _ := common.NewURL( + context.TODO(), + "dubbo://127.0.0.1:20000/org.apache.dubbo-go.mockService", + common.WithParamsValue(constant.CLUSTER_KEY, "mock"), + common.WithParamsValue(constant.GROUP_KEY, "group"), + common.WithParamsValue(constant.VERSION_KEY, "1.0.0"), + ) url.SubURL = &suburl mockRegistry, _ := registry.NewMockRegistry(&common.URL{}) registryDirectory, _ := NewRegistryDirectory(&url, mockRegistry) - go registryDirectory.Subscribe(*common.NewURLWithOptions(common.WithPath("testservice"))) - 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"))}) + go 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( + common.WithPath("TEST"+strconv.FormatInt(int64(i), 10)), + common.WithProtocol("dubbo"), + ), + }, + ) + } } return registryDirectory, mockRegistry.(*registry.MockRegistry) } diff --git a/registry/etcdv3/listener.go b/registry/etcdv3/listener.go index a8f2facc1a..e0dc099085 100644 --- a/registry/etcdv3/listener.go +++ b/registry/etcdv3/listener.go @@ -12,16 +12,17 @@ import ( import ( "github.com/apache/dubbo-go/common" "github.com/apache/dubbo-go/common/logger" + "github.com/apache/dubbo-go/config_center" "github.com/apache/dubbo-go/registry" "github.com/apache/dubbo-go/remoting" ) type dataListener struct { interestedURL []*common.URL - listener remoting.ConfigurationListener + listener config_center.ConfigurationListener } -func NewRegistryDataListener(listener remoting.ConfigurationListener) *dataListener { +func NewRegistryDataListener(listener config_center.ConfigurationListener) *dataListener { return &dataListener{listener: listener, interestedURL: []*common.URL{}} } @@ -40,7 +41,13 @@ func (l *dataListener) DataChange(eventType remoting.Event) bool { for _, v := range l.interestedURL { if serviceURL.URLEqual(*v) { - l.listener.Process(&remoting.ConfigChangeEvent{Key: eventType.Path, Value: serviceURL, ConfigType: eventType.Action}) + l.listener.Process( + &config_center.ConfigChangeEvent{ + Key: eventType.Path, + Value: serviceURL, + ConfigType: eventType.Action, + }, + ) return true } } @@ -50,15 +57,15 @@ func (l *dataListener) DataChange(eventType remoting.Event) bool { type configurationListener struct { registry *etcdV3Registry - events chan *remoting.ConfigChangeEvent + events chan *config_center.ConfigChangeEvent } func NewConfigurationListener(reg *etcdV3Registry) *configurationListener { // add a new waiter reg.wg.Add(1) - return &configurationListener{registry: reg, events: make(chan *remoting.ConfigChangeEvent, 32)} + return &configurationListener{registry: reg, events: make(chan *config_center.ConfigChangeEvent, 32)} } -func (l *configurationListener) Process(configType *remoting.ConfigChangeEvent) { +func (l *configurationListener) Process(configType *config_center.ConfigChangeEvent) { l.events <- configType } diff --git a/registry/etcdv3/listener_test.go b/registry/etcdv3/listener_test.go index 0ac8fc475e..00024d2894 100644 --- a/registry/etcdv3/listener_test.go +++ b/registry/etcdv3/listener_test.go @@ -2,6 +2,7 @@ package etcdv3 import ( "context" + "github.com/apache/dubbo-go/config_center" "testing" "time" ) @@ -68,4 +69,4 @@ func TestRegistrySuite(t *testing.T) { type MockDataListener struct{} -func (*MockDataListener) Process(configType *remoting.ConfigChangeEvent) {} +func (*MockDataListener) Process(configType *config_center.ConfigChangeEvent) {} diff --git a/registry/etcdv3/registry.go b/registry/etcdv3/registry.go index 96d237f18b..bf097f0b59 100644 --- a/registry/etcdv3/registry.go +++ b/registry/etcdv3/registry.go @@ -30,7 +30,10 @@ var ( localIP = "" ) -const Name = "etcdv3" +const ( + Name = "etcdv3" + RegistryConnDelay = 3 +) func init() { processID = fmt.Sprintf("%d", os.Getpid()) @@ -293,7 +296,7 @@ func (r *etcdV3Registry) registerProvider(svc common.URL) error { return nil } -func (r *etcdV3Registry) Subscribe(svc common.URL) (registry.Listener, error) { +func (r *etcdV3Registry) subscribe(svc *common.URL) (registry.Listener, error) { var ( configListener *configurationListener @@ -319,8 +322,44 @@ func (r *etcdV3Registry) Subscribe(svc common.URL) (registry.Listener, error) { } //register the svc to dataListener - r.dataListener.AddInterestedURL(&svc) - go r.listener.ListenServiceEvent(fmt.Sprintf("/dubbo/%s/providers", svc.Service()), r.dataListener) + r.dataListener.AddInterestedURL(svc) + for _, v := range strings.Split(svc.GetParam(constant.CATEGORY_KEY, constant.DEFAULT_CATEGORY), ",") { + go r.listener.ListenServiceEvent(fmt.Sprintf("/dubbo/%s/"+v, svc.Service()), r.dataListener) + } return configListener, nil } + +//subscribe from registry +func (r *etcdV3Registry) Subscribe(url *common.URL, notifyListener registry.NotifyListener) { + for { + if !r.IsAvailable() { + logger.Warnf("event listener game over.") + return + } + + listener, err := r.subscribe(url) + if err != nil { + if !r.IsAvailable() { + logger.Warnf("event listener game over.") + return + } + logger.Warnf("getListener() = err:%v", perrors.WithStack(err)) + time.Sleep(time.Duration(RegistryConnDelay) * time.Second) + continue + } + + for { + if serviceEvent, err := listener.Next(); err != nil { + logger.Warnf("Selector.watch() = error{%v}", perrors.WithStack(err)) + listener.Close() + return + } else { + logger.Infof("update begin, service event: %v", serviceEvent.String()) + notifyListener.Notify(serviceEvent) + } + + } + + } +} diff --git a/registry/etcdv3/registry_test.go b/registry/etcdv3/registry_test.go index 6d8fc24056..6da9ad9d7d 100644 --- a/registry/etcdv3/registry_test.go +++ b/registry/etcdv3/registry_test.go @@ -67,7 +67,7 @@ func (suite *RegistryTestSuite) TestSubscribe() { reg2 := initRegistry(t) reg2.Register(url) - listener, err := reg2.Subscribe(url) + listener, err := reg2.subscribe(&url) if err != nil { t.Fatal(err) } @@ -85,7 +85,7 @@ func (suite *RegistryTestSuite) TestConsumerDestory() { url, _ := common.NewURL(context.Background(), "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.Subscribe(url) + _, err := reg.subscribe(&url) if err != nil { t.Fatal(err) } diff --git a/registry/mock_registry.go b/registry/mock_registry.go index 1fc700edb7..512c452e39 100644 --- a/registry/mock_registry.go +++ b/registry/mock_registry.go @@ -17,12 +17,17 @@ package registry +import ( + "time" +) + import ( "go.uber.org/atomic" ) import ( "github.com/apache/dubbo-go/common" + "github.com/apache/dubbo-go/common/logger" ) type MockRegistry struct { @@ -53,9 +58,43 @@ func (r *MockRegistry) GetUrl() common.URL { return common.URL{} } -func (r *MockRegistry) Subscribe(common.URL) (Listener, error) { +func (r *MockRegistry) subscribe(*common.URL) (Listener, error) { return r.listener, nil } +func (r *MockRegistry) Subscribe(url *common.URL, notifyListener NotifyListener) { + go func() { + for { + if !r.IsAvailable() { + logger.Warnf("event listener game over.") + time.Sleep(time.Duration(3) * time.Second) + return + } + + listener, err := r.subscribe(url) + if err != nil { + if !r.IsAvailable() { + logger.Warnf("event listener game over.") + return + } + time.Sleep(time.Duration(3) * time.Second) + continue + } + + for { + if serviceEvent, err := listener.Next(); err != nil { + listener.Close() + time.Sleep(time.Duration(3) * time.Second) + return + } else { + logger.Infof("update begin, service event: %v", serviceEvent.String()) + notifyListener.Notify(serviceEvent) + } + + } + + } + }() +} type listener struct { count int64 diff --git a/registry/nacos/listener.go b/registry/nacos/listener.go index 0cb48e0764..1f264ec9e4 100644 --- a/registry/nacos/listener.go +++ b/registry/nacos/listener.go @@ -19,6 +19,7 @@ import ( "github.com/apache/dubbo-go/common" "github.com/apache/dubbo-go/common/constant" "github.com/apache/dubbo-go/common/logger" + "github.com/apache/dubbo-go/config_center" "github.com/apache/dubbo-go/registry" "github.com/apache/dubbo-go/remoting" ) @@ -26,7 +27,7 @@ import ( type nacosListener struct { namingClient naming_client.INamingClient listenUrl common.URL - events chan *remoting.ConfigChangeEvent + events chan *config_center.ConfigChangeEvent instanceMap map[string]model.Instance cacheLock sync.Mutex done chan struct{} @@ -36,7 +37,7 @@ type nacosListener struct { func NewNacosListener(url common.URL, namingClient naming_client.INamingClient) (*nacosListener, error) { listener := &nacosListener{ namingClient: namingClient, - listenUrl: url, events: make(chan *remoting.ConfigChangeEvent, 32), + listenUrl: url, events: make(chan *config_center.ConfigChangeEvent, 32), instanceMap: map[string]model.Instance{}, done: make(chan struct{}), } @@ -134,20 +135,20 @@ func (nl *nacosListener) Callback(services []model.SubscribeService, err error) for i := range addInstances { newUrl := generateUrl(addInstances[i]) if newUrl != nil { - nl.process(&remoting.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(&remoting.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(&remoting.ConfigChangeEvent{Value: *newUrl, ConfigType: remoting.EventTypeUpdate}) + nl.process(&config_center.ConfigChangeEvent{Value: *newUrl, ConfigType: remoting.EventTypeUpdate}) } } } @@ -175,7 +176,7 @@ func (nl *nacosListener) stopListen() error { return nl.namingClient.Unsubscribe(nl.subscribeParam) } -func (nl *nacosListener) process(configType *remoting.ConfigChangeEvent) { +func (nl *nacosListener) process(configType *config_center.ConfigChangeEvent) { nl.events <- configType } diff --git a/registry/nacos/registry.go b/registry/nacos/registry.go index d6235cb230..229c6f8f0c 100644 --- a/registry/nacos/registry.go +++ b/registry/nacos/registry.go @@ -7,6 +7,7 @@ import ( "strings" "time" ) + import ( "github.com/nacos-group/nacos-sdk-go/clients" "github.com/nacos-group/nacos-sdk-go/clients/naming_client" @@ -19,6 +20,7 @@ import ( "github.com/apache/dubbo-go/common" "github.com/apache/dubbo-go/common/constant" "github.com/apache/dubbo-go/common/extension" + "github.com/apache/dubbo-go/common/logger" "github.com/apache/dubbo-go/common/utils" "github.com/apache/dubbo-go/registry" ) @@ -27,6 +29,10 @@ var ( localIP = "" ) +const ( + RegistryConnDelay = 3 +) + func init() { localIP, _ = utils.GetLocalIP() extension.SetRegistry(constant.NACOS_KEY, newNacosRegistry) @@ -162,8 +168,42 @@ func (nr *nacosRegistry) Register(url common.URL) error { return nil } -func (nr *nacosRegistry) Subscribe(conf common.URL) (registry.Listener, error) { - return NewNacosListener(conf, nr.namingClient) +func (nr *nacosRegistry) subscribe(conf *common.URL) (registry.Listener, error) { + return NewNacosListener(*conf, nr.namingClient) +} + +//subscribe from registry +func (nr *nacosRegistry) Subscribe(url *common.URL, notifyListener registry.NotifyListener) { + for { + if !nr.IsAvailable() { + logger.Warnf("event listener game over.") + return + } + + listener, err := nr.subscribe(url) + if err != nil { + if !nr.IsAvailable() { + logger.Warnf("event listener game over.") + return + } + logger.Warnf("getListener() = err:%v", perrors.WithStack(err)) + time.Sleep(time.Duration(RegistryConnDelay) * time.Second) + continue + } + + for { + if serviceEvent, err := listener.Next(); err != nil { + logger.Warnf("Selector.watch() = error{%v}", perrors.WithStack(err)) + listener.Close() + return + } else { + logger.Infof("update begin, service event: %v", serviceEvent.String()) + notifyListener.Notify(serviceEvent) + } + + } + + } } func (nr *nacosRegistry) GetUrl() common.URL { diff --git a/registry/nacos/registry_test.go b/registry/nacos/registry_test.go index bb43a5feed..023ff78809 100644 --- a/registry/nacos/registry_test.go +++ b/registry/nacos/registry_test.go @@ -68,7 +68,7 @@ func TestNacosRegistry_Subscribe(t *testing.T) { regurl.SetParam(constant.ROLE_KEY, strconv.Itoa(common.CONSUMER)) reg2, _ := newNacosRegistry(®url) - listener, err := reg2.Subscribe(url) + listener, err := reg2.(*nacosRegistry).subscribe(&url) 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) { regurl.SetParam(constant.ROLE_KEY, strconv.Itoa(common.CONSUMER)) reg2, _ := newNacosRegistry(®url) - listener, err := reg2.Subscribe(url1) + listener, err := reg2.(*nacosRegistry).subscribe(&url1) assert.Nil(t, err) if err != nil { t.Errorf("subscribe error:%s \n", err.Error()) @@ -162,7 +162,7 @@ func TestNacosListener_Close(t *testing.T) { urlMap.Set(constant.NACOS_PATH_KEY, "") url1, _ := common.NewURL(context.TODO(), "dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider2", common.WithParams(urlMap), common.WithMethods([]string{"GetUser", "AddUser"})) reg, _ := newNacosRegistry(®url) - listener, err := reg.Subscribe(url1) + 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 d01c92ec5c..d1e02b11b2 100644 --- a/registry/protocol/protocol.go +++ b/registry/protocol/protocol.go @@ -18,19 +18,28 @@ package protocol import ( + "strings" "sync" ) +import ( + "github.com/dubbogo/gost/container" +) + import ( "github.com/apache/dubbo-go/common" "github.com/apache/dubbo-go/common/constant" "github.com/apache/dubbo-go/common/extension" "github.com/apache/dubbo-go/common/logger" "github.com/apache/dubbo-go/common/proxy/proxy_factory" + "github.com/apache/dubbo-go/config" + "github.com/apache/dubbo-go/config_center" + _ "github.com/apache/dubbo-go/config_center/configurator" "github.com/apache/dubbo-go/protocol" "github.com/apache/dubbo-go/protocol/protocolwrapper" "github.com/apache/dubbo-go/registry" directory2 "github.com/apache/dubbo-go/registry/directory" + "github.com/apache/dubbo-go/remoting" ) var ( @@ -40,20 +49,31 @@ var ( type registryProtocol struct { invokers []protocol.Invoker // Registry Map - registries sync.Map + registries *sync.Map //To solve the problem of RMI repeated exposure port conflicts, the services that have been exposed are no longer exposed. //providerurl <--> exporter - bounds sync.Map + bounds *sync.Map + overrideListeners *sync.Map + serviceConfigurationListeners *sync.Map + providerConfigurationListener *providerConfigurationListener + once sync.Once } func init() { extension.SetProtocol("registry", GetProtocol) } +func getCacheKey(url *common.URL) string { + newUrl := url.Clone() + delKeys := container.NewSet("dynamic", "enabled") + newUrl.RemoveParams(delKeys) + return newUrl.String() +} + func newRegistryProtocol() *registryProtocol { return ®istryProtocol{ - registries: sync.Map{}, - bounds: sync.Map{}, + registries: &sync.Map{}, + bounds: &sync.Map{}, } } func getRegistry(regUrl *common.URL) registry.Registry { @@ -64,6 +84,11 @@ func getRegistry(regUrl *common.URL) registry.Registry { } return reg } +func (proto *registryProtocol) initConfigurationListeners() { + proto.overrideListeners = &sync.Map{} + proto.serviceConfigurationListeners = &sync.Map{} + proto.providerConfigurationListener = newProviderConfigurationListener(proto.overrideListeners) +} func (proto *registryProtocol) Refer(url common.URL) protocol.Invoker { var registryUrl = url @@ -72,6 +97,7 @@ func (proto *registryProtocol) Refer(url common.URL) protocol.Invoker { protocol := registryUrl.GetParam(constant.REGISTRY_KEY, "") registryUrl.Protocol = protocol } + var reg registry.Registry if regI, loaded := proto.registries.Load(registryUrl.Key()); !loaded { @@ -84,14 +110,16 @@ func (proto *registryProtocol) Refer(url common.URL) protocol.Invoker { //new registry directory for store service url from registry directory, err := directory2.NewRegistryDirectory(®istryUrl, 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()) + 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) if err != nil { - logger.Errorf("consumer service %v register registry %v error, error message is %s", serviceUrl.String(), registryUrl.String(), err.Error()) + logger.Errorf("consumer service %v register registry %v error, error message is %s", + serviceUrl.String(), registryUrl.String(), err.Error()) } - go directory.Subscribe(*serviceUrl) + go directory.Subscribe(serviceUrl) //new cluster invoker cluster := extension.GetCluster(serviceUrl.GetParam(constant.CLUSTER_KEY, constant.DEFAULT_CLUSTER)) @@ -102,25 +130,39 @@ func (proto *registryProtocol) Refer(url common.URL) protocol.Invoker { } func (proto *registryProtocol) Export(invoker protocol.Invoker) protocol.Exporter { - registryUrl := proto.getRegistryUrl(invoker) - providerUrl := proto.getProviderUrl(invoker) + + proto.once.Do(func() { + proto.initConfigurationListeners() + }) + registryUrl := getRegistryUrl(invoker) + providerUrl := getProviderUrl(invoker) + + overriderUrl := getSubscribedOverrideUrl(providerUrl) + // Deprecated! subscribe to override rules in 2.6.x or before. + overrideSubscribeListener := newOverrideSubscribeListener(overriderUrl, invoker, proto) + proto.overrideListeners.Store(overriderUrl, overrideSubscribeListener) + proto.providerConfigurationListener.OverrideUrl(providerUrl) + serviceConfigurationListener := newServiceConfigurationListener(overrideSubscribeListener, providerUrl) + proto.serviceConfigurationListeners.Store(providerUrl.ServiceKey(), serviceConfigurationListener) + serviceConfigurationListener.OverrideUrl(providerUrl) 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) } - err := reg.Register(providerUrl) + err := reg.Register(*providerUrl) if err != nil { - logger.Errorf("provider service %v register registry %v error, error message is %s", providerUrl.Key(), registryUrl.Key(), err.Error()) + logger.Errorf("provider service %v register registry %v error, error message is %s", + providerUrl.Key(), registryUrl.Key(), err.Error()) return nil } - key := providerUrl.Key() + key := getCacheKey(providerUrl) logger.Infof("The cached exporter keys is %v !", key) cachedExporter, loaded := proto.bounds.Load(key) if loaded { @@ -132,9 +174,125 @@ func (proto *registryProtocol) Export(invoker protocol.Invoker) protocol.Exporte logger.Infof("The exporter has not been cached, and will return a new exporter!") } + reg.Subscribe(overriderUrl, overrideSubscribeListener) return cachedExporter.(protocol.Exporter) } +func (proto *registryProtocol) reExport(invoker protocol.Invoker, newUrl *common.URL) { + url := getProviderUrl(invoker) + key := getCacheKey(url) + if oldExporter, loaded := proto.bounds.Load(key); loaded { + wrappedNewInvoker := newWrappedInvoker(invoker, newUrl) + oldExporter.(protocol.Exporter).Unexport() + proto.bounds.Delete(key) + proto.Export(wrappedNewInvoker) + //TODO: unregister & unsubscribe + + } +} + +type overrideSubscribeListener struct { + url *common.URL + originInvoker protocol.Invoker + protocol *registryProtocol + configurator config_center.Configurator +} + +func newOverrideSubscribeListener(overriderUrl *common.URL, invoker protocol.Invoker, proto *registryProtocol) *overrideSubscribeListener { + return &overrideSubscribeListener{url: overriderUrl, originInvoker: invoker, protocol: proto} +} +func (nl *overrideSubscribeListener) Notify(event *registry.ServiceEvent) { + if isMatched(&(event.Service), nl.url) && event.Action == remoting.EventTypeAdd { + nl.configurator = extension.GetDefaultConfigurator(&(event.Service)) + nl.doOverrideIfNecessary() + } +} +func (nl *overrideSubscribeListener) doOverrideIfNecessary() { + providerUrl := getProviderUrl(nl.originInvoker) + key := getCacheKey(providerUrl) + if exporter, ok := nl.protocol.bounds.Load(key); ok { + currentUrl := exporter.(protocol.Exporter).GetInvoker().GetUrl() + // Compatible with the 2.6.x + if nl.configurator != nil { + nl.configurator.Configure(providerUrl) + } + // provider application level management in 2.7.x + for _, v := range nl.protocol.providerConfigurationListener.Configurators() { + v.Configure(providerUrl) + } + // provider service level management in 2.7.x + if serviceListener, ok := nl.protocol.serviceConfigurationListeners.Load(providerUrl.ServiceKey()); ok { + listener := serviceListener.(*serviceConfigurationListener) + for _, v := range listener.Configurators() { + v.Configure(providerUrl) + } + } + + if currentUrl.String() != providerUrl.String() { + newRegUrl := nl.originInvoker.GetUrl() + setProviderUrl(&newRegUrl, providerUrl) + nl.protocol.reExport(nl.originInvoker, &newRegUrl) + } + } +} + +func isMatched(providerUrl *common.URL, consumerUrl *common.URL) bool { + // Compatible with the 2.6.x + if len(providerUrl.GetParam(constant.CATEGORY_KEY, "")) == 0 && + providerUrl.Protocol == constant.OVERRIDE_PROTOCOL { + providerUrl.AddParam(constant.CATEGORY_KEY, constant.CONFIGURATORS_CATEGORY) + } + consumerInterface := consumerUrl.GetParam(constant.INTERFACE_KEY, consumerUrl.Path) + providerInterface := providerUrl.GetParam(constant.INTERFACE_KEY, providerUrl.Path) + + if !(constant.ANY_VALUE == consumerInterface || + constant.ANY_VALUE == providerInterface || + providerInterface == consumerInterface) { + return false + } + + if !isMatchCategory(providerUrl.GetParam(constant.CATEGORY_KEY, constant.DEFAULT_CATEGORY), + consumerUrl.GetParam(constant.CATEGORY_KEY, constant.DEFAULT_CATEGORY)) { + return false + } + + if !providerUrl.GetParamBool(constant.ENABLED_KEY, true) && + consumerUrl.GetParam(constant.ENABLED_KEY, "") != constant.ANY_VALUE { + return false + } + consumerGroup := consumerUrl.GetParam(constant.GROUP_KEY, "") + consumerVersion := consumerUrl.GetParam(constant.VERSION_KEY, "") + consumerClassifier := consumerUrl.GetParam(constant.CLASSIFIER_KEY, "") + + providerGroup := providerUrl.GetParam(constant.GROUP_KEY, "") + providerVersion := providerUrl.GetParam(constant.VERSION_KEY, "") + providerClassifier := providerUrl.GetParam(constant.CLASSIFIER_KEY, "") + //todo: public static boolean isContains(String values, String value) { + // return isNotEmpty(values) && isContains(COMMA_SPLIT_PATTERN.split(values), value); + // } + return (consumerGroup == constant.ANY_VALUE || consumerGroup == providerGroup || + strings.Contains(consumerGroup, providerGroup)) && (consumerVersion == constant.ANY_VALUE || + consumerVersion == providerVersion) && (len(consumerClassifier) == 0 || + consumerClassifier == constant.ANY_VALUE || consumerClassifier == providerClassifier) +} +func isMatchCategory(category string, categories string) bool { + if len(categories) == 0 { + return category == constant.DEFAULT_CATEGORY + } else if strings.Contains(categories, constant.ANY_VALUE) { + return true + } else if strings.Contains(categories, constant.REMOVE_VALUE_PREFIX) { + return !strings.Contains(categories, constant.REMOVE_VALUE_PREFIX+category) + } else { + return strings.Contains(categories, category) + } +} +func getSubscribedOverrideUrl(providerUrl *common.URL) *common.URL { + newUrl := providerUrl.Clone() + newUrl.Protocol = constant.PROVIDER_PROTOCOL + newUrl.SetParam(constant.CATEGORY_KEY, constant.CONFIGURATORS_CATEGORY) + newUrl.SetParam(constant.CHECK_KEY, "false") + return newUrl +} func (proto *registryProtocol) Destroy() { for _, ivk := range proto.invokers { @@ -159,7 +317,7 @@ func (proto *registryProtocol) Destroy() { }) } -func (*registryProtocol) getRegistryUrl(invoker protocol.Invoker) common.URL { +func getRegistryUrl(invoker protocol.Invoker) *common.URL { //here add * for return a new url url := invoker.GetUrl() //if the protocol == registry ,set protocol the registry value in url.params @@ -167,12 +325,16 @@ func (*registryProtocol) getRegistryUrl(invoker protocol.Invoker) common.URL { protocol := url.GetParam(constant.REGISTRY_KEY, "") url.Protocol = protocol } - return url + return &url } -func (*registryProtocol) getProviderUrl(invoker protocol.Invoker) common.URL { +func getProviderUrl(invoker protocol.Invoker) *common.URL { url := invoker.GetUrl() - return *url.SubURL + //be careful params maps in url is map type + return url.SubURL.Clone() +} +func setProviderUrl(regURL *common.URL, providerURL *common.URL) { + regURL.SubURL = providerURL } func GetProtocol() protocol.Protocol { @@ -187,14 +349,60 @@ type wrappedInvoker struct { protocol.BaseInvoker } -func newWrappedInvoker(invoker protocol.Invoker, url common.URL) *wrappedInvoker { +func newWrappedInvoker(invoker protocol.Invoker, url *common.URL) *wrappedInvoker { return &wrappedInvoker{ invoker: invoker, - BaseInvoker: *protocol.NewBaseInvoker(url), + BaseInvoker: *protocol.NewBaseInvoker(*url), } } + func (ivk *wrappedInvoker) Invoke(invocation protocol.Invocation) protocol.Result { // get right url ivk.invoker.(*proxy_factory.ProxyInvoker).BaseInvoker = *protocol.NewBaseInvoker(ivk.GetUrl()) return ivk.invoker.Invoke(invocation) } + +type providerConfigurationListener struct { + registry.BaseConfigurationListener + overrideListeners *sync.Map +} + +func newProviderConfigurationListener(overrideListeners *sync.Map) *providerConfigurationListener { + listener := &providerConfigurationListener{} + listener.overrideListeners = overrideListeners + listener.InitWith( + config.GetProviderConfig().ApplicationConfig.Name+constant.CONFIGURATORS_SUFFIX, + listener, + extension.GetDefaultConfiguratorFunc(), + ) + return listener +} + +func (listener *providerConfigurationListener) Process(event *config_center.ConfigChangeEvent) { + listener.BaseConfigurationListener.Process(event) + listener.overrideListeners.Range(func(key, value interface{}) bool { + value.(*overrideSubscribeListener).doOverrideIfNecessary() + return true + }) +} + +type serviceConfigurationListener struct { + registry.BaseConfigurationListener + overrideListener *overrideSubscribeListener + providerUrl *common.URL +} + +func newServiceConfigurationListener(overrideListener *overrideSubscribeListener, providerUrl *common.URL) *serviceConfigurationListener { + listener := &serviceConfigurationListener{overrideListener: overrideListener, providerUrl: providerUrl} + listener.InitWith( + providerUrl.EncodedServiceKey()+constant.CONFIGURATORS_SUFFIX, + listener, + extension.GetDefaultConfiguratorFunc(), + ) + return listener +} + +func (listener *serviceConfigurationListener) Process(event *config_center.ConfigChangeEvent) { + listener.BaseConfigurationListener.Process(event) + listener.overrideListener.doOverrideIfNecessary() +} diff --git a/registry/protocol/protocol_test.go b/registry/protocol/protocol_test.go index 418f1f6779..0c19da59df 100644 --- a/registry/protocol/protocol_test.go +++ b/registry/protocol/protocol_test.go @@ -20,6 +20,7 @@ package protocol import ( "context" "testing" + "time" ) import ( @@ -29,13 +30,21 @@ import ( import ( cluster "github.com/apache/dubbo-go/cluster/cluster_impl" "github.com/apache/dubbo-go/common" + common_cfg "github.com/apache/dubbo-go/common/config" "github.com/apache/dubbo-go/common/constant" "github.com/apache/dubbo-go/common/extension" + "github.com/apache/dubbo-go/config" + "github.com/apache/dubbo-go/config_center" + "github.com/apache/dubbo-go/config_center/configurator" "github.com/apache/dubbo-go/protocol" "github.com/apache/dubbo-go/protocol/protocolwrapper" "github.com/apache/dubbo-go/registry" + "github.com/apache/dubbo-go/remoting" ) +func init() { + config.SetProviderConfig(config.ProviderConfig{ApplicationConfig: &config.ApplicationConfig{Name: "test-application"}}) +} func referNormal(t *testing.T, regProtocol *registryProtocol) { extension.SetProtocol("registry", GetProtocol) extension.SetRegistry("mock", registry.NewMockRegistry) @@ -43,7 +52,11 @@ func referNormal(t *testing.T, regProtocol *registryProtocol) { extension.SetCluster("mock", cluster.NewMockCluster) url, _ := common.NewURL(context.TODO(), "mock://127.0.0.1:1111") - suburl, _ := common.NewURL(context.TODO(), "dubbo://127.0.0.1:20000//", common.WithParamsValue(constant.CLUSTER_KEY, "mock")) + suburl, _ := common.NewURL( + context.TODO(), + "dubbo://127.0.0.1:20000//", + common.WithParamsValue(constant.CLUSTER_KEY, "mock"), + ) url.SubURL = &suburl @@ -53,6 +66,9 @@ func referNormal(t *testing.T, regProtocol *registryProtocol) { } func TestRefer(t *testing.T) { + config.SetConsumerConfig( + config.ConsumerConfig{ + ApplicationConfig: &config.ApplicationConfig{Name: "test-application"}}) regProtocol := newRegistryProtocol() referNormal(t, regProtocol) } @@ -61,7 +77,11 @@ func TestMultiRegRefer(t *testing.T) { regProtocol := newRegistryProtocol() referNormal(t, regProtocol) url2, _ := common.NewURL(context.TODO(), "mock://127.0.0.1:2222") - suburl2, _ := common.NewURL(context.TODO(), "dubbo://127.0.0.1:20000//", common.WithParamsValue(constant.CLUSTER_KEY, "mock")) + suburl2, _ := common.NewURL( + context.TODO(), + "dubbo://127.0.0.1:20000//", + common.WithParamsValue(constant.CLUSTER_KEY, "mock"), + ) url2.SubURL = &suburl2 @@ -79,7 +99,11 @@ func TestOneRegRefer(t *testing.T) { referNormal(t, regProtocol) url2, _ := common.NewURL(context.TODO(), "mock://127.0.0.1:1111") - suburl2, _ := common.NewURL(context.TODO(), "dubbo://127.0.0.1:20000//", common.WithParamsValue(constant.CLUSTER_KEY, "mock")) + suburl2, _ := common.NewURL( + context.TODO(), + "dubbo://127.0.0.1:20000//", + common.WithParamsValue(constant.CLUSTER_KEY, "mock"), + ) url2.SubURL = &suburl2 @@ -92,12 +116,18 @@ func TestOneRegRefer(t *testing.T) { assert.Equal(t, count, 1) } -func exporterNormal(t *testing.T, regProtocol *registryProtocol) { +func exporterNormal(t *testing.T, regProtocol *registryProtocol) *common.URL { extension.SetProtocol("registry", GetProtocol) extension.SetRegistry("mock", registry.NewMockRegistry) extension.SetProtocol(protocolwrapper.FILTER, protocolwrapper.NewMockProtocolFilter) url, _ := common.NewURL(context.TODO(), "mock://127.0.0.1:1111") - suburl, _ := common.NewURL(context.TODO(), "dubbo://127.0.0.1:20000//", common.WithParamsValue(constant.CLUSTER_KEY, "mock")) + suburl, _ := common.NewURL( + context.TODO(), + "dubbo://127.0.0.1:20000/org.apache.dubbo-go.mockService", + common.WithParamsValue(constant.CLUSTER_KEY, "mock"), + common.WithParamsValue(constant.GROUP_KEY, "group"), + common.WithParamsValue(constant.VERSION_KEY, "1.0.0"), + ) url.SubURL = &suburl invoker := protocol.NewBaseInvoker(url) @@ -105,9 +135,11 @@ func exporterNormal(t *testing.T, regProtocol *registryProtocol) { assert.IsType(t, &protocol.BaseExporter{}, exporter) assert.Equal(t, exporter.GetInvoker().GetUrl().String(), suburl.String()) + return &url } func TestExporter(t *testing.T) { + regProtocol := newRegistryProtocol() exporterNormal(t, regProtocol) } @@ -117,7 +149,11 @@ func TestMultiRegAndMultiProtoExporter(t *testing.T) { exporterNormal(t, regProtocol) url2, _ := common.NewURL(context.TODO(), "mock://127.0.0.1:2222") - suburl2, _ := common.NewURL(context.TODO(), "jsonrpc://127.0.0.1:20000//", common.WithParamsValue(constant.CLUSTER_KEY, "mock")) + suburl2, _ := common.NewURL( + context.TODO(), + "jsonrpc://127.0.0.1:20000//", + common.WithParamsValue(constant.CLUSTER_KEY, "mock"), + ) url2.SubURL = &suburl2 invoker2 := protocol.NewBaseInvoker(url2) @@ -143,7 +179,13 @@ func TestOneRegAndProtoExporter(t *testing.T) { exporterNormal(t, regProtocol) url2, _ := common.NewURL(context.TODO(), "mock://127.0.0.1:1111") - suburl2, _ := common.NewURL(context.TODO(), "dubbo://127.0.0.1:20000//", common.WithParamsValue(constant.CLUSTER_KEY, "mock")) + suburl2, _ := common.NewURL( + context.TODO(), + "dubbo://127.0.0.1:20000/org.apache.dubbo-go.mockService", + common.WithParamsValue(constant.CLUSTER_KEY, "mock"), + common.WithParamsValue(constant.GROUP_KEY, "group"), + common.WithParamsValue(constant.VERSION_KEY, "1.0.0"), + ) url2.SubURL = &suburl2 invoker2 := protocol.NewBaseInvoker(url2) @@ -186,3 +228,66 @@ func TestDestry(t *testing.T) { }) assert.Equal(t, count2, 0) } + +func TestExportWithOverrideListener(t *testing.T) { + extension.SetDefaultConfigurator(configurator.NewMockConfigurator) + + regProtocol := newRegistryProtocol() + url := exporterNormal(t, regProtocol) + var reg *registry.MockRegistry + if regI, loaded := regProtocol.registries.Load(url.Key()); loaded { + reg = regI.(*registry.MockRegistry) + } else { + assert.Fail(t, "regProtocol.registries.Load can not be loaded") + return + } + overrideUrl, _ := common.NewURL( + context.Background(), + "override://0:0:0:0/org.apache.dubbo-go.mockService?cluster=mock1&&group=group&&version=1.0.0", + ) + event := ®istry.ServiceEvent{Action: remoting.EventTypeAdd, Service: overrideUrl} + reg.MockEvent(event) + time.Sleep(1e9) + newUrl := url.SubURL.Clone() + newUrl.SetParam(constant.CLUSTER_KEY, "mock1") + v2, _ := regProtocol.bounds.Load(getCacheKey(newUrl)) + assert.NotNil(t, v2) +} + +func TestExportWithServiceConfig(t *testing.T) { + extension.SetDefaultConfigurator(configurator.NewMockConfigurator) + ccUrl, _ := common.NewURL(context.TODO(), "mock://127.0.0.1:1111") + dc, _ := (&config_center.MockDynamicConfigurationFactory{}).GetDynamicConfiguration(&ccUrl) + common_cfg.GetEnvInstance().SetDynamicConfiguration(dc) + regProtocol := newRegistryProtocol() + url := exporterNormal(t, regProtocol) + if _, loaded := regProtocol.registries.Load(url.Key()); !loaded { + assert.Fail(t, "regProtocol.registries.Load can not be loaded") + return + } + dc.(*config_center.MockDynamicConfiguration).MockServiceConfigEvent() + + newUrl := url.SubURL.Clone() + newUrl.SetParam(constant.CLUSTER_KEY, "mock1") + v2, _ := regProtocol.bounds.Load(getCacheKey(newUrl)) + assert.NotNil(t, v2) +} + +func TestExportWithApplicationConfig(t *testing.T) { + extension.SetDefaultConfigurator(configurator.NewMockConfigurator) + ccUrl, _ := common.NewURL(context.TODO(), "mock://127.0.0.1:1111") + dc, _ := (&config_center.MockDynamicConfigurationFactory{}).GetDynamicConfiguration(&ccUrl) + common_cfg.GetEnvInstance().SetDynamicConfiguration(dc) + regProtocol := newRegistryProtocol() + url := exporterNormal(t, regProtocol) + if _, loaded := regProtocol.registries.Load(url.Key()); !loaded { + assert.Fail(t, "regProtocol.registries.Load can not be loaded") + return + } + dc.(*config_center.MockDynamicConfiguration).MockApplicationConfigEvent() + + newUrl := url.SubURL.Clone() + newUrl.SetParam(constant.CLUSTER_KEY, "mock1") + v2, _ := regProtocol.bounds.Load(getCacheKey(newUrl)) + assert.NotNil(t, v2) +} diff --git a/registry/registry.go b/registry/registry.go index b41ac534ba..c7279a29e1 100644 --- a/registry/registry.go +++ b/registry/registry.go @@ -28,10 +28,21 @@ type Registry interface { //And it is also used for service consumer calling , register services cared about ,for dubbo's admin monitoring. Register(url common.URL) error - //used for service consumer ,start subscribe service event from registry - Subscribe(common.URL) (Listener, error) + //When creating new registry extension,pls select one of the following modes. + //Will remove in dubbogo version v1.1.0 + //mode1 : return Listener with Next function which can return subscribe service event from registry + //Deprecated! + //subscribe(common.URL) (Listener, error) + + //Will relace mode1 in dubbogo version v1.1.0 + //mode2 : callback mode, subscribe with notify(notify listener). + Subscribe(*common.URL, NotifyListener) +} +type NotifyListener interface { + Notify(*ServiceEvent) } +//Deprecated! type Listener interface { Next() (*ServiceEvent, error) Close() diff --git a/registry/zookeeper/listener.go b/registry/zookeeper/listener.go index 7d58cee122..857421f077 100644 --- a/registry/zookeeper/listener.go +++ b/registry/zookeeper/listener.go @@ -21,12 +21,15 @@ import ( "context" "strings" ) + import ( perrors "github.com/pkg/errors" ) + import ( "github.com/apache/dubbo-go/common" "github.com/apache/dubbo-go/common/logger" + "github.com/apache/dubbo-go/config_center" "github.com/apache/dubbo-go/registry" "github.com/apache/dubbo-go/remoting" zk "github.com/apache/dubbo-go/remoting/zookeeper" @@ -34,10 +37,10 @@ import ( type RegistryDataListener struct { interestedURL []*common.URL - listener remoting.ConfigurationListener + listener config_center.ConfigurationListener } -func NewRegistryDataListener(listener remoting.ConfigurationListener) *RegistryDataListener { +func NewRegistryDataListener(listener config_center.ConfigurationListener) *RegistryDataListener { return &RegistryDataListener{listener: listener, interestedURL: []*common.URL{}} } func (l *RegistryDataListener) AddInterestedURL(url *common.URL) { @@ -59,7 +62,7 @@ func (l *RegistryDataListener) DataChange(eventType remoting.Event) bool { } for _, v := range l.interestedURL { if serviceURL.URLEqual(*v) { - l.listener.Process(&remoting.ConfigChangeEvent{Value: serviceURL, ConfigType: eventType.Action}) + l.listener.Process(&config_center.ConfigChangeEvent{Value: serviceURL, ConfigType: eventType.Action}) return true } } @@ -70,14 +73,14 @@ func (l *RegistryDataListener) DataChange(eventType remoting.Event) bool { type RegistryConfigurationListener struct { client *zk.ZookeeperClient registry *zkRegistry - events chan *remoting.ConfigChangeEvent + events chan *config_center.ConfigChangeEvent } func NewRegistryConfigurationListener(client *zk.ZookeeperClient, reg *zkRegistry) *RegistryConfigurationListener { reg.wg.Add(1) - return &RegistryConfigurationListener{client: client, registry: reg, events: make(chan *remoting.ConfigChangeEvent, 32)} + return &RegistryConfigurationListener{client: client, registry: reg, events: make(chan *config_center.ConfigChangeEvent, 32)} } -func (l *RegistryConfigurationListener) Process(configType *remoting.ConfigChangeEvent) { +func (l *RegistryConfigurationListener) Process(configType *config_center.ConfigChangeEvent) { l.events <- configType } diff --git a/registry/zookeeper/listener_test.go b/registry/zookeeper/listener_test.go index 9d9cebefcb..910d47b7e4 100644 --- a/registry/zookeeper/listener_test.go +++ b/registry/zookeeper/listener_test.go @@ -22,10 +22,14 @@ import ( "testing" ) +import ( + "github.com/stretchr/testify/assert" +) + import ( "github.com/apache/dubbo-go/common" + "github.com/apache/dubbo-go/config_center" "github.com/apache/dubbo-go/remoting" - "github.com/stretchr/testify/assert" ) func Test_DataChange(t *testing.T) { @@ -39,5 +43,5 @@ func Test_DataChange(t *testing.T) { type MockDataListener struct { } -func (*MockDataListener) Process(configType *remoting.ConfigChangeEvent) { +func (*MockDataListener) Process(configType *config_center.ConfigChangeEvent) { } diff --git a/registry/zookeeper/registry.go b/registry/zookeeper/registry.go index 99e4fa15ce..972a4b6c5e 100644 --- a/registry/zookeeper/registry.go +++ b/registry/zookeeper/registry.go @@ -44,7 +44,8 @@ import ( ) const ( - RegistryZkClient = "zk registry" + RegistryZkClient = "zk registry" + RegistryConnDelay = 3 ) var ( @@ -146,6 +147,7 @@ func newMockZkRegistry(url *common.URL, opts ...zookeeper.Option) (*zk.TestClust return c, r, nil } + func (r *zkRegistry) ZkClient() *zookeeper.ZookeeperClient { return r.client } @@ -394,11 +396,45 @@ func (r *zkRegistry) registerTempZookeeperNode(root string, node string) error { return nil } -func (r *zkRegistry) Subscribe(conf common.URL) (registry.Listener, error) { +func (r *zkRegistry) subscribe(conf *common.URL) (registry.Listener, error) { return r.getListener(conf) } -func (r *zkRegistry) getListener(conf common.URL) (*RegistryConfigurationListener, error) { +//subscribe from registry +func (r *zkRegistry) Subscribe(url *common.URL, notifyListener registry.NotifyListener) { + for { + if !r.IsAvailable() { + logger.Warnf("event listener game over.") + return + } + + listener, err := r.subscribe(url) + if err != nil { + if !r.IsAvailable() { + logger.Warnf("event listener game over.") + return + } + logger.Warnf("getListener() = err:%v", perrors.WithStack(err)) + time.Sleep(time.Duration(RegistryConnDelay) * time.Second) + continue + } + + for { + if serviceEvent, err := listener.Next(); err != nil { + logger.Warnf("Selector.watch() = error{%v}", perrors.WithStack(err)) + listener.Close() + return + } else { + logger.Infof("update begin, service event: %v", serviceEvent.String()) + notifyListener.Notify(serviceEvent) + } + + } + + } +} + +func (r *zkRegistry) getListener(conf *common.URL) (*RegistryConfigurationListener, error) { var ( zkListener *RegistryConfigurationListener ) @@ -423,9 +459,10 @@ func (r *zkRegistry) getListener(conf common.URL) (*RegistryConfigurationListene } //Interested register to dataconfig. - r.dataListener.AddInterestedURL(&conf) - - go r.listener.ListenServiceEvent(fmt.Sprintf("/dubbo/%s/providers", conf.Service()), r.dataListener) + r.dataListener.AddInterestedURL(conf) + for _, v := range strings.Split(conf.GetParam(constant.CATEGORY_KEY, constant.DEFAULT_CATEGORY), ",") { + go r.listener.ListenServiceEvent(fmt.Sprintf("/dubbo/%s/"+v, conf.Service()), r.dataListener) + } return zkListener, nil } diff --git a/registry/zookeeper/registry_test.go b/registry/zookeeper/registry_test.go index 2ac946a3fa..841c38da7f 100644 --- a/registry/zookeeper/registry_test.go +++ b/registry/zookeeper/registry_test.go @@ -64,7 +64,7 @@ func Test_Subscribe(t *testing.T) { _, reg2, _ := newMockZkRegistry(®url, zookeeper.WithTestCluster(ts)) reg2.Register(url) - listener, _ := reg2.Subscribe(url) + listener, _ := reg2.subscribe(&url) serviceEvent, _ := listener.Next() assert.NoError(t, err) @@ -85,7 +85,7 @@ func Test_ConsumerDestory(t *testing.T) { assert.NoError(t, err) err = reg.Register(url) assert.NoError(t, err) - _, err = reg.Subscribe(url) + _, err = reg.subscribe(&url) assert.NoError(t, err) //listener.Close() diff --git a/remoting/listener.go b/remoting/listener.go index b94ba26980..8d1e357d37 100644 --- a/remoting/listener.go +++ b/remoting/listener.go @@ -17,26 +17,14 @@ package remoting -import "fmt" - -type ConfigurationListener interface { - Process(*ConfigChangeEvent) -} +import ( + "fmt" +) type DataListener interface { DataChange(eventType Event) bool //bool is return for interface implement is interesting } -type ConfigChangeEvent struct { - Key string - Value interface{} - ConfigType EventType -} - -func (c ConfigChangeEvent) String() string { - return fmt.Sprintf("ConfigChangeEvent{key = %v , value = %v , changeType = %v}", c.Key, c.Value, c.ConfigType) -} - ////////////////////////////////////////// // event type ////////////////////////////////////////// diff --git a/remoting/zookeeper/listener_test.go b/remoting/zookeeper/listener_test.go index 8b133336e7..a90fbad05a 100644 --- a/remoting/zookeeper/listener_test.go +++ b/remoting/zookeeper/listener_test.go @@ -117,6 +117,8 @@ func (m *mockDataListener) DataChange(eventType remoting.Event) bool { m.eventList = append(m.eventList, eventType) if eventType.Content == m.changedData { m.wait.Done() + m.client.Close() + } return true }