diff --git a/common/url.go b/common/url.go index 26c4ebdb34..fc618ea7cf 100644 --- a/common/url.go +++ b/common/url.go @@ -210,7 +210,7 @@ func WithToken(token string) Option { if len(token) > 0 { value := token if strings.ToLower(token) == "true" || strings.ToLower(token) == "default" { - u := uuid.NewV4() + u, _ := uuid.NewV4() value = u.String() } url.SetParam(constant.TOKEN_KEY, value) diff --git a/config/application_config.go b/config/application_config.go index 11181093a9..fb766bef02 100644 --- a/config/application_config.go +++ b/config/application_config.go @@ -55,14 +55,6 @@ func (ac *ApplicationConfig) Init() error { return nil } -func GetApplicationInstance(opts ...ApplicationConfigOpt) *ApplicationConfig { - ac := &ApplicationConfig{} - for _, opt := range opts { - opt(ac) - } - return ac -} - func (ac *ApplicationConfig) check() error { if err := defaults.Set(ac); err != nil { return err @@ -70,46 +62,49 @@ func (ac *ApplicationConfig) check() error { return verify(ac) } -type ApplicationConfigOpt func(config *ApplicationConfig) +func NewApplicationConfigBuilder() *ApplicationConfigBuilder { + return &ApplicationConfigBuilder{application: &ApplicationConfig{}} +} -func WithOrganization(organization string) ApplicationConfigOpt { - return func(ac *ApplicationConfig) { - ac.Organization = organization - } +type ApplicationConfigBuilder struct { + application *ApplicationConfig } -func WithName(name string) ApplicationConfigOpt { - return func(ac *ApplicationConfig) { - ac.Name = name - } +func (acb *ApplicationConfigBuilder) SetOrganization(organization string) *ApplicationConfigBuilder { + acb.application.Organization = organization + return acb } -func WithModule(module string) ApplicationConfigOpt { - return func(ac *ApplicationConfig) { - ac.Module = module - } +func (acb *ApplicationConfigBuilder) SetName(name string) *ApplicationConfigBuilder { + acb.application.Name = name + return acb } -func WithVersion(version string) ApplicationConfigOpt { - return func(ac *ApplicationConfig) { - ac.Version = version - } +func (acb *ApplicationConfigBuilder) SetModule(module string) *ApplicationConfigBuilder { + acb.application.Module = module + return acb } -func WithOwner(owner string) ApplicationConfigOpt { - return func(ac *ApplicationConfig) { - ac.Owner = owner - } +func (acb *ApplicationConfigBuilder) SetVersion(version string) *ApplicationConfigBuilder { + acb.application.Version = version + return acb } -func WithEnvironment(env string) ApplicationConfigOpt { - return func(ac *ApplicationConfig) { - ac.Environment = env - } +func (acb *ApplicationConfigBuilder) SetOwner(owner string) *ApplicationConfigBuilder { + acb.application.Owner = owner + return acb } -func WithMetadataType(metadataType string) ApplicationConfigOpt { - return func(ac *ApplicationConfig) { - ac.MetadataType = metadataType - } +func (acb *ApplicationConfigBuilder) SetEnvironment(environment string) *ApplicationConfigBuilder { + acb.application.Environment = environment + return acb +} + +func (acb *ApplicationConfigBuilder) SetMetadataType(metadataType string) *ApplicationConfigBuilder { + acb.application.MetadataType = metadataType + return acb +} + +func (acb *ApplicationConfigBuilder) Build() *ApplicationConfig { + return acb.application } diff --git a/config/config_center_config.go b/config/config_center_config.go index b0b4e60ba5..6ac615f9b5 100644 --- a/config/config_center_config.go +++ b/config/config_center_config.go @@ -76,16 +76,6 @@ func (CenterConfig) Prefix() string { return constant.ConfigCenterPrefix } -func GetConfigCenterInstance(opts ...CenterConfigOpt) *CenterConfig { - cc := &CenterConfig{ - Params: make(map[string]string, 1), - } - for _, opt := range opts { - opt(cc) - } - return cc -} - func (c *CenterConfig) check() error { if err := defaults.Set(c); err != nil { return err @@ -140,21 +130,6 @@ func (c *CenterConfig) translateConfigAddress() string { // toURL will compatible with baseConfig.ShutdownConfig.Address and baseConfig.ShutdownConfig.RemoteRef before 1.6.0 // After 1.6.0 will not compatible, only baseConfig.ShutdownConfig.RemoteRef func (c *CenterConfig) toURL() (*common.URL, error) { - //remoteRef := baseConfig.ConfigCenterConfig.RemoteRef - //// if set remote ref use remote - //if len(remoteRef) <= 0 { - // return common.NewURL(baseConfig.ConfigCenterConfig.Address, - // common.WithProtocol(baseConfig.ConfigCenterConfig.Protocol), - // common.WithParams(baseConfig.ConfigCenterConfig.GetUrlMap())) - //} - //rc, ok := baseConfig.GetRemoteConfig(remoteRef) - //if !ok { - // return nil, perrors.New("Could not find out the remote ref config, name: " + remoteRef) - //} - //// set protocol if remote not set - //if len(rc.Protocol) <= 0 { - // rc.Protocol = baseConfig.ConfigCenterConfig.Protocol - //} return common.NewURL(c.Address, common.WithProtocol(c.Protocol), common.WithParams(c.GetUrlMap())) @@ -211,105 +186,57 @@ func (c *CenterConfig) prepareEnvironment(configCenterUrl *common.URL) (string, envInstance.SetDynamicConfiguration(dynamicConfig) return dynamicConfig.GetProperties(c.DataId, config_center.WithGroup(c.Group)) - //if err != nil { - // logger.Errorf("Get config content in dynamic configuration error , error message is %v", err) - // return errors.WithStack(err) - //} - //yaml.Unmarshal([]byte(conten),rootConfig) - //var appGroup string - //var appContent string - //if config2.providerConfig != nil && config2.providerConfig.ApplicationConfig != nil && - // reflect.ValueOf(baseConfig.fatherConfig).Elem().Type().Name() == "ProviderConfig" { - // appGroup = config2.providerConfig.ApplicationConfig.Name - //} else if config2.consumerConfig != nil && config2.consumerConfig.ApplicationConfig != nil && - // reflect.ValueOf(baseConfig.fatherConfig).Elem().Type().Name() == "ConsumerConfig" { - // appGroup = config2.consumerConfig.ApplicationConfig.Name - //} - // - //if len(appGroup) != 0 { - // configFile := baseConfig.ConfigCenterConfig.AppConfigFile - // if len(configFile) == 0 { - // configFile = baseConfig.ConfigCenterConfig.ConfigFile - // } - // appContent, err = dynamicConfig.GetProperties(configFile, config_center.WithGroup(appGroup)) - // if err != nil { - // return perrors.WithStack(err) - // } - //} - //// global config file - //mapContent, err := dynamicConfig.Parser().Parse(content) - //if err != nil { - // return perrors.WithStack(err) - //} - //envInstance.UpdateExternalConfigMap(mapContent) - // - //// appGroup config file - //if len(appContent) != 0 { - // appMapContent, err := dynamicConfig.Parser().Parse(appContent) - // if err != nil { - // return perrors.WithStack(err) - // } - // envInstance.UpdateAppExternalConfigMap(appMapContent) - //} } -type CenterConfigOpt func(config *CenterConfig) +func NewConfigCenterConfigBuilder() *ConfigCenterConfigBuilder { + return &ConfigCenterConfigBuilder{configCenterConfig: newEmptyConfigCenterConfig()} +} -func NewConfigCenterConfig(opts ...CenterConfigOpt) *CenterConfig { - centerConfig := &CenterConfig{ - Params: make(map[string]string), - } - for _, o := range opts { - o(centerConfig) - } - return centerConfig +type ConfigCenterConfigBuilder struct { + configCenterConfig *CenterConfig } -// WithConfigCenterProtocol set ProtocolConfig with given protocolName protocol -func WithConfigCenterProtocol(protocol string) CenterConfigOpt { - return func(config *CenterConfig) { - config.Protocol = protocol - } +func (ccb *ConfigCenterConfigBuilder) SetProtocol(protocol string) *ConfigCenterConfigBuilder { + ccb.configCenterConfig.Protocol = protocol + return ccb } -// WithConfigCenterAddress set ProtocolConfig with given @addr -func WithConfigCenterAddress(addr string) CenterConfigOpt { - return func(config *CenterConfig) { - config.Address = addr - } +func (ccb *ConfigCenterConfigBuilder) SetUserName(userName string) *ConfigCenterConfigBuilder { + ccb.configCenterConfig.Username = userName + return ccb } -// WithConfigCenterDataID set ProtocolConfig with given @dataID -func WithConfigCenterDataID(dataID string) CenterConfigOpt { - return func(config *CenterConfig) { - config.DataId = dataID - } +func (ccb *ConfigCenterConfigBuilder) SetAddress(address string) *ConfigCenterConfigBuilder { + ccb.configCenterConfig.Address = address + return ccb } -// WithConfigCenterGroup set ProtocolConfig with given @group -func WithConfigCenterGroup(group string) CenterConfigOpt { - return func(config *CenterConfig) { - config.Group = group - } +func (ccb *ConfigCenterConfigBuilder) SetPassword(password string) *ConfigCenterConfigBuilder { + ccb.configCenterConfig.Password = password + return ccb } -// WithConfigCenterUsername set ProtocolConfig with given @username -func WithConfigCenterUsername(username string) CenterConfigOpt { - return func(config *CenterConfig) { - config.Username = username - } +func (ccb *ConfigCenterConfigBuilder) SetNamespace(namespace string) *ConfigCenterConfigBuilder { + ccb.configCenterConfig.Namespace = namespace + return ccb } -// WithConfigCenterPassword set ProtocolConfig with given @password -func WithConfigCenterPassword(password string) CenterConfigOpt { - return func(config *CenterConfig) { - config.Password = password - } +func (ccb *ConfigCenterConfigBuilder) SetDataID(dataID string) *ConfigCenterConfigBuilder { + ccb.configCenterConfig.DataId = dataID + return ccb } -// WithConfigCenterNamespace set ProtocolConfig with given @namespace -func WithConfigCenterNamespace(namespace string) CenterConfigOpt { - return func(config *CenterConfig) { - config.Namespace = namespace +func (ccb *ConfigCenterConfigBuilder) SetGroup(group string) *ConfigCenterConfigBuilder { + ccb.configCenterConfig.Group = group + return ccb +} + +func (ccb *ConfigCenterConfigBuilder) Build() *CenterConfig { + return ccb.configCenterConfig +} + +func newEmptyConfigCenterConfig() *CenterConfig { + return &CenterConfig{ + Params: make(map[string]string), } } diff --git a/config/config_loader.go b/config/config_loader.go index 6a3f411612..b309cc5a5a 100644 --- a/config/config_loader.go +++ b/config/config_loader.go @@ -42,7 +42,7 @@ import ( ) var ( - rootConfig = GetInstance() + rootConfig = NewRootConfigBuilder().Build() maxWait = 3 ) @@ -188,19 +188,19 @@ func RPCService(service common.RPCService) { // So you don't need to worry about the race condition func GetMetricConfig() *MetricConfig { // todo - //if GetBaseConfig().MetricConfig == nil { + //if GetBaseConfig().Metric == nil { // configAccessMutex.Lock() // defer configAccessMutex.Unlock() - // if GetBaseConfig().MetricConfig == nil { - // GetBaseConfig().MetricConfig = &metric.MetricConfig{} + // if GetBaseConfig().Metric == nil { + // GetBaseConfig().Metric = &metric.Metric{} // } //} - //return GetBaseConfig().MetricConfig - return rootConfig.MetricConfig + //return GetBaseConfig().Metric + return rootConfig.Metric } func GetMetadataReportConfg() *MetadataReportConfig { - return rootConfig.MetadataReportConfig + return rootConfig.MetadataReport } func IsProvider() bool { diff --git a/config/config_loader_test.go b/config/config_loader_test.go deleted file mode 100644 index 73b96fc50e..0000000000 --- a/config/config_loader_test.go +++ /dev/null @@ -1,593 +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 config - -import ( - "testing" -) - -import ( - "github.com/stretchr/testify/assert" -) - -const ( - configPath = "./testdata/application.yaml" -) - -func TestLoad(t *testing.T) { - err := Load(WithPath(configPath)) - assert.Nil(t, err) - t.Run("application", func(t *testing.T) { - application := rootConfig.Application - - assert.Equal(t, "dubbo-go", application.Organization) - assert.Equal(t, "dubbo-go", application.Name) - assert.Equal(t, "local", application.Module) - assert.Equal(t, "1.0.0", application.Version) - assert.Equal(t, "zhaoyunxing", application.Owner) - assert.Equal(t, "dev", application.Environment) - assert.Equal(t, "local", application.MetadataType) - }) - - t.Run("registries", func(t *testing.T) { - registries := rootConfig.Registries - - assert.Equal(t, 2, len(registries)) - //address= nacos://127.0.0.1:8848 Translate Registry Address - assert.Equal(t, "nacos", registries["nacos"].Protocol) - assert.Equal(t, "5s", registries["zk"].Timeout) - }) - - //config-center - t.Run("config-center", func(t *testing.T) { - conf := rootConfig.ConfigCenter - - assert.Equal(t, "nacos", conf.Protocol) - }) - -} - -//TestLoadConfigCenter test key config_center、config-center 、configCenter -func TestLoadConfigCenter(t *testing.T) { - - err := Load(WithPath("./testdata/config/center/conf-application.yaml")) - assert.Nil(t, err) - conf := rootConfig.ConfigCenter - assert.Equal(t, "nacos", conf.Protocol) - assert.Equal(t, "10s", conf.Timeout) - assert.Equal(t, "./logs", conf.LogDir) -} - -func TestGetRegistriesConfig(t *testing.T) { - - err := Load(WithPath("./testdata/config/registry/application.yaml")) - - assert.Nil(t, err) - registries := rootConfig.Registries - - assert.Equal(t, 2, len(registries)) - // nacos - assert.Equal(t, "nacos", registries["nacos"].Protocol) - assert.Equal(t, "5s", registries["nacos"].Timeout) - assert.Equal(t, "127.0.0.1:8848", registries["nacos"].Address) - assert.Equal(t, "dev", registries["nacos"].Group) - // zk - assert.Equal(t, "zookeeper", registries["zk"].Protocol) - assert.Equal(t, "5s", registries["zk"].Timeout) - assert.Equal(t, "127.0.0.1:2181", registries["zk"].Address) - assert.Equal(t, "test", registries["zk"].Group) -} - -// -//func TestLoadWithSingleReg(t *testing.T) { -// reference.doInitConsumerWithSingleRegistry() -// mockInitProviderWithSingleRegistry() -// -// ms := &MockService{} -// instance.SetConsumerService(ms) -// instance.SetProviderService(ms) -// -// extension.SetProtocol("registry", reference.GetProtocol) -// extension.SetCluster(constant.ZONEAWARE_CLUSTER_NAME, cluster_impl.NewZoneAwareCluster) -// extension.SetProxyFactory("default", proxy_factory.NewDefaultProxyFactory) -// var mm *mockMetadataService -// GetApplicationConfig().MetadataType = "mock" -// extension.SetLocalMetadataService("mock", func() (metadataService service.MetadataService, err error) { -// if mm == nil { -// mm = &mockMetadataService{ -// exportedServiceURLs: new(sync.Map), -// lock: new(sync.RWMutex), -// } -// } -// return mm, nil -// }) -// Load() -// -// assert.Equal(t, ms, GetRPCService(ms.Reference())) -// ms2 := &struct { -// MockService -// }{} -// RPCService(ms2) -// assert.NotEqual(t, ms2, GetRPCService(ms2.Reference())) -// -// service2.conServices = map[string]common.RPCService{} -// service2.proServices = map[string]common.RPCService{} -// common.ServiceMap.UnRegister("com.MockService", "mock", common.ServiceKey("com.MockService", "huadong_idc", "1.0.0")) -// consumerConfig = nil -// providerConfig = nil -//} -// -//func TestWithNoRegLoad(t *testing.T) { -// reference.doInitConsumer() -// service2.doInitProvider() -// providerConfig.Services["MockService"].Registry = "" -// consumerConfig.References["MockService"].Registry = "" -// ms := &MockService{} -// instance.SetConsumerService(ms) -// instance.SetProviderService(ms) -// -// extension.SetProtocol("registry", reference.GetProtocol) -// extension.SetCluster(constant.ZONEAWARE_CLUSTER_NAME, cluster_impl.NewZoneAwareCluster) -// extension.SetProxyFactory("default", proxy_factory.NewDefaultProxyFactory) -// var mm *mockMetadataService -// GetApplicationConfig().MetadataType = "mock" -// extension.SetLocalMetadataService("mock", func() (metadataService service.MetadataService, err error) { -// if mm == nil { -// mm = &mockMetadataService{ -// exportedServiceURLs: new(sync.Map), -// lock: new(sync.RWMutex), -// } -// } -// return mm, nil -// }) -// Load() -// -// assert.Equal(t, ms, GetRPCService(ms.Reference())) -// ms2 := &struct { -// MockService -// }{} -// RPCService(ms2) -// assert.NotEqual(t, ms2, GetRPCService(ms2.Reference())) -// -// service2.conServices = map[string]common.RPCService{} -// service2.proServices = map[string]common.RPCService{} -// err := common.ServiceMap.UnRegister("com.MockService", "mock", -// common.ServiceKey("com.MockService", "huadong_idc", "1.0.0")) -// assert.Nil(t, err) -// common.ServiceMap.UnRegister("com.MockService", "mock", common.ServiceKey("com.MockService", "huadong_idc", "1.0.0")) -// consumerConfig = nil -// providerConfig = nil -//} -// -//func TestSetDefaultValue(t *testing.T) { -// proConfig := &provider.ProviderConfig{Registries: make(map[string]*registry2.RegistryConfig), Protocols: make(map[string]*protocol2.ProtocolConfig)} -// assert.Nil(t, proConfig.ApplicationConfig) -// setDefaultValue(proConfig) -// assert.Equal(t, proConfig.Registries["demoZK"].Address, "127.0.0.1:2181") -// assert.Equal(t, proConfig.Registries["demoZK"].TimeoutStr, "3s") -// assert.Equal(t, proConfig.Registries["demoZK"].Protocol, "zookeeper") -// assert.Equal(t, proConfig.Protocols["dubbo"].Name, "dubbo") -// assert.Equal(t, proConfig.Protocols["dubbo"].Port, "20000") -// assert.NotNil(t, proConfig.ApplicationConfig) -// -// conConfig := &consumer.ShutdownConfig{Registries: make(map[string]*registry2.RegistryConfig)} -// assert.Nil(t, conConfig.ApplicationConfig) -// setDefaultValue(conConfig) -// assert.Equal(t, conConfig.Registries["demoZK"].Address, "127.0.0.1:2181") -// assert.Equal(t, conConfig.Registries["demoZK"].TimeoutStr, "3s") -// assert.Equal(t, conConfig.Registries["demoZK"].Protocol, "zookeeper") -// assert.NotNil(t, conConfig.ApplicationConfig) -// -//} -//func TestConfigLoaderWithConfigCenter(t *testing.T) { -// extension.SetConfigCenterFactory("mock", func() config_center.DynamicConfigurationFactory { -// return &config_center.MockDynamicConfigurationFactory{} -// }) -// -// conPath, err := filepath.Abs("./testdata/consumer_config_with_configcenter.yml") -// assert.NoError(t, err) -// proPath, err := filepath.Abs(mockProviderConfigPath) -// assert.NoError(t, err) -// -// assert.Nil(t, consumerConfig) -// assert.Equal(t, consumer.ShutdownConfig{}, GetConsumerConfig()) -// assert.Nil(t, providerConfig) -// assert.Equal(t, provider.ProviderConfig{}, GetProviderConfig()) -// -// err = consumer.ConsumerInit(conPath) -// assert.NoError(t, err) -// err = consumer.configCenterRefreshConsumer() -// assert.NoError(t, err) -// err = provider.ProviderInit(proPath) -// assert.NoError(t, err) -// err = provider.configCenterRefreshProvider() -// assert.NoError(t, err) -// -// assert.NotNil(t, consumerConfig) -// assert.NotEqual(t, consumer.ShutdownConfig{}, GetConsumerConfig()) -// assert.NotNil(t, providerConfig) -// assert.NotEqual(t, provider.ProviderConfig{}, GetProviderConfig()) -// -// assert.Equal(t, "BDTService", consumerConfig.ApplicationConfig.Name) -// 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.applicationConfig.organization=ikurento.com -// dubbo.applicationConfig.name=BDTService -// dubbo.applicationConfig.module=dubbogo user-info server -// dubbo.applicationConfig.version=0.0.1 -// dubbo.applicationConfig.owner=ZX -// dubbo.applicationConfig.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(mockProviderConfigPath) -// assert.NoError(t, err) -// -// assert.Nil(t, consumerConfig) -// assert.Equal(t, consumer.ShutdownConfig{}, GetConsumerConfig()) -// assert.Nil(t, providerConfig) -// assert.Equal(t, provider.ProviderConfig{}, GetProviderConfig()) -// -// err = consumer.ConsumerInit(conPath) -// assert.NoError(t, err) -// checkApplicationName(consumerConfig.ApplicationConfig) -// err = consumer.configCenterRefreshConsumer() -// checkRegistries(consumerConfig.Registries, consumerConfig.Registry) -// assert.NoError(t, err) -// err = provider.ProviderInit(proPath) -// assert.NoError(t, err) -// checkApplicationName(providerConfig.ApplicationConfig) -// err = provider.configCenterRefreshProvider() -// checkRegistries(providerConfig.Registries, providerConfig.Registry) -// assert.NoError(t, err) -// -// assert.NotNil(t, consumerConfig) -// assert.NotEqual(t, consumer.ShutdownConfig{}, GetConsumerConfig()) -// assert.NotNil(t, providerConfig) -// assert.NotEqual(t, provider.ProviderConfig{}, GetProviderConfig()) -// -// assert.Equal(t, "BDTService", consumerConfig.ApplicationConfig.Name) -// assert.Equal(t, "mock://127.0.0.1:2182", consumerConfig.Registries[constant.DEFAULT_KEY].Address) -//} -// -//func TestGetBaseConfig(t *testing.T) { -// bc := GetBaseConfig() -// assert.NotNil(t, bc) -// _, found := bc.GetRemoteConfig("mock") -// assert.False(t, found) -//} -// -//// mockInitProviderWithSingleRegistry will init a mocked providerConfig -//func mockInitProviderWithSingleRegistry() { -// providerConfig = &provider.ProviderConfig{ -// BaseConfig: base.ShutdownConfig{ -// applicationConfig.ShutdownConfig: &applicationConfig.ShutdownConfig{ -// Organization: "dubbo_org", -// Name: "dubbo", -// Module: "module", -// Version: "1.0.0", -// Owner: "dubbo", -// Environment: "test", -// }, -// }, -// -// Registry: ®istry2.RegistryConfig{ -// Address: "mock://127.0.0.1:2181", -// Username: "user1", -// Password: "pwd1", -// }, -// Registries: map[string]*registry2.RegistryConfig{}, -// -// Services: map[string]*service2.ShutdownConfig{ -// "MockService": { -// InterfaceName: "com.MockService", -// Protocol: "mock", -// Cluster: "failover", -// Loadbalance: "random", -// Retries: "3", -// Group: "huadong_idc", -// Version: "1.0.0", -// Methods: []*method.MethodConfig{ -// { -// Name: "GetUser", -// Retries: "2", -// LoadBalance: "random", -// Weight: 200, -// }, -// { -// Name: "GetUser1", -// Retries: "2", -// LoadBalance: "random", -// Weight: 200, -// }, -// }, -// exported: new(atomic.Bool), -// }, -// }, -// Protocols: map[string]*protocol2.ProtocolConfig{ -// "mock": { -// Name: "mock", -// Ip: "127.0.0.1", -// Port: "20000", -// }, -// }, -// } -//} -// -//type mockMetadataService struct { -// exportedServiceURLs *sync.Map -// lock *sync.RWMutex -//} -// -//func (m *mockMetadataService) GetExportedURLs(serviceInterface string, group string, version string, protocol string) ([]*common.URL, error) { -// panic("implement me") -//} -// -//func (m *mockMetadataService) GetMetadataInfo(revision string) (*common.MetadataInfo, error) { -// panic("implement me") -//} -// -//func (m *mockMetadataService) GetExportedServiceURLs() []*common.URL { -// panic("implement me") -//} -// -//func (m *mockMetadataService) GetMetadataServiceURL() *common.URL { -// panic("implement me") -//} -// -//func (m *mockMetadataService) SetMetadataServiceURL(url *common.URL) { -// panic("implement me") -//} -// -//func (m *mockMetadataService) Reference() string { -// panic("implement me") -//} -// -//func (m *mockMetadataService) ServiceName() (string, error) { -// panic("implement me") -//} -// -//func (m *mockMetadataService) ExportURL(url *common.URL) (bool, error) { -// return m.addURL(m.exportedServiceURLs, url), nil -//} -// -//func (m *mockMetadataService) UnexportURL(*common.URL) error { -// panic("implement me") -//} -// -//func (m *mockMetadataService) SubscribeURL(*common.URL) (bool, error) { -// panic("implement me") -//} -// -//func (m *mockMetadataService) UnsubscribeURL(*common.URL) error { -// panic("implement me") -//} -// -//func (m *mockMetadataService) PublishServiceDefinition(*common.URL) error { -// return nil -//} -// -//func (m *mockMetadataService) MethodMapper() map[string]string { -// panic("implement me") -//} -// -//func (m *mockMetadataService) GetSubscribedURLs() ([]*common.URL, error) { -// panic("implement me") -//} -// -//func (m *mockMetadataService) GetServiceDefinition(string, string, string) (string, error) { -// panic("implement me") -//} -// -//func (m *mockMetadataService) GetServiceDefinitionByServiceKey(string) (string, error) { -// panic("implement me") -//} -// -//func (m *mockMetadataService) RefreshMetadata(string, string) (bool, error) { -// panic("implement me") -//} -// -//func (m *mockMetadataService) Version() (string, error) { -// panic("implement me") -//} -// -//func (m *mockMetadataService) addURL(targetMap *sync.Map, url *common.URL) bool { -// var ( -// urlSet interface{} -// loaded bool -// ) -// logger.Debug(url.ServiceKey()) -// if urlSet, loaded = targetMap.LoadOrStore(url.ServiceKey(), skip.New(uint64(0))); loaded { -// m.lock.RLock() -// wantedUrl := urlSet.(*skip.SkipList).Get(url) -// if len(wantedUrl) > 0 && wantedUrl[0] != nil { -// m.lock.RUnlock() -// return false -// } -// m.lock.RUnlock() -// } -// m.lock.Lock() -// // double chk -// wantedUrl := urlSet.(*skip.SkipList).Get(url) -// if len(wantedUrl) > 0 && wantedUrl[0] != nil { -// m.lock.Unlock() -// return false -// } -// urlSet.(*skip.SkipList).Insert(url) -// m.lock.Unlock() -// return true -//} -// -//func (m *mockMetadataService) getAllService(services *sync.Map) []*common.URL { -// // using skip list to dedup and sorting -// var res []*common.URL -// services.Range(func(key, value interface{}) bool { -// urls := value.(*skip.SkipList) -// for i := uint64(0); i < urls.Len(); i++ { -// url := urls.ByPosition(i).(*common.URL) -// if url.GetParam(constant.INTERFACE_KEY, url.Path) != constant.METADATA_SERVICE_NAME { -// res = append(res, url) -// } -// } -// return true -// }) -// sort.Sort(common.URLSlice(res)) -// return res -//} -// -//type mockServiceDiscoveryRegistry struct{} -// -//func (mr *mockServiceDiscoveryRegistry) GetURL() *common.URL { -// panic("implement me") -//} -// -//func (mr *mockServiceDiscoveryRegistry) IsAvailable() bool { -// panic("implement me") -//} -// -//func (mr *mockServiceDiscoveryRegistry) Destroy() { -// panic("implement me") -//} -// -//func (mr *mockServiceDiscoveryRegistry) Register(*common.URL) error { -// panic("implement me") -//} -// -//func (mr *mockServiceDiscoveryRegistry) UnRegister(*common.URL) error { -// panic("implement me") -//} -// -//func (mr *mockServiceDiscoveryRegistry) Subscribe(*common.URL, registry.NotifyListener) error { -// panic("implement me") -//} -// -//func (mr *mockServiceDiscoveryRegistry) UnSubscribe(*common.URL, registry.NotifyListener) error { -// panic("implement me") -//} -// -//func (mr *mockServiceDiscoveryRegistry) GetServiceDiscovery() registry.ServiceDiscovery { -// return &mockServiceDiscovery{} -//} -// -//type mockServiceDiscovery struct{} -// -//func (m *mockServiceDiscovery) String() string { -// panic("implement me") -//} -// -//func (m *mockServiceDiscovery) Destroy() error { -// panic("implement me") -//} -// -//func (m *mockServiceDiscovery) Register(registry.ServiceInstance) error { -// return nil -//} -// -//func (m *mockServiceDiscovery) Update(registry.ServiceInstance) error { -// panic("implement me") -//} -// -//func (m *mockServiceDiscovery) Unregister(registry.ServiceInstance) error { -// panic("implement me") -//} -// -//func (m *mockServiceDiscovery) GetDefaultPageSize() int { -// panic("implement me") -//} -// -//func (m *mockServiceDiscovery) GetServices() *gxset.HashSet { -// panic("implement me") -//} -// -//func (m *mockServiceDiscovery) GetInstances(string) []registry.ServiceInstance { -// panic("implement me") -//} -// -//func (m *mockServiceDiscovery) GetInstancesByPage(string, int, int) gxpage.Pager { -// panic("implement me") -//} -// -//func (m *mockServiceDiscovery) GetHealthyInstancesByPage(string, int, int, bool) gxpage.Pager { -// panic("implement me") -//} -// -//func (m *mockServiceDiscovery) GetRequestInstances([]string, int, int) map[string]gxpage.Pager { -// panic("implement me") -//} -// -//func (m *mockServiceDiscovery) AddListener(registry.ServiceInstancesChangedListener) error { -// panic("implement me") -//} -// -//func (m *mockServiceDiscovery) DispatchEventByServiceName(string) error { -// panic("implement me") -//} -// -//func (m *mockServiceDiscovery) DispatchEventForInstances(string, []registry.ServiceInstance) error { -// panic("implement me") -//} -// -//func (m *mockServiceDiscovery) DispatchEvent(*registry.ServiceInstancesChangedEvent) error { -// panic("implement me") -//} -// -//func ConvertURLArrToIntfArr(urls []*common.URL) []interface{} { -// if len(urls) == 0 { -// return []interface{}{} -// } -// -// res := make([]interface{}, 0, len(urls)) -// for _, u := range urls { -// res = append(res, u.String()) -// } -// return res -//} -// -//type mockGracefulShutdownFilter struct{} -// -//func (f *mockGracefulShutdownFilter) Invoke(ctx context.Context, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result { -// panic("implement me") -//} -// -//func (f *mockGracefulShutdownFilter) OnResponse(ctx context.Context, result protocol.Result, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result { -// panic("implement me") -//} -// -//func (f *mockGracefulShutdownFilter) Set(name string, config interface{}) { -// return -//} diff --git a/config/consumer_config.go b/config/consumer_config.go index 9f76e4cb40..db34f45fe2 100644 --- a/config/consumer_config.go +++ b/config/consumer_config.go @@ -42,7 +42,7 @@ type ConsumerConfig struct { // ConnectTimeout will be remove in 3.0 config-enhance ConnectTimeout string `default:"3s" yaml:"connect-timeout" json:"connect-timeout,omitempty" property:"connect-timeout"` // support string - Registry []string `yaml:"registry" json:"registry,omitempty" property:"registry"` + RegistryIDs []string `yaml:"registryIDs" json:"registryIDs,omitempty" property:"registryIDs"` RequestTimeout string `default:"3s" yaml:"request-timeout" json:"request-timeout,omitempty" property:"request-timeout"` ProxyFactory string `default:"default" yaml:"proxy" json:"proxy,omitempty" property:"proxy"` @@ -64,9 +64,9 @@ func (cc *ConsumerConfig) Init(rc *RootConfig) error { if cc == nil { return nil } - cc.Registry = translateRegistryIds(cc.Registry) - if len(cc.Registry) <= 0 { - cc.Registry = rc.getRegistryIds() + cc.RegistryIDs = translateRegistryIds(cc.RegistryIDs) + if len(cc.RegistryIDs) <= 0 { + cc.RegistryIDs = rc.getRegistryIds() } for _, reference := range cc.References { if err := reference.Init(rc); err != nil { @@ -135,71 +135,8 @@ func SetConsumerConfig(c ConsumerConfig) { rootConfig.Consumer = &c } -// ConsumerInit loads config file to init consumer config -func ConsumerInit(confConFile string) error { - //if confConFile == "" { - // return perrors.Errorf("applicationConfig configure(consumer) file name is nil") - //} - //consumerConfig = &ShutdownConfig{} - //fileStream, err := yaml.UnmarshalYMLConfig(confConFile, consumerConfig) - //if err != nil { - // return perrors.Errorf("unmarshalYmlConfig error %v", perrors.WithStack(err)) - //} - //consumerConfig.fileStream = bytes.NewBuffer(fileStream) - //// set method interfaceId & interfaceName - //for k, v := range consumerConfig.References { - // // set id for reference - // for _, n := range consumerConfig.References[k].Methods { - // n.InterfaceName = v.InterfaceName - // n.InterfaceId = k - // } - //} - //if consumerConfig.Request_Timeout != "" { - // if consumerConfig.RequestTimeout, err = time.ParseDuration(consumerConfig.Request_Timeout); err != nil { - // return perrors.WithMessagef(err, "time.ParseDuration(Request_Timeout{%#v})", consumerConfig.Request_Timeout) - // } - // if consumerConfig.RequestTimeout >= time.Duration(MaxWheelTimeSpan) { - // return perrors.WithMessagef(err, "request_timeout %s should be less than %s", - // consumerConfig.Request_Timeout, time.Duration(MaxWheelTimeSpan)) - // } - //} - //if consumerConfig.Connect_Timeout != "" { - // if consumerConfig.ConnectTimeout, err = time.ParseDuration(consumerConfig.Connect_Timeout); err != nil { - // return perrors.WithMessagef(err, "time.ParseDuration(Connect_Timeout{%#v})", consumerConfig.Connect_Timeout) - // } - //} - // - //logger.Debugf("consumer config{%#v}\n", consumerConfig) - - return nil -} - -func configCenterRefreshConsumer() error { - //// fresh it - //var err error - //if consumerConfig.Request_Timeout != "" { - // if consumerConfig.RequestTimeout, err = time.ParseDuration(consumerConfig.Request_Timeout); err != nil { - // return perrors.WithMessagef(err, "time.ParseDuration(Request_Timeout{%#v})", consumerConfig.Request_Timeout) - // } - //} - //if consumerConfig.Connect_Timeout != "" { - // if consumerConfig.ConnectTimeout, err = time.ParseDuration(consumerConfig.Connect_Timeout); err != nil { - // return perrors.WithMessagef(err, "time.ParseDuration(Connect_Timeout{%#v})", consumerConfig.Connect_Timeout) - // } - //} - //if consumerConfig.ConfigCenterConfig != nil { - // consumerConfig.SetFatherConfig(consumerConfig) - // if err = consumerConfig.startConfigCenter((*consumerConfig).BaseConfig); err != nil { - // return perrors.Errorf("start config center error , error message is {%v}", perrors.WithStack(err)) - // } - // consumerConfig.fresh() - //} - return nil -} -func NewEmptyConsumerConfig() *ConsumerConfig { - +func newEmptyConsumerConfig() *ConsumerConfig { newConsumerConfig := &ConsumerConfig{ - //Registries: make(map[string]*RegistryConfig, 8), References: make(map[string]*ReferenceConfig, 8), ConnectTimeout: "3s", RequestTimeout: "3s", @@ -208,67 +145,59 @@ func NewEmptyConsumerConfig() *ConsumerConfig { return newConsumerConfig } -// NewConsumerConfig returns ConsumerConfig with @opts -func NewConsumerConfig(opts ...ConsumerConfigOpt) *ConsumerConfig { - newConfig := NewEmptyConsumerConfig() - for _, v := range opts { - v(newConfig) - } - return newConfig +type ConsumerConfigBuilder struct { + consumerConfig *ConsumerConfig } -///////////////////////////////////// consumer config api -// ConsumerConfigOpt is the options to init ConsumerConfig -type ConsumerConfigOpt func(config *ConsumerConfig) *ConsumerConfig +func NewConsumerConfigBuilder() *ConsumerConfigBuilder { + return &ConsumerConfigBuilder{consumerConfig: newEmptyConsumerConfig()} +} -// GetConsumerInstance returns ConsumerConfig with @opts -func GetConsumerInstance(opts ...ConsumerConfigOpt) *ConsumerConfig { - cc := &ConsumerConfig{ - References: make(map[string]*ReferenceConfig, 8), - Check: true, - } - for _, opt := range opts { - opt(cc) - } - return cc +func (ccb *ConsumerConfigBuilder) SetFilter(filter string) *ConsumerConfigBuilder { + ccb.consumerConfig.Filter = filter + return ccb } -// WithRootConfig returns ConsumerConfigOpt with given @rootConfig -func WithRootConfig(rootConfig *RootConfig) ConsumerConfigOpt { - return func(config *ConsumerConfig) *ConsumerConfig { - config.rootConfig = rootConfig - return config - } +func (ccb *ConsumerConfigBuilder) SetRegistryIDs(RegistryIDs ...string) *ConsumerConfigBuilder { + ccb.consumerConfig.RegistryIDs = RegistryIDs + return ccb } -// WithConsumerReferenceConfig returns ConsumerConfigOpt with -func WithConsumerReferenceConfig(referenceKey string, refConfig *ReferenceConfig) ConsumerConfigOpt { - return func(config *ConsumerConfig) *ConsumerConfig { - config.References[referenceKey] = refConfig - return config - } +func (ccb *ConsumerConfigBuilder) SetRequestTimeout(requestTimeout string) *ConsumerConfigBuilder { + ccb.consumerConfig.RequestTimeout = requestTimeout + return ccb } -// WithConsumerConnTimeout returns ConsumerConfigOpt with given consumer conn @timeout -func WithConsumerConnTimeout(timeout string) ConsumerConfigOpt { - return func(config *ConsumerConfig) *ConsumerConfig { - config.ConnectTimeout = timeout - return config - } +func (ccb *ConsumerConfigBuilder) SetProxyFactory(proxyFactory string) *ConsumerConfigBuilder { + ccb.consumerConfig.ProxyFactory = proxyFactory + return ccb } -// WithConsumerRequestTimeout returns ConsumerConfigOpt with given consumer request @timeout -func WithConsumerRequestTimeout(timeout string) ConsumerConfigOpt { - return func(config *ConsumerConfig) *ConsumerConfig { - config.RequestTimeout = timeout - return config - } +func (ccb *ConsumerConfigBuilder) SetCheck(check bool) *ConsumerConfigBuilder { + ccb.consumerConfig.Check = check + return ccb } -// WithConsumerConfigCheck returns ConsumerConfigOpt with given @check flag -func WithConsumerConfigCheck(check bool) ConsumerConfigOpt { - return func(config *ConsumerConfig) *ConsumerConfig { - config.Check = check - return config - } +func (ccb *ConsumerConfigBuilder) AddReference(referenceKey string, referenceConfig *ReferenceConfig) *ConsumerConfigBuilder { + ccb.consumerConfig.References[referenceKey] = referenceConfig + return ccb +} + +func (ccb *ConsumerConfigBuilder) SetReferences(references map[string]*ReferenceConfig) *ConsumerConfigBuilder { + ccb.consumerConfig.References = references + return ccb +} + +func (ccb *ConsumerConfigBuilder) SetFilterConf(filterConf interface{}) *ConsumerConfigBuilder { + ccb.consumerConfig.FilterConf = filterConf + return ccb +} + +func (ccb *ConsumerConfigBuilder) SetRootConfig(rootConfig *RootConfig) *ConsumerConfigBuilder { + ccb.consumerConfig.rootConfig = rootConfig + return ccb +} + +func (ccb *ConsumerConfigBuilder) Build() *ConsumerConfig { + return ccb.consumerConfig } diff --git a/config/dubbo_bootstrap.go b/config/dubbo_bootstrap.go deleted file mode 100644 index 6793e26f1a..0000000000 --- a/config/dubbo_bootstrap.go +++ /dev/null @@ -1,110 +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 config - -import ( - "sync" -) - -import ( - hessian "github.com/apache/dubbo-go-hessian2" -) - -import ( - "dubbo.apache.org/dubbo-go/v3/common" - "dubbo.apache.org/dubbo-go/v3/common/logger" -) - -var ( - startOnce sync.Once -) - -func GetInstance(opts ...RootConfigOpt) *RootConfig { - registerPOJO() - rc := &RootConfig{ - ConfigCenter: GetConfigCenterInstance(), - ServiceDiscoveries: make(map[string]*ServiceDiscoveryConfig), - MetadataReportConfig: &MetadataReportConfig{}, - Application: GetApplicationInstance(), - Registries: make(map[string]*RegistryConfig), - Protocols: GetProtocolsInstance(), - Provider: GetProviderInstance(), - Consumer: GetConsumerInstance(), - MetricConfig: &MetricConfig{}, - Logger: GetLoggerConfigInstance(), - } - for _, opt := range opts { - opt(rc) - } - return rc -} - -func registerPOJO() { - hessian.RegisterPOJO(&common.MetadataInfo{}) - hessian.RegisterPOJO(&common.ServiceInfo{}) - hessian.RegisterPOJO(&common.URL{}) -} - -func (rc *RootConfig) Init() error { - - if err := rc.Logger.Init(); err != nil { - return err - } - if err := rc.ConfigCenter.Init(rc); err != nil { - logger.Warnf("config center doesn't start. error is %s", err) - } - if err := rc.Application.Init(); err != nil { - return err - } - if err := initProtocolsConfig(rc); err != nil { - return err - } - if err := initRegistryConfig(rc); err != nil { - return err - } - if err := initServiceDiscoveryConfig(rc); err != nil { - return err - } - if err := rc.MetadataReportConfig.Init(rc); err != nil { - return err - } - if err := initMetricConfig(rc); err != nil { - return err - } - if err := initRouterConfig(rc); err != nil { - return err - } - // provider、consumer must last init - if err := rc.Provider.Init(rc); err != nil { - return err - } - if err := rc.Consumer.Init(rc); err != nil { - return err - } - - rc.Start() - return nil -} - -func (rc *RootConfig) Start() { - startOnce.Do(func() { - rc.Provider.Load() - rc.Consumer.Load() - registerServiceInstance() - }) -} diff --git a/config/graceful_shutdown_config.go b/config/graceful_shutdown_config.go index 76720a31d2..fdf2376cbe 100644 --- a/config/graceful_shutdown_config.go +++ b/config/graceful_shutdown_config.go @@ -83,3 +83,40 @@ func (config *ShutdownConfig) GetStepTimeout() time.Duration { } return result } + +type ShutdownConfigBuilder struct { + shutdownConfig *ShutdownConfig +} + +func NewShutDownConfigBuilder() *ShutdownConfigBuilder { + return &ShutdownConfigBuilder{shutdownConfig: &ShutdownConfig{}} +} + +func (scb *ShutdownConfigBuilder) SetTimeout(timeout string) *ShutdownConfigBuilder { + scb.shutdownConfig.Timeout = timeout + return scb +} + +func (scb *ShutdownConfigBuilder) SetStepTimeout(stepTimeout string) *ShutdownConfigBuilder { + scb.shutdownConfig.StepTimeout = stepTimeout + return scb +} + +func (scb *ShutdownConfigBuilder) SetRejectRequestHandler(rejectRequestHandler string) *ShutdownConfigBuilder { + scb.shutdownConfig.RejectRequestHandler = rejectRequestHandler + return scb +} + +func (scb *ShutdownConfigBuilder) SetRequestsFinished(requestsFinished bool) *ShutdownConfigBuilder { + scb.shutdownConfig.RequestsFinished = requestsFinished + return scb +} + +func (scb *ShutdownConfigBuilder) SetRejectRequest(rejectRequest bool) *ShutdownConfigBuilder { + scb.shutdownConfig.RejectRequest = rejectRequest + return scb +} + +func (scb *ShutdownConfigBuilder) Build() *ShutdownConfig { + return scb.shutdownConfig +} diff --git a/config/graceful_shutdown_test.go b/config/graceful_shutdown_test.go index 825ba7e27f..5be5d82238 100644 --- a/config/graceful_shutdown_test.go +++ b/config/graceful_shutdown_test.go @@ -63,7 +63,7 @@ package config // // // without configuration // config.consumerConfig = nil -// config.providerConfig = nil +// config.referenceConfig = nil // BeforeShutdown() // // config.consumerConfig = &consumer.ShutdownConfig{ @@ -83,7 +83,7 @@ package config // Name: "mock", // } // -// config.providerConfig = &provider.ProviderConfig{ +// config.referenceConfig = &provider.ProviderConfig{ // ShutdownConfig: &ShutdownConfig{ // Timeout: "1", // StepTimeout: "1s", @@ -93,7 +93,7 @@ package config // // test destroy protocol // BeforeShutdown() // -// config.providerConfig = &provider.ProviderConfig{ +// config.referenceConfig = &provider.ProviderConfig{ // ShutdownConfig: &ShutdownConfig{ // Timeout: "1", // StepTimeout: "-1s", diff --git a/config/logger_config.go b/config/logger_config.go index d829256c65..444bc38d01 100644 --- a/config/logger_config.go +++ b/config/logger_config.go @@ -72,16 +72,7 @@ func (LoggerConfig) Prefix() string { return constant.LoggerConfigPrefix } -func GetLoggerConfigInstance() *LoggerConfig { - lc := &LoggerConfig{} - return lc -} - func (lc *LoggerConfig) Init() error { - - if lc == nil { - lc = GetLoggerConfigInstance() - } err := lc.check() if err != nil { return err @@ -153,3 +144,29 @@ func (lc *LoggerConfig) getUrlMap() url.Values { } return urlMap } + +type LoggerConfigBuilder struct { + loggerConfig *LoggerConfig +} + +// nolint +func NewLoggerConfigBuilder() *LoggerConfigBuilder { + return &LoggerConfigBuilder{loggerConfig: &LoggerConfig{}} +} + +// nolint +func (lcb *LoggerConfigBuilder) SetLumberjackConfig(lumberjackConfig *lumberjack.Logger) *LoggerConfigBuilder { + lcb.loggerConfig.LumberjackConfig = lumberjackConfig + return lcb +} + +// nolint +func (lcb *LoggerConfigBuilder) SetZapConfig(zapConfig ZapConfig) *LoggerConfigBuilder { + lcb.loggerConfig.ZapConfig = zapConfig + return lcb +} + +// nolint +func (lcb *LoggerConfigBuilder) Build() *LoggerConfig { + return lcb.loggerConfig +} diff --git a/config/metadata_report_config.go b/config/metadata_report_config.go index 888edd16ef..22f1fcbb8f 100644 --- a/config/metadata_report_config.go +++ b/config/metadata_report_config.go @@ -65,7 +65,7 @@ func (mc *MetadataReportConfig) ToUrl() (*common.URL, error) { common.WithParamsValue(constant.METADATATYPE_KEY, mc.MetadataType), ) if err != nil || len(res.Protocol) == 0 { - return nil, perrors.New("Invalid MetadataReportConfig.") + return nil, perrors.New("Invalid MetadataReport Config.") } res.SetParam("metadata", res.Protocol) return res, nil @@ -122,3 +122,60 @@ func selectMetadataServiceExportedURL() *common.URL { } return selectedUrl } + +type MetadataReportConfigBuilder struct { + metadataReportConfig *MetadataReportConfig +} + +// nolint +func NewMetadataReportConfigBuilder() *MetadataReportConfigBuilder { + return &MetadataReportConfigBuilder{metadataReportConfig: &MetadataReportConfig{}} +} + +// nolint +func (mrcb *MetadataReportConfigBuilder) SetProtocol(protocol string) *MetadataReportConfigBuilder { + mrcb.metadataReportConfig.Protocol = protocol + return mrcb +} + +// nolint +func (mrcb *MetadataReportConfigBuilder) SetAddress(address string) *MetadataReportConfigBuilder { + mrcb.metadataReportConfig.Address = address + return mrcb +} + +// nolint +func (mrcb *MetadataReportConfigBuilder) SetUsername(username string) *MetadataReportConfigBuilder { + mrcb.metadataReportConfig.Username = username + return mrcb +} + +// nolint +func (mrcb *MetadataReportConfigBuilder) SetPassword(password string) *MetadataReportConfigBuilder { + mrcb.metadataReportConfig.Password = password + return mrcb +} + +// nolint +func (mrcb *MetadataReportConfigBuilder) SetTimeout(timeout string) *MetadataReportConfigBuilder { + mrcb.metadataReportConfig.Timeout = timeout + return mrcb +} + +// nolint +func (mrcb *MetadataReportConfigBuilder) SetGroup(group string) *MetadataReportConfigBuilder { + mrcb.metadataReportConfig.Group = group + return mrcb +} + +// nolint +func (mrcb *MetadataReportConfigBuilder) SetMetadataType(metadataType string) *MetadataReportConfigBuilder { + mrcb.metadataReportConfig.MetadataType = metadataType + return mrcb +} + +// nolint +func (mrcb *MetadataReportConfigBuilder) Build() *MetadataReportConfig { + // TODO Init + return mrcb.metadataReportConfig +} diff --git a/config/metric_config.go b/config/metric_config.go index e6d0a5a171..64f6b2d47f 100644 --- a/config/metric_config.go +++ b/config/metric_config.go @@ -19,17 +19,19 @@ package config var defaultHistogramBucket = []float64{10, 50, 100, 200, 500, 1000, 10000} -// This is the config struct for all metrics implementation +// MetricConfig This is the config struct for all metrics implementation type MetricConfig struct { - Reporters []string `yaml:"reporters" json:"reporters,omitempty"` + Reporters []string `yaml:"reporters" json:"reporters,omitempty"` + // TODO s? HistogramBucket []float64 `yaml:"histogram_bucket" json:"histogram_bucket,omitempty"` } -func initMetricConfig(rc *RootConfig) error { +// nolint +func (mc *MetricConfig) Init() error { return nil } -// find the histogram bucket +// GetHistogramBucket find the histogram bucket // if it's empty, the default value will be return func (mc *MetricConfig) GetHistogramBucket() []float64 { if len(mc.HistogramBucket) == 0 { @@ -37,3 +39,50 @@ func (mc *MetricConfig) GetHistogramBucket() []float64 { } return mc.HistogramBucket } + +type MetricConfigBuilder struct { + metricConfig *MetricConfig +} + +// nolint +func NewMetricConfigBuilder() *MetricConfigBuilder { + return &MetricConfigBuilder{metricConfig: &MetricConfig{}} +} + +// nolint +func (mcb *MetricConfigBuilder) SetReporters(reporters []string) *MetricConfigBuilder { + mcb.metricConfig.Reporters = reporters + return mcb +} + +// nolint +func (mcb *MetricConfigBuilder) AddReporter(reporter string) *MetricConfigBuilder { + if mcb.metricConfig.Reporters == nil { + mcb.metricConfig.Reporters = make([]string, 0) + } + mcb.metricConfig.Reporters = append(mcb.metricConfig.Reporters, reporter) + return mcb +} + +// nolint +func (mcb *MetricConfigBuilder) SetHistogramBucket(histogramBucket []float64) *MetricConfigBuilder { + mcb.metricConfig.HistogramBucket = histogramBucket + return mcb +} + +// nolint +func (mcb *MetricConfigBuilder) AddBucket(bucket float64) *MetricConfigBuilder { + if mcb.metricConfig.HistogramBucket == nil { + mcb.metricConfig.HistogramBucket = make([]float64, 0) + } + mcb.metricConfig.HistogramBucket = append(mcb.metricConfig.HistogramBucket, bucket) + return mcb +} + +// nolint +func (mcb *MetricConfigBuilder) Build() *MetricConfig { + if err := mcb.metricConfig.Init(); err != nil { + panic(err) + } + return mcb.metricConfig +} diff --git a/config/protocol_config.go b/config/protocol_config.go index 0a1a1a9716..8c4f8ecb84 100644 --- a/config/protocol_config.go +++ b/config/protocol_config.go @@ -42,69 +42,41 @@ func GetProtocolsInstance() map[string]*ProtocolConfig { return make(map[string]*ProtocolConfig, 1) } -func initProtocolsConfig(rc *RootConfig) error { - protocols := rc.Protocols - if len(protocols) <= 0 { - protocol := new(ProtocolConfig) - protocols = make(map[string]*ProtocolConfig, 1) - protocols[constant.DUBBO] = protocol - rc.Protocols = protocols - return protocol.check() - } - for _, protocol := range protocols { - if err := protocol.check(); err != nil { - return err - } - } - rc.Protocols = protocols - return nil -} - -func (p *ProtocolConfig) check() error { +func (p *ProtocolConfig) Init() error { if err := defaults.Set(p); err != nil { return err } return verify(p) } -func NewDefaultProtocolConfig() *ProtocolConfig { - return &ProtocolConfig{ - Name: constant.DEFAULT_PROTOCOL, - Port: "20000", - Ip: "127.0.0.1", - } +func NewProtocolConfigBuilder() *ProtocolConfigBuilder { + return &ProtocolConfigBuilder{protocolConfig: &ProtocolConfig{}} } -// NewProtocolConfig returns ProtocolConfig with given @opts -func NewProtocolConfig(opts ...ProtocolConfigOpt) *ProtocolConfig { - newConfig := NewDefaultProtocolConfig() - for _, v := range opts { - v(newConfig) - } - return newConfig +type ProtocolConfigBuilder struct { + protocolConfig *ProtocolConfig } -type ProtocolConfigOpt func(config *ProtocolConfig) *ProtocolConfig +func (pcb *ProtocolConfigBuilder) SetName(name string) *ProtocolConfigBuilder { + pcb.protocolConfig.Name = name + return pcb +} -// WithProtocolIP set ProtocolConfig with given binding @ip -// Deprecated: the param @ip would be used as service lisener binding and would be registered to registry center -func WithProtocolIP(ip string) ProtocolConfigOpt { - return func(config *ProtocolConfig) *ProtocolConfig { - config.Ip = ip - return config - } +func (pcb *ProtocolConfigBuilder) SetIp(ip string) *ProtocolConfigBuilder { + pcb.protocolConfig.Ip = ip + return pcb } -func WithProtocolName(protcolName string) ProtocolConfigOpt { - return func(config *ProtocolConfig) *ProtocolConfig { - config.Name = protcolName - return config - } +func (pcb *ProtocolConfigBuilder) SetPort(port string) *ProtocolConfigBuilder { + pcb.protocolConfig.Port = port + return pcb } -func WithProtocolPort(port string) ProtocolConfigOpt { - return func(config *ProtocolConfig) *ProtocolConfig { - config.Port = port - return config - } +func (pcb *ProtocolConfigBuilder) SetParams(params interface{}) *ProtocolConfigBuilder { + pcb.protocolConfig.Params = params + return pcb +} + +func (pcb *ProtocolConfigBuilder) Build() *ProtocolConfig { + return pcb.protocolConfig } diff --git a/config/provider_config.go b/config/provider_config.go index a77f3f9c19..abd4a2c870 100644 --- a/config/provider_config.go +++ b/config/provider_config.go @@ -35,16 +35,17 @@ type ProviderConfig struct { Filter string `yaml:"filter" json:"filter,omitempty" property:"filter"` // Deprecated Register whether registration is required Register bool `yaml:"register" json:"register" property:"register"` - // Registry registry ids - Registry []string `yaml:"registry" json:"registry" property:"registry"` + // RegistryIDs is registry ids list + RegistryIDs []string `yaml:"registryIDs" json:"registryIDs" property:"registryIDs"` // Services services Services map[string]*ServiceConfig `yaml:"services" json:"services,omitempty" property:"services"` ProxyFactory string `default:"default" yaml:"proxy" json:"proxy,omitempty" property:"proxy"` - FilterConf interface{} `yaml:"filter_conf" json:"filter_conf,omitempty" property:"filter_conf"` - // ShutdownConfig *ShutdownConfig `yaml:"shutdown_conf" json:"shutdown_conf,omitempty" property:"shutdown_conf"` + FilterConf interface{} `yaml:"filter_conf" json:"filter_conf,omitempty" property:"filter_conf"` ConfigType map[string]string `yaml:"config_type" json:"config_type,omitempty" property:"config_type"` + + rootConfig *RootConfig } func (ProviderConfig) Prefix() string { @@ -62,9 +63,9 @@ func (c *ProviderConfig) Init(rc *RootConfig) error { if c == nil { return nil } - c.Registry = translateRegistryIds(c.Registry) - if len(c.Registry) <= 0 { - c.Registry = rc.getRegistryIds() + c.RegistryIDs = translateRegistryIds(c.RegistryIDs) + if len(c.RegistryIDs) <= 0 { + c.RegistryIDs = rc.getRegistryIds() } for _, service := range c.Services { if err := service.Init(rc); err != nil { @@ -93,57 +94,89 @@ func (c *ProviderConfig) Load() { } -// SetProviderConfig sets provider config by @p -func SetProviderConfig(p ProviderConfig) { - rootConfig.Provider = &p -} - -///////////////////////////////////// provider config api -// ProviderConfigOpt is the -type ProviderConfigOpt func(config *ProviderConfig) *ProviderConfig - -// NewEmptyProviderConfig returns ProviderConfig with default ApplicationConfig -func NewEmptyProviderConfig() *ProviderConfig { +// newEmptyProviderConfig returns ProviderConfig with default ApplicationConfig +func newEmptyProviderConfig() *ProviderConfig { newProviderConfig := &ProviderConfig{ - Services: make(map[string]*ServiceConfig), - Registry: make([]string, 8), + Services: make(map[string]*ServiceConfig), + RegistryIDs: make([]string, 8), } return newProviderConfig } -// NewProviderConfig returns ProviderConfig with given @opts -func NewProviderConfig(opts ...ProviderConfigOpt) *ProviderConfig { - newConfig := NewEmptyProviderConfig() - for _, v := range opts { - v(newConfig) - } - return newConfig +type ProviderConfigBuilder struct { + providerConfig *ProviderConfig } -// GetProviderInstance returns ProviderConfig with given @opts -func GetProviderInstance(opts ...ProviderConfigOpt) *ProviderConfig { - newConfig := &ProviderConfig{ - Services: make(map[string]*ServiceConfig), - Registry: make([]string, 8), - } - for _, opt := range opts { - opt(newConfig) - } - return newConfig +func NewProviderConfigBuilder() *ProviderConfigBuilder { + return &ProviderConfigBuilder{providerConfig: newEmptyProviderConfig()} +} + +func (pcb *ProviderConfigBuilder) SetFilter(filter string) *ProviderConfigBuilder { + pcb.providerConfig.Filter = filter + return pcb +} + +// nolint +func (pcb *ProviderConfigBuilder) SetRegister(register bool) *ProviderConfigBuilder { + pcb.providerConfig.Register = register + return pcb +} + +// nolint +func (pcb *ProviderConfigBuilder) SetRegistryIDs(RegistryIDs ...string) *ProviderConfigBuilder { + pcb.providerConfig.RegistryIDs = RegistryIDs + return pcb } -// WithProviderServices returns ProviderConfig with given serviceNameKey @serviceName and @serviceConfig -func WithProviderService(serviceName string, serviceConfig *ServiceConfig) ProviderConfigOpt { - return func(config *ProviderConfig) *ProviderConfig { - config.Services[serviceName] = serviceConfig - return config +// nolint +func (pcb *ProviderConfigBuilder) SetServices(services map[string]*ServiceConfig) *ProviderConfigBuilder { + pcb.providerConfig.Services = services + return pcb +} + +// nolint +func (pcb *ProviderConfigBuilder) AddService(serviceID string, serviceConfig *ServiceConfig) *ProviderConfigBuilder { + if pcb.providerConfig.Services == nil { + pcb.providerConfig.Services = make(map[string]*ServiceConfig) } + pcb.providerConfig.Services[serviceID] = serviceConfig + return pcb +} + +// nolint +func (pcb *ProviderConfigBuilder) SetProxyFactory(proxyFactory string) *ProviderConfigBuilder { + pcb.providerConfig.ProxyFactory = proxyFactory + return pcb +} + +// nolint +func (pcb *ProviderConfigBuilder) SetFilterConf(filterConf interface{}) *ProviderConfigBuilder { + pcb.providerConfig.FilterConf = filterConf + return pcb } -// WithProviderRegistryKeys returns ProviderConfigOpt with given @registryKey and registry @registryConfig -func WithProviderRegistryKeys(registryKey ...string) ProviderConfigOpt { - return func(config *ProviderConfig) *ProviderConfig { - config.Registry = append(config.Registry, registryKey...) - return config +// nolint +func (pcb *ProviderConfigBuilder) SetConfigType(configType map[string]string) *ProviderConfigBuilder { + pcb.providerConfig.ConfigType = configType + return pcb +} + +// nolint +func (pcb *ProviderConfigBuilder) AddConfigType(key, value string) *ProviderConfigBuilder { + if pcb.providerConfig.ConfigType == nil { + pcb.providerConfig.ConfigType = make(map[string]string) } + pcb.providerConfig.ConfigType[key] = value + return pcb +} + +// nolint +func (pcb *ProviderConfigBuilder) SetRootConfig(rootConfig *RootConfig) *ProviderConfigBuilder { + pcb.providerConfig.rootConfig = rootConfig + return pcb +} + +// nolint +func (pcb *ProviderConfigBuilder) Build() *ProviderConfig { + return pcb.providerConfig } diff --git a/config/provider_config_test.go b/config/provider_config_test.go index 27b3c6695c..b418bffe7f 100644 --- a/config/provider_config_test.go +++ b/config/provider_config_test.go @@ -29,8 +29,8 @@ func TestProviderConfigEmptyRegistry(t *testing.T) { err := Load(WithPath("./testdata/config/provider/empty_registry_application.yaml")) assert.Nil(t, err) provider := rootConfig.Provider - assert.Equal(t, 1, len(provider.Registry)) - assert.Equal(t, "nacos", provider.Registry[0]) + assert.Equal(t, 1, len(provider.RegistryIDs)) + assert.Equal(t, "nacos", provider.RegistryIDs[0]) } func TestProviderConfigRootRegistry(t *testing.T) { @@ -40,8 +40,8 @@ func TestProviderConfigRootRegistry(t *testing.T) { assert.NotNil(t, provider) assert.Equal(t, 2, len(provider.Services)) - assert.Equal(t, 2, len(provider.Services["HelloService"].Registry)) - assert.Equal(t, 1, len(provider.Services["OrderService"].Registry)) + assert.Equal(t, 2, len(provider.Services["HelloService"].RegistryIDs)) + assert.Equal(t, 1, len(provider.Services["OrderService"].RegistryIDs)) } // @@ -56,5 +56,5 @@ func TestProviderConfigRootRegistry(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", config.providerConfig.Services["UserProvider"].Protocol) +// assert.Equal(t, "dubbo", config.referenceConfig.Services["UserProvider"].Protocol) //} diff --git a/config/reference_config.go b/config/reference_config.go index 986a39076e..1055e75feb 100644 --- a/config/reference_config.go +++ b/config/reference_config.go @@ -50,7 +50,7 @@ type ReferenceConfig struct { URL string `yaml:"url" json:"url,omitempty" property:"url"` Filter string `yaml:"filter" json:"filter,omitempty" property:"filter"` Protocol string `default:"dubbo" yaml:"protocol" json:"protocol,omitempty" property:"protocol"` - Registry []string `yaml:"registry" json:"registry,omitempty" property:"registry"` + RegistryIDs []string `yaml:"registryIDs" json:"registryIDs,omitempty" property:"registryIDs"` Cluster string `yaml:"cluster" json:"cluster,omitempty" property:"cluster"` Loadbalance string `yaml:"loadbalance" json:"loadbalance,omitempty" property:"loadbalance"` Retries string `yaml:"retries" json:"retries,omitempty" property:"retries"` @@ -90,9 +90,12 @@ func (rc *ReferenceConfig) Init(root *RootConfig) error { if root.Application != nil { rc.metaDataType = root.Application.MetadataType } - rc.Registry = translateRegistryIds(rc.Registry) - if len(rc.Registry) <= 0 { - rc.Registry = root.Consumer.Registry + if rc.Cluster == "" { + rc.Cluster = "failover" + } + rc.RegistryIDs = translateRegistryIds(rc.RegistryIDs) + if len(rc.RegistryIDs) <= 0 { + rc.RegistryIDs = root.Consumer.RegistryIDs } return verify(rc) } @@ -133,7 +136,7 @@ func (rc *ReferenceConfig) Refer(srv interface{}) { } } else { // 2. assemble SubURL from register center's configuration mode - rc.urls = loadRegistries(rc.Registry, rc.rootConfig.Registries, common.CONSUMER) + rc.urls = loadRegistries(rc.RegistryIDs, rc.rootConfig.Registries, common.CONSUMER) // set url to regURLs for _, regURL := range rc.urls { @@ -323,71 +326,56 @@ func (rc *ReferenceConfig) postProcessConfig(url *common.URL) { //////////////////////////////////// reference config api -// ReferenceConfigOpt is consumer's reference config -type ReferenceConfigOpt func(config *ReferenceConfig) *ReferenceConfig - -// NewReferenceConfig The only way to get a new ReferenceConfig -func NewReferenceConfigWithID(id string) *ReferenceConfig { - return &ReferenceConfig{id: id} -} - -// NewEmptyReferenceConfig returns empty ReferenceConfig -func NewEmptyReferenceConfig() *ReferenceConfig { - newReferenceConfig := NewReferenceConfigWithID("") +// newEmptyReferenceConfig returns empty ReferenceConfig +func newEmptyReferenceConfig() *ReferenceConfig { + newReferenceConfig := &ReferenceConfig{} newReferenceConfig.Methods = make([]*MethodConfig, 0, 8) newReferenceConfig.Params = make(map[string]string, 8) return newReferenceConfig } -// NewReferenceConfig returns ReferenceConfig with given @opts -func NewReferenceConfig(opts ...ReferenceConfigOpt) *ReferenceConfig { - newReferenceConfig := NewEmptyReferenceConfig() - for _, v := range opts { - v(newReferenceConfig) - } - return newReferenceConfig +type ReferenceConfigBuilder struct { + referenceConfig *ReferenceConfig } -// WithReferenceRegistry returns ReferenceConfigOpt with given registryKey: @registry -func WithReferenceRegistry(registryKeys ...string) ReferenceConfigOpt { - return func(config *ReferenceConfig) *ReferenceConfig { - config.Registry = registryKeys - return config - } +func NewReferenceConfigBuilder() *ReferenceConfigBuilder { + return &ReferenceConfigBuilder{referenceConfig: newEmptyReferenceConfig()} } -// WithReferenceProtocolName returns ReferenceConfigOpt with given protocolName: @protocol -func WithReferenceProtocolName(protocol string) ReferenceConfigOpt { - return func(config *ReferenceConfig) *ReferenceConfig { - config.Protocol = protocol - return config - } +func (pcb *ReferenceConfigBuilder) SetInterface(interfaceName string) *ReferenceConfigBuilder { + pcb.referenceConfig.InterfaceName = interfaceName + return pcb } -// WithReferenceInterface returns ReferenceConfigOpt with given @interfaceName -func WithReferenceInterface(interfaceName string) ReferenceConfigOpt { - return func(config *ReferenceConfig) *ReferenceConfig { - config.InterfaceName = interfaceName - return config - } +func (pcb *ReferenceConfigBuilder) SetRegistryIDs(registryIDs ...string) *ReferenceConfigBuilder { + pcb.referenceConfig.RegistryIDs = registryIDs + return pcb } -// WithReferenceCluster returns ReferenceConfigOpt with given cluster name: @cluster -func WithReferenceCluster(cluster string) ReferenceConfigOpt { - return func(config *ReferenceConfig) *ReferenceConfig { - config.Cluster = cluster - return config +func (pcb *ReferenceConfigBuilder) SetGeneric(generic bool) *ReferenceConfigBuilder { + if generic { + pcb.referenceConfig.Generic = "true" + } else { + pcb.referenceConfig.Generic = "false" } + return pcb } -// WithReferenceMethod returns ReferenceConfigOpt with given @method, @retries, and load balance: @lb -func WithReferenceMethod(methodName, retries, lb string) ReferenceConfigOpt { - return func(config *ReferenceConfig) *ReferenceConfig { - config.Methods = append(config.Methods, &MethodConfig{ - Name: methodName, - Retries: retries, - LoadBalance: lb, - }) - return config - } +func (pcb *ReferenceConfigBuilder) SetCluster(cluster string) *ReferenceConfigBuilder { + pcb.referenceConfig.Cluster = cluster + return pcb +} + +func (pcb *ReferenceConfigBuilder) SetSerialization(serialization string) *ReferenceConfigBuilder { + pcb.referenceConfig.Serialization = serialization + return pcb +} + +func (pcb *ReferenceConfigBuilder) SetProtocol(protocol string) *ReferenceConfigBuilder { + pcb.referenceConfig.Protocol = protocol + return pcb +} + +func (pcb *ReferenceConfigBuilder) Build() *ReferenceConfig { + return pcb.referenceConfig } diff --git a/config/registry_config.go b/config/registry_config.go index c811eeed9f..51e3539076 100644 --- a/config/registry_config.go +++ b/config/registry_config.go @@ -63,7 +63,7 @@ func (RegistryConfig) Prefix() string { return constant.RegistryConfigPrefix } -func (c *RegistryConfig) check() error { +func (c *RegistryConfig) Init() error { if err := defaults.Set(c); err != nil { return err } @@ -71,18 +71,6 @@ func (c *RegistryConfig) check() error { return verify(c) } -// initRegistryConfig init registry config -func initRegistryConfig(rc *RootConfig) error { - registries := rc.Registries - for key, reg := range registries { - if err := reg.check(); err != nil { - return err - } - registries[key] = reg - } - return nil -} - func (c *RegistryConfig) getUrlMap(roleType common.RoleType) url.Values { urlMap := url.Values{} urlMap.Set(constant.GROUP_KEY, c.Group) @@ -284,3 +272,98 @@ func WithRegistryParams(params map[string]string) RegistryConfigOpt { return config } } + +func NewRegistryConfigBuilder() *RegistryConfigBuilder { + return &RegistryConfigBuilder{ + registryConfig: &RegistryConfig{}, + } +} + +type RegistryConfigBuilder struct { + registryConfig *RegistryConfig +} + +func (rcb *RegistryConfigBuilder) SetProtocol(protocol string) *RegistryConfigBuilder { + rcb.registryConfig.Protocol = protocol + return rcb +} + +func (rcb *RegistryConfigBuilder) SetTimeout(timeout string) *RegistryConfigBuilder { + rcb.registryConfig.Timeout = timeout + return rcb +} + +func (rcb *RegistryConfigBuilder) SetGroup(group string) *RegistryConfigBuilder { + rcb.registryConfig.Group = group + return rcb +} + +func (rcb *RegistryConfigBuilder) SetNamespace(namespace string) *RegistryConfigBuilder { + rcb.registryConfig.Namespace = namespace + return rcb +} + +func (rcb *RegistryConfigBuilder) SetTTL(ttl string) *RegistryConfigBuilder { + rcb.registryConfig.TTL = ttl + return rcb +} + +func (rcb *RegistryConfigBuilder) SetAddress(address string) *RegistryConfigBuilder { + rcb.registryConfig.Address = address + return rcb +} + +func (rcb *RegistryConfigBuilder) SetUsername(username string) *RegistryConfigBuilder { + rcb.registryConfig.Username = username + return rcb +} + +func (rcb *RegistryConfigBuilder) SetPassword(password string) *RegistryConfigBuilder { + rcb.registryConfig.Password = password + return rcb +} + +func (rcb *RegistryConfigBuilder) SetSimplified(simplified bool) *RegistryConfigBuilder { + rcb.registryConfig.Simplified = simplified + return rcb +} + +func (rcb *RegistryConfigBuilder) SetPreferred(preferred bool) *RegistryConfigBuilder { + rcb.registryConfig.Preferred = preferred + return rcb +} + +func (rcb *RegistryConfigBuilder) SetZone(zone string) *RegistryConfigBuilder { + rcb.registryConfig.Zone = zone + return rcb +} + +func (rcb *RegistryConfigBuilder) SetWeight(weight int64) *RegistryConfigBuilder { + rcb.registryConfig.Weight = weight + return rcb +} + +func (rcb *RegistryConfigBuilder) SetParams(params map[string]string) *RegistryConfigBuilder { + rcb.registryConfig.Params = params + return rcb +} + +func (rcb *RegistryConfigBuilder) addParam(key, value string) *RegistryConfigBuilder { + if rcb.registryConfig.Params == nil { + rcb.registryConfig.Params = make(map[string]string) + } + rcb.registryConfig.Params[key] = value + return rcb +} + +func (rcb *RegistryConfigBuilder) SetRegistryType(registryType string) *RegistryConfigBuilder { + rcb.registryConfig.RegistryType = registryType + return rcb +} + +func (rcb *RegistryConfigBuilder) Build() *RegistryConfig { + if err := rcb.registryConfig.Init(); err != nil { + panic(err) + } + return rcb.registryConfig +} diff --git a/config/remote_config.go b/config/remote_config.go index 820f744b0b..444db6ee8e 100644 --- a/config/remote_config.go +++ b/config/remote_config.go @@ -31,17 +31,17 @@ import ( "dubbo.apache.org/dubbo-go/v3/common/constant" ) -// RemoteConfig: usually we need some middleware, including nacos, zookeeper +// RemoteConfig usually we need some middleware, including nacos, zookeeper // this represents an instance of this middleware // so that other module, like config center, registry could reuse the config // but now, only metadata report, metadata service, service discovery use this structure type RemoteConfig struct { - Protocol string `yaml:"protocol" json:"protocol,omitempty" property:"protocol"` - Address string `yaml:"address" json:"address,omitempty" property:"address"` - TimeoutStr string `default:"5s" yaml:"timeout" json:"timeout,omitempty" property:"timeout"` - Username string `yaml:"username" json:"username,omitempty" property:"username"` - Password string `yaml:"password" json:"password,omitempty" property:"password"` - Params map[string]string `yaml:"params" json:"params,omitempty"` + Protocol string `yaml:"protocol" json:"protocol,omitempty" property:"protocol"` + Address string `yaml:"address" json:"address,omitempty" property:"address"` + Timeout string `default:"5s" yaml:"timeout" json:"timeout,omitempty" property:"timeout"` + Username string `yaml:"username" json:"username,omitempty" property:"username"` + Password string `yaml:"password" json:"password,omitempty" property:"password"` + Params map[string]string `yaml:"params" json:"params,omitempty"` } // Prefix dubbo.remote. @@ -49,10 +49,15 @@ func (rc *RemoteConfig) Prefix() string { return constant.RemotePrefix } -// Timeout return timeout duration. +// nolint +func (rc *RemoteConfig) Init() error { + return nil +} + +// GetTimeout return timeout duration. // if the configure is invalid, or missing, the default value 5s will be returned -func (rc *RemoteConfig) Timeout() time.Duration { - if res, err := time.ParseDuration(rc.TimeoutStr); err == nil { +func (rc *RemoteConfig) GetTimeout() time.Duration { + if res, err := time.ParseDuration(rc.Timeout); err == nil { return res } return 5 * time.Second @@ -87,10 +92,63 @@ func (rc *RemoteConfig) getUrlMap() url.Values { urlMap := url.Values{} urlMap.Set(constant.CONFIG_USERNAME_KEY, rc.Username) urlMap.Set(constant.CONFIG_PASSWORD_KEY, rc.Password) - urlMap.Set(constant.CONFIG_TIMEOUT_KEY, rc.TimeoutStr) + urlMap.Set(constant.CONFIG_TIMEOUT_KEY, rc.Timeout) for key, val := range rc.Params { urlMap.Set(key, val) } return urlMap } + +func NewRemoteConfigBuilder() *RemoteConfigBuilder { + return &RemoteConfigBuilder{remoteConfig: &RemoteConfig{}} +} + +type RemoteConfigBuilder struct { + remoteConfig *RemoteConfig +} + +func (rcb *RemoteConfigBuilder) SetProtocol(protocol string) *RemoteConfigBuilder { + rcb.remoteConfig.Protocol = protocol + return rcb +} + +func (rcb *RemoteConfigBuilder) SetAddress(address string) *RemoteConfigBuilder { + rcb.remoteConfig.Address = address + return rcb +} + +func (rcb *RemoteConfigBuilder) SetTimeout(timeout string) *RemoteConfigBuilder { + rcb.remoteConfig.Timeout = timeout + return rcb +} + +func (rcb *RemoteConfigBuilder) SetUsername(username string) *RemoteConfigBuilder { + rcb.remoteConfig.Username = username + return rcb +} + +func (rcb *RemoteConfigBuilder) SetPassword(password string) *RemoteConfigBuilder { + rcb.remoteConfig.Password = password + return rcb +} + +func (rcb *RemoteConfigBuilder) SetParams(params map[string]string) *RemoteConfigBuilder { + rcb.remoteConfig.Params = params + return rcb +} + +func (rcb *RemoteConfigBuilder) AddParam(key, value string) *RemoteConfigBuilder { + if rcb.remoteConfig.Params == nil { + rcb.remoteConfig.Params = make(map[string]string) + } + rcb.remoteConfig.Params[key] = value + return rcb +} + +func (rcb *RemoteConfigBuilder) Build() *RemoteConfig { + if err := rcb.remoteConfig.Init(); err != nil { + panic(err) + } + return rcb.remoteConfig +} diff --git a/config/root_config.go b/config/root_config.go index 36d24b5e7c..21adc42c97 100644 --- a/config/root_config.go +++ b/config/root_config.go @@ -19,10 +19,21 @@ package config import ( _ "net/http/pprof" + "sync" ) import ( + hessian "github.com/apache/dubbo-go-hessian2" +) + +import ( + "dubbo.apache.org/dubbo-go/v3/common" "dubbo.apache.org/dubbo-go/v3/common/constant" + "dubbo.apache.org/dubbo-go/v3/common/logger" +) + +var ( + startOnce sync.Once ) // RootConfig is the root config @@ -38,12 +49,13 @@ type RootConfig struct { // Remotes to be remove in 3.0 config-enhance Remotes map[string]*RemoteConfig `yaml:"remote" json:"remote,omitempty" property:"remote"` + // TODO ConfigCenter and CenterConfig? ConfigCenter *CenterConfig `yaml:"config-center" json:"config-center,omitempty"` // ServiceDiscoveries to be remove in 3.0 config-enhance ServiceDiscoveries map[string]*ServiceDiscoveryConfig `yaml:"service-discovery" json:"service-discovery,omitempty" property:"service-discovery"` - MetadataReportConfig *MetadataReportConfig `yaml:"metadata-report" json:"metadata-report,omitempty" property:"metadata-report"` + MetadataReport *MetadataReportConfig `yaml:"metadata-report" json:"metadata-report,omitempty" property:"metadata-report"` // provider config Provider *ProviderConfig `yaml:"provider" json:"provider" property:"provider"` @@ -51,7 +63,7 @@ type RootConfig struct { // consumer config Consumer *ConsumerConfig `yaml:"consumer" json:"consumer" property:"consumer"` - MetricConfig *MetricConfig `yaml:"metrics" json:"metrics,omitempty" property:"metrics"` + Metric *MetricConfig `yaml:"metrics" json:"metrics,omitempty" property:"metrics"` // Logger log Logger *LoggerConfig `yaml:"logger" json:"logger,omitempty" property:"logger"` @@ -82,110 +94,28 @@ func GetRootConfig() *RootConfig { func GetProviderConfig() *ProviderConfig { if err := check(); err != nil { - return GetProviderInstance() + return NewProviderConfigBuilder().Build() } if rootConfig.Provider != nil { return rootConfig.Provider } - return GetProviderInstance() + return NewProviderConfigBuilder().Build() } func GetConsumerConfig() *ConsumerConfig { if err := check(); err != nil { - return GetConsumerInstance() + return NewConsumerConfigBuilder().Build() } if rootConfig.Consumer != nil { return rootConfig.Consumer } - return GetConsumerInstance() + return NewConsumerConfigBuilder().Build() } func GetApplicationConfig() *ApplicationConfig { return rootConfig.Application } -// GetConfigCenterConfig get config center config -//func GetConfigCenterConfig() (*CenterConfig, error) { -// if err := check(); err != nil { -// return nil, err -// } -// conf := rootConfig.ConfigCenter -// if conf == nil { -// return nil, errors.New("config center config is null") -// } -// if err := defaults.Set(conf); err != nil { -// return nil, err -// } -// conf.translateConfigAddress() -// if err := verify(conf); err != nil { -// return nil, err -// } -// return conf, nil -//} - -// GetRegistriesConfig get registry config default zookeeper registry -//func GetRegistriesConfig() (map[string]*RegistryConfig, error) { -// if err := check(); err != nil { -// return nil, err -// } -// -// if registriesConfig != nil { -// return registriesConfig, nil -// } -// registriesConfig = initRegistriesConfig(rootConfig.Registries) -// for _, reg := range registriesConfig { -// if err := defaults.Set(reg); err != nil { -// return nil, err -// } -// reg.translateRegistryAddress() -// if err := verify(reg); err != nil { -// return nil, err -// } -// } -// -// return registriesConfig, nil -//} - -// GetProtocolsConfig get protocols config default dubbo protocol -//func GetProtocolsConfig() (map[string]*ProtocolConfig, error) { -// if err := check(); err != nil { -// return nil, err -// } -// -// protocols := getProtocolsConfig(rootConfig.Protocols) -// for _, protocol := range protocols { -// if err := defaults.Set(protocol); err != nil { -// return nil, err -// } -// if err := verify(protocol); err != nil { -// return nil, err -// } -// } -// return protocols, nil -//} - -// GetProviderConfig get provider config -//func GetProviderConfig() (*ProviderConfig, error) { -// if err := check(); err != nil { -// return nil, err -// } -// -// if providerConfig != nil { -// return providerConfig, nil -// } -// provider := getProviderConfig(rootConfig.Provider) -// if err := defaults.Set(provider); err != nil { -// return nil, err -// } -// if err := verify(provider); err != nil { -// return nil, err -// } -// -// provider.Services = getRegistryServices(common.PROVIDER, provider.Services, provider.Registry) -// providerConfig = provider -// return provider, nil -//} - // getRegistryIds get registry ids func (rc *RootConfig) getRegistryIds() []string { ids := make([]string, 0) @@ -194,87 +124,197 @@ func (rc *RootConfig) getRegistryIds() []string { } return removeDuplicateElement(ids) } +func registerPOJO() { + hessian.RegisterPOJO(&common.MetadataInfo{}) + hessian.RegisterPOJO(&common.ServiceInfo{}) + hessian.RegisterPOJO(&common.URL{}) +} -// NewRootConfig get root config -func NewRootConfig(opts ...RootConfigOpt) *RootConfig { - newRootConfig := &RootConfig{ - ConfigCenter: &CenterConfig{}, - ServiceDiscoveries: make(map[string]*ServiceDiscoveryConfig), - MetadataReportConfig: &MetadataReportConfig{}, - Application: &ApplicationConfig{}, - Registries: make(map[string]*RegistryConfig), - Protocols: make(map[string]*ProtocolConfig), - Provider: GetProviderInstance(), - Consumer: GetConsumerInstance(), - MetricConfig: &MetricConfig{}, +func (rc *RootConfig) Init() error { + registerPOJO() + if err := rc.Logger.Init(); err != nil { + return err } - for _, o := range opts { - o(newRootConfig) + if err := rc.ConfigCenter.Init(rc); err != nil { + logger.Warnf("config center doesn't start. error is %s", err) + } + if err := rc.Application.Init(); err != nil { + return err } - return newRootConfig -} -type RootConfigOpt func(config *RootConfig) + // init protocol + protocols := rc.Protocols + if len(protocols) <= 0 { + protocol := &ProtocolConfig{} + protocols = make(map[string]*ProtocolConfig, 1) + protocols[constant.DUBBO] = protocol + rc.Protocols = protocols + } + for _, protocol := range protocols { + if err := protocol.Init(); err != nil { + return err + } + } -// WithMetricsConfig set root config with given @metricsConfig -func WithMetricsConfig(metricsConfig *MetricConfig) RootConfigOpt { - return func(rc *RootConfig) { - rc.MetricConfig = metricsConfig + // init registry + registries := rc.Registries + if registries != nil { + for _, reg := range registries { + if err := reg.Init(); err != nil { + return err + } + } } -} -// WithRootConsumerConfig set root config with given @consumerConfig -func WithRootConsumerConfig(consumerConfig *ConsumerConfig) RootConfigOpt { - return func(rc *RootConfig) { - rc.Consumer = consumerConfig + // init serviceDiscoveries + serviceDiscoveries := rc.ServiceDiscoveries + if serviceDiscoveries != nil { + for _, sd := range serviceDiscoveries { + if err := sd.Init(); err != nil { + return err + } + } } -} -// WithRootProviderConfig set root config with given @providerConfig -func WithRootProviderConfig(providerConfig *ProviderConfig) RootConfigOpt { - return func(rc *RootConfig) { - rc.Provider = providerConfig + if err := rc.MetadataReport.Init(rc); err != nil { + return err } + if err := rc.Metric.Init(); err != nil { + return err + } + if err := initRouterConfig(rc); err != nil { + return err + } + // provider、consumer must last init + if err := rc.Provider.Init(rc); err != nil { + return err + } + if err := rc.Consumer.Init(rc); err != nil { + return err + } + + rc.Start() + return nil } -// WithRootProtocolConfig set root config with key @protocolName and given @protocolConfig -func WithRootProtocolConfig(protocolName string, protocolConfig *ProtocolConfig) RootConfigOpt { - return func(rc *RootConfig) { - rc.Protocols[protocolName] = protocolConfig - } +func (rc *RootConfig) Start() { + startOnce.Do(func() { + rc.Provider.Load() + rc.Consumer.Load() + registerServiceInstance() + }) } -// WithRootRegistryConfig set root config with key @registryKey and given @regConfig -func WithRootRegistryConfig(registryKey string, regConfig *RegistryConfig) RootConfigOpt { - return func(rc *RootConfig) { - rc.Registries[registryKey] = regConfig +// newEmptyRootConfig get empty root config +func newEmptyRootConfig() *RootConfig { + newRootConfig := &RootConfig{ + ConfigCenter: NewConfigCenterConfigBuilder().Build(), + ServiceDiscoveries: make(map[string]*ServiceDiscoveryConfig), + MetadataReport: NewMetadataReportConfigBuilder().Build(), + Application: NewApplicationConfigBuilder().Build(), + Registries: make(map[string]*RegistryConfig), + Protocols: make(map[string]*ProtocolConfig), + Provider: NewProviderConfigBuilder().Build(), + Consumer: NewConsumerConfigBuilder().Build(), + Metric: NewMetricConfigBuilder().Build(), + Logger: NewLoggerConfigBuilder().Build(), } + return newRootConfig } -// WithRootApplicationConfig set root config with given @appConfig -func WithRootApplicationConfig(appConfig *ApplicationConfig) RootConfigOpt { - return func(rc *RootConfig) { - rc.Application = appConfig - } +func NewRootConfigBuilder() *RootConfigBuilder { + return &RootConfigBuilder{rootConfig: newEmptyRootConfig()} } -// WithRootMetadataReportConfig set root config with given @metadataReportConfig -func WithRootMetadataReportConfig(metadataReportConfig *MetadataReportConfig) RootConfigOpt { - return func(rc *RootConfig) { - rc.MetadataReportConfig = metadataReportConfig - } +type RootConfigBuilder struct { + rootConfig *RootConfig } -// WithRootServiceDiscoverConfig set root config with given @serviceDiscConfig and key @name -func WithRootServiceDiscoverConfig(name string, serviceDiscConfig *ServiceDiscoveryConfig) RootConfigOpt { - return func(rc *RootConfig) { - rc.ServiceDiscoveries[name] = serviceDiscConfig - } +func (rb *RootConfigBuilder) SetApplication(application *ApplicationConfig) *RootConfigBuilder { + rb.rootConfig.Application = application + return rb } -// WithRootCenterConfig set root config with given centerConfig -func WithRootCenterConfig(centerConfig *CenterConfig) RootConfigOpt { - return func(rc *RootConfig) { - rc.ConfigCenter = centerConfig - } +func (rb *RootConfigBuilder) AddProtocol(protocolID string, protocolConfig *ProtocolConfig) *RootConfigBuilder { + rb.rootConfig.Protocols[protocolID] = protocolConfig + return rb +} + +func (rb *RootConfigBuilder) AddRegistry(registryID string, registryConfig *RegistryConfig) *RootConfigBuilder { + rb.rootConfig.Registries[registryID] = registryConfig + return rb +} + +func (rb *RootConfigBuilder) SetProtocols(protocols map[string]*ProtocolConfig) *RootConfigBuilder { + rb.rootConfig.Protocols = protocols + return rb +} + +func (rb *RootConfigBuilder) SetRegistries(registries map[string]*RegistryConfig) *RootConfigBuilder { + rb.rootConfig.Registries = registries + return rb +} + +func (rb *RootConfigBuilder) SetRemotes(remotes map[string]*RemoteConfig) *RootConfigBuilder { + rb.rootConfig.Remotes = remotes + return rb +} + +func (rb *RootConfigBuilder) SetServiceDiscoveries(serviceDiscoveries map[string]*ServiceDiscoveryConfig) *RootConfigBuilder { + rb.rootConfig.ServiceDiscoveries = serviceDiscoveries + return rb +} + +func (rb *RootConfigBuilder) SetMetadataReport(metadataReport *MetadataReportConfig) *RootConfigBuilder { + rb.rootConfig.MetadataReport = metadataReport + return rb +} + +func (rb *RootConfigBuilder) SetProvider(provider *ProviderConfig) *RootConfigBuilder { + rb.rootConfig.Provider = provider + return rb +} + +func (rb *RootConfigBuilder) SetConsumer(consumer *ConsumerConfig) *RootConfigBuilder { + rb.rootConfig.Consumer = consumer + return rb +} + +func (rb *RootConfigBuilder) SetMetric(metric *MetricConfig) *RootConfigBuilder { + rb.rootConfig.Metric = metric + return rb +} + +func (rb *RootConfigBuilder) SetLogger(logger *LoggerConfig) *RootConfigBuilder { + rb.rootConfig.Logger = logger + return rb +} + +func (rb *RootConfigBuilder) SetShutdown(shutdown *ShutdownConfig) *RootConfigBuilder { + rb.rootConfig.Shutdown = shutdown + return rb +} + +func (rb *RootConfigBuilder) SetRouter(router []*RouterConfig) *RootConfigBuilder { + rb.rootConfig.Router = router + return rb +} + +func (rb *RootConfigBuilder) SetEventDispatcherType(eventDispatcherType string) *RootConfigBuilder { + rb.rootConfig.EventDispatcherType = eventDispatcherType + return rb +} + +func (rb *RootConfigBuilder) SetCacheFile(cacheFile string) *RootConfigBuilder { + rb.rootConfig.CacheFile = cacheFile + return rb +} + +func (rb *RootConfigBuilder) SetConfigCenter(configCenterConfig *CenterConfig) *RootConfigBuilder { + rb.rootConfig.ConfigCenter = configCenterConfig + return rb +} + +func (rb *RootConfigBuilder) Build() *RootConfig { + return rb.rootConfig } diff --git a/config/router_config.go b/config/router_config.go index 28cf7a0864..854fa8e8ce 100644 --- a/config/router_config.go +++ b/config/router_config.go @@ -51,7 +51,7 @@ func (RouterConfig) Prefix() string { return constant.RouterConfigPrefix } -func (c *RouterConfig) check() error { +func (c *RouterConfig) Init() error { if err := defaults.Set(c); err != nil { return err } @@ -62,7 +62,7 @@ func initRouterConfig(rc *RootConfig) error { routers := rc.Router if len(routers) > 0 { for _, r := range routers { - if err := r.check(); err != nil { + if err := r.Init(); err != nil { return err } } @@ -91,3 +91,92 @@ func initRouterConfig(rc *RootConfig) error { // chain.SetVSAndDRConfigByte(vsBytes, drBytes) // return nil //} + +type RouterConfigBuilder struct { + routerConfig *RouterConfig +} + +// nolint +func NewRouterConfigBuilder() *RouterConfigBuilder { + return &RouterConfigBuilder{routerConfig: &RouterConfig{}} +} + +// nolint +func (rcb *RouterConfigBuilder) SetScope(scope string) *RouterConfigBuilder { + rcb.routerConfig.Scope = scope + return rcb +} + +// nolint +func (rcb *RouterConfigBuilder) SetKey(key string) *RouterConfigBuilder { + rcb.routerConfig.Key = key + return rcb +} + +// nolint +func (rcb *RouterConfigBuilder) SetForce(force bool) *RouterConfigBuilder { + rcb.routerConfig.Force = force + return rcb +} + +// nolint +func (rcb *RouterConfigBuilder) SetRuntime(runtime bool) *RouterConfigBuilder { + rcb.routerConfig.Runtime = runtime + return rcb +} + +// nolint +func (rcb *RouterConfigBuilder) SetEnable(enable bool) *RouterConfigBuilder { + rcb.routerConfig.Enable = enable + return rcb +} + +// nolint +func (rcb *RouterConfigBuilder) SetValid(valid bool) *RouterConfigBuilder { + rcb.routerConfig.Valid = valid + return rcb +} + +// nolint +func (rcb *RouterConfigBuilder) SetPriority(priority int) *RouterConfigBuilder { + rcb.routerConfig.Priority = priority + return rcb +} + +// nolint +func (rcb *RouterConfigBuilder) SetConditions(conditions []string) *RouterConfigBuilder { + rcb.routerConfig.Conditions = conditions + return rcb +} + +// nolint +func (rcb *RouterConfigBuilder) AddCondition(condition string) *RouterConfigBuilder { + if rcb.routerConfig.Conditions == nil { + rcb.routerConfig.Conditions = make([]string, 0) + } + rcb.routerConfig.Conditions = append(rcb.routerConfig.Conditions, condition) + return rcb +} + +// nolint +func (rcb *RouterConfigBuilder) SetTags(tags []Tag) *RouterConfigBuilder { + rcb.routerConfig.Tags = tags + return rcb +} + +// nolint +func (rcb *RouterConfigBuilder) AddTag(tag Tag) *RouterConfigBuilder { + if rcb.routerConfig.Tags == nil { + rcb.routerConfig.Tags = make([]Tag, 0) + } + rcb.routerConfig.Tags = append(rcb.routerConfig.Tags, tag) + return rcb +} + +// nolint +func (rcb *RouterConfigBuilder) Build() *RouterConfig { + if err := rcb.routerConfig.Init(); err != nil { + panic(err) + } + return rcb.routerConfig +} diff --git a/config/service_config.go b/config/service_config.go index 53dce7ac3a..bb13e4b2f0 100644 --- a/config/service_config.go +++ b/config/service_config.go @@ -50,9 +50,9 @@ import ( type ServiceConfig struct { id string Filter string `yaml:"filter" json:"filter,omitempty" property:"filter"` - Protocol []string `default:"[\"dubbo\"]" validate:"required" yaml:"protocol" json:"protocol,omitempty" property:"protocol"` // multi protocol support, split by ',' + ProtocolIDs []string `default:"[\"dubbo\"]" validate:"required" yaml:"protocolIDs" json:"protocolIDs,omitempty" property:"protocolIDs"` // multi protocolIDs support, split by ',' Interface string `validate:"required" yaml:"interface" json:"interface,omitempty" property:"interface"` - Registry []string `yaml:"registry" json:"registry,omitempty" property:"registry"` + RegistryIDs []string `yaml:"registryIDs" json:"registryIDs,omitempty" property:"registryIDs"` Cluster string `default:"failover" yaml:"cluster" json:"cluster,omitempty" property:"cluster"` Loadbalance string `default:"random" yaml:"loadbalance" json:"loadbalance,omitempty" property:"loadbalance"` Group string `yaml:"group" json:"group,omitempty" property:"group"` @@ -76,8 +76,8 @@ type ServiceConfig struct { Tag string `yaml:"tag" json:"tag,omitempty" property:"tag"` GrpcMaxMessageSize int `default:"4" yaml:"max_message_size" json:"max_message_size,omitempty"` - Protocols map[string]*ProtocolConfig - Registries map[string]*RegistryConfig + RCProtocolsMap map[string]*ProtocolConfig + RCRegistriesMap map[string]*RegistryConfig ProxyFactoryKey string unexported *atomic.Bool exported *atomic.Bool @@ -106,14 +106,14 @@ func (svc *ServiceConfig) Init(rc *RootConfig) error { svc.exported = atomic.NewBool(false) svc.metadataType = rc.Application.MetadataType svc.unexported = atomic.NewBool(false) - svc.Registries = rc.Registries - svc.Protocols = rc.Protocols + svc.RCRegistriesMap = rc.Registries + svc.RCProtocolsMap = rc.Protocols if rc.Provider != nil { svc.ProxyFactoryKey = rc.Provider.ProxyFactory } - svc.Registry = translateRegistryIds(svc.Registry) - if len(svc.Registry) <= 0 { - svc.Registry = rc.Provider.Registry + svc.RegistryIDs = translateRegistryIds(svc.RegistryIDs) + if len(svc.RegistryIDs) <= 0 { + svc.RegistryIDs = rc.Provider.RegistryIDs } svc.export = true return verify(svc) @@ -160,11 +160,11 @@ func (svc *ServiceConfig) Export() error { return nil } - regUrls := loadRegistries(svc.Registry, svc.Registries, common.PROVIDER) + regUrls := loadRegistries(svc.RegistryIDs, svc.RCRegistriesMap, common.PROVIDER) urlMap := svc.getUrlMap() - protocolConfigs := loadProtocol(svc.Protocol, svc.Protocols) + protocolConfigs := loadProtocol(svc.ProtocolIDs, svc.RCProtocolsMap) if len(protocolConfigs) == 0 { - logger.Warnf("The service %v's '%v' protocols don't has right protocolConfigs, Please check your configuration center and transfer protocol ", svc.Interface, svc.Protocol) + logger.Warnf("The service %v's '%v' protocols don't has right protocolConfigs, Please check your configuration center and transfer protocol ", svc.Interface, svc.ProtocolIDs) return nil } @@ -410,7 +410,7 @@ func (svc *ServiceConfig) GetExportedUrls() []*common.URL { } func (svc *ServiceConfig) publishServiceDefinition(url *common.URL) { - //svc.rootConfig.MetadataReportConfig. + //svc.rootConfig.MetadataReport. if remoteMetadataService, err := extension.GetRemoteMetadataService(); err == nil && remoteMetadataService != nil { remoteMetadataService.PublishServiceDefinition(url) } @@ -423,145 +423,102 @@ func (svc *ServiceConfig) postProcessConfig(url *common.URL) { } } -// ServiceConfigOpt is the option to init ServiceConfig -type ServiceConfigOpt func(config *ServiceConfig) *ServiceConfig - -// NewDefaultServiceConfig returns default ServiceConfig -func NewDefaultServiceConfig() *ServiceConfig { +// newEmptyServiceConfig returns default ServiceConfig +func newEmptyServiceConfig() *ServiceConfig { newServiceConfig := &ServiceConfig{ - unexported: atomic.NewBool(false), - exported: atomic.NewBool(false), - export: true, - Protocols: make(map[string]*ProtocolConfig), - Registries: make(map[string]*RegistryConfig), + unexported: atomic.NewBool(false), + exported: atomic.NewBool(false), + export: true, + RCProtocolsMap: make(map[string]*ProtocolConfig), + RCRegistriesMap: make(map[string]*RegistryConfig), } newServiceConfig.Params = make(map[string]string) newServiceConfig.Methods = make([]*MethodConfig, 0, 8) return newServiceConfig } -// NewServiceConfig returns ServiceConfig with given @opts -func NewServiceConfig(opts ...ServiceConfigOpt) *ServiceConfig { - defaultServiceConfig := NewDefaultServiceConfig() - for _, v := range opts { - v(defaultServiceConfig) - } - return defaultServiceConfig +type ServiceConfigBuilder struct { + serviceConfig *ServiceConfig } -// WithServiceRegistry returns ServiceConfigOpt with given registryKey @registry -func WithServiceRegistry(registry string) ServiceConfigOpt { - return func(config *ServiceConfig) *ServiceConfig { - config.Registry = append(config.Registry, registry) - return config - } +func NewServiceConfigBuilder() *ServiceConfigBuilder { + return &ServiceConfigBuilder{serviceConfig: newEmptyServiceConfig()} } -// WithServiceProtocolKeys returns ServiceConfigOpt with given protocolKey @protocol -func WithServiceProtocolKeys(protocolKeys ...string) ServiceConfigOpt { - return func(config *ServiceConfig) *ServiceConfig { - config.Protocol = protocolKeys - return config - } +func (pcb *ServiceConfigBuilder) SetRegistryIDs(registryIDs ...string) *ServiceConfigBuilder { + pcb.serviceConfig.RegistryIDs = registryIDs + return pcb } -// WithServiceInterface returns ServiceConfigOpt with given @interfaceName -func WithServiceInterface(interfaceName string) ServiceConfigOpt { - return func(config *ServiceConfig) *ServiceConfig { - config.Interface = interfaceName - return config - } +func (pcb *ServiceConfigBuilder) SetProtocolIDs(protocolIDs ...string) *ServiceConfigBuilder { + pcb.serviceConfig.ProtocolIDs = protocolIDs + return pcb } -// WithServiceMetadataType returns ServiceConfigOpt with given @metadataType -func WithServiceMetadataType(metadataType string) ServiceConfigOpt { - return func(config *ServiceConfig) *ServiceConfig { - config.metadataType = metadataType - return config - } +func (pcb *ServiceConfigBuilder) SetInterface(interfaceName string) *ServiceConfigBuilder { + pcb.serviceConfig.Interface = interfaceName + return pcb } -// WithServiceLoadBalance returns ServiceConfigOpt with given load balance @lb -func WithServiceLoadBalance(lb string) ServiceConfigOpt { - return func(config *ServiceConfig) *ServiceConfig { - config.Loadbalance = lb - return config - } +func (pcb *ServiceConfigBuilder) SetMetadataType(setMetadataType string) *ServiceConfigBuilder { + pcb.serviceConfig.metadataType = setMetadataType + return pcb } -// WithServiceWarmUpTime returns ServiceConfigOpt with given @warmUp time -func WithServiceWarmUpTime(warmUp string) ServiceConfigOpt { - return func(config *ServiceConfig) *ServiceConfig { - config.Warmup = warmUp - return config - } +func (pcb *ServiceConfigBuilder) SetLoadBalancce(lb string) *ServiceConfigBuilder { + pcb.serviceConfig.Loadbalance = lb + return pcb } -// WithServiceCluster returns ServiceConfigOpt with given cluster name @cluster -func WithServiceCluster(cluster string) ServiceConfigOpt { - return func(config *ServiceConfig) *ServiceConfig { - config.Cluster = cluster - return config - } +func (pcb *ServiceConfigBuilder) SetWarmUpTie(warmUp string) *ServiceConfigBuilder { + pcb.serviceConfig.Warmup = warmUp + return pcb } -// WithServiceMethod returns ServiceConfigOpt with given @name, @retries and load balance @lb -func WithServiceMethod(name, retries, lb string) ServiceConfigOpt { - return func(config *ServiceConfig) *ServiceConfig { - config.Methods = append(config.Methods, &MethodConfig{ - Name: name, - Retries: retries, - LoadBalance: lb, - }) - return config - } +func (pcb *ServiceConfigBuilder) SetCluster(cluster string) *ServiceConfigBuilder { + pcb.serviceConfig.Cluster = cluster + return pcb } -func WithServiceProtocol(protocolName string, protocolConfig *ProtocolConfig) ServiceConfigOpt { - return func(config *ServiceConfig) *ServiceConfig { - config.Protocols[protocolName] = protocolConfig - return config - } +func (pcb *ServiceConfigBuilder) AddRCProtocol(protocolName string, protocolConfig *ProtocolConfig) *ServiceConfigBuilder { + pcb.serviceConfig.RCProtocolsMap[protocolName] = protocolConfig + return pcb } -func WithServiceRegistries(registryName string, registryConfig *RegistryConfig) ServiceConfigOpt { - return func(config *ServiceConfig) *ServiceConfig { - config.Registries[registryName] = registryConfig - return config - } +func (pcb *ServiceConfigBuilder) AddRCRegistry(registryName string, registryConfig *RegistryConfig) *ServiceConfigBuilder { + pcb.serviceConfig.RCRegistriesMap[registryName] = registryConfig + return pcb } -func WithServiceGroup(group string) ServiceConfigOpt { - return func(config *ServiceConfig) *ServiceConfig { - config.Group = group - return config - } +func (pcb *ServiceConfigBuilder) SetGroup(group string) *ServiceConfigBuilder { + pcb.serviceConfig.Group = group + return pcb +} +func (pcb *ServiceConfigBuilder) SetVersion(version string) *ServiceConfigBuilder { + pcb.serviceConfig.Version = version + return pcb } -func WithServiceVersion(version string) ServiceConfigOpt { - return func(config *ServiceConfig) *ServiceConfig { - config.Version = version - return config - } +func (pcb *ServiceConfigBuilder) SetProxyFactoryKey(proxyFactoryKey string) *ServiceConfigBuilder { + pcb.serviceConfig.ProxyFactoryKey = proxyFactoryKey + return pcb } -func WithProxyFactoryKey(proxyFactoryKey string) ServiceConfigOpt { - return func(config *ServiceConfig) *ServiceConfig { - config.ProxyFactoryKey = proxyFactoryKey - return config - } +func (pcb *ServiceConfigBuilder) SetRPCService(service common.RPCService) *ServiceConfigBuilder { + pcb.serviceConfig.rpcService = service + return pcb } -func WithRPCService(service common.RPCService) ServiceConfigOpt { - return func(config *ServiceConfig) *ServiceConfig { - config.rpcService = service - return config - } +func (pcb *ServiceConfigBuilder) SetSerialization(serialization string) *ServiceConfigBuilder { + pcb.serviceConfig.Serialization = serialization + return pcb } -func WithServiceID(id string) ServiceConfigOpt { - return func(config *ServiceConfig) *ServiceConfig { - config.id = id - return config - } +func (pcb *ServiceConfigBuilder) SetServiceID(id string) *ServiceConfigBuilder { + pcb.serviceConfig.id = id + return pcb +} + +func (pcb *ServiceConfigBuilder) Build() *ServiceConfig { + return pcb.serviceConfig } diff --git a/config/service_discovery_config.go b/config/service_discovery_config.go index 2ba2bde0bc..d93aea57f0 100644 --- a/config/service_discovery_config.go +++ b/config/service_discovery_config.go @@ -37,6 +37,38 @@ func (ServiceDiscoveryConfig) Prefix() string { return constant.ServiceDiscPrefix } -func initServiceDiscoveryConfig(rc *RootConfig) error { +func (ServiceDiscoveryConfig) Init() error { return nil } + +func NewServiceDiscoveryConfigBuilder() *ServiceDiscoveryConfigBuilder { + return &ServiceDiscoveryConfigBuilder{ + serviceDiscoveryConfig: &ServiceDiscoveryConfig{}, + } +} + +type ServiceDiscoveryConfigBuilder struct { + serviceDiscoveryConfig *ServiceDiscoveryConfig +} + +func (sdcb *ServiceDiscoveryConfigBuilder) SetProtocol(protocol string) *ServiceDiscoveryConfigBuilder { + sdcb.serviceDiscoveryConfig.Protocol = protocol + return sdcb +} + +func (sdcb *ServiceDiscoveryConfigBuilder) SetGroup(group string) *ServiceDiscoveryConfigBuilder { + sdcb.serviceDiscoveryConfig.Group = group + return sdcb +} + +func (sdcb *ServiceDiscoveryConfigBuilder) SetRemoteRef(remoteRef string) *ServiceDiscoveryConfigBuilder { + sdcb.serviceDiscoveryConfig.RemoteRef = remoteRef + return sdcb +} + +func (sdcb *ServiceDiscoveryConfigBuilder) Build() *ServiceDiscoveryConfig { + if err := sdcb.serviceDiscoveryConfig.Init(); err != nil { + panic(err) + } + return sdcb.serviceDiscoveryConfig +} diff --git a/config/testdata/application.yaml b/config/testdata/application.yaml index f0876a125d..e0ee9a27f8 100644 --- a/config/testdata/application.yaml +++ b/config/testdata/application.yaml @@ -26,10 +26,10 @@ dubbo: services: helloService: interface: org.dubbo.service.HelloService - registry: nacos,zk + registryIDs: nacos,zk orderService: interface: org.dubbo.service.OrderService - registry: nacos + registryIDs: nacos provider: register: true services: \ No newline at end of file diff --git a/config/testdata/config/app/application.yaml b/config/testdata/config/app/application.yaml index 4cd30cc61e..336a0badb0 100644 --- a/config/testdata/config/app/application.yaml +++ b/config/testdata/config/app/application.yaml @@ -14,7 +14,7 @@ dubbo: interface: org.github.dubbo.HelloService # must be compatible with grpc or dubbo-java provider: register: true - registry: nacos + registryIDs: nacos services: helloService: protocol: dubbo diff --git a/config/testdata/config/provider/application.yaml b/config/testdata/config/provider/application.yaml index 8816257a05..a30a8d3b2d 100644 --- a/config/testdata/config/provider/application.yaml +++ b/config/testdata/config/provider/application.yaml @@ -6,12 +6,12 @@ dubbo: address: nacos://127.0.0.1:8848 provider: register: true - registry: + registryIDs: - nacos - zk services: helloService: interface: org.dubbo.service.HelloService - registry: nacos,zk + registryIDs: nacos,zk orderService: interface: org.dubbo.service.OrderService \ No newline at end of file diff --git a/config/testdata/config/provider/registry_application.yaml b/config/testdata/config/provider/registry_application.yaml index dd08a0d4fd..98190567a0 100644 --- a/config/testdata/config/provider/registry_application.yaml +++ b/config/testdata/config/provider/registry_application.yaml @@ -4,10 +4,10 @@ dubbo: timeout: 3s address: naocs://127.0.0.1:8848 provider: - registry: nacos + registryIDs: nacos services: HelloService: interface: org.dubbo.service.HelloService - registry: nacos,zk + registryIDs: nacos,zk OrderService: interface: org.dubbo.service.OrderService \ No newline at end of file diff --git a/config/testdata/consumer_config.yml b/config/testdata/consumer_config.yml index c011c9e40b..a9849eaf6a 100644 --- a/config/testdata/consumer_config.yml +++ b/config/testdata/consumer_config.yml @@ -33,7 +33,7 @@ registries : references: "UserProvider": - registry: "hangzhouzk,shanghaizk" + registryIDs: "hangzhouzk,shanghaizk" filter: "" protocol : "dubbo" version: "1.0" diff --git a/config/testdata/consumer_config_with_configcenter.yml b/config/testdata/consumer_config_with_configcenter.yml index fe979dacd4..f5a617a3f0 100644 --- a/config/testdata/consumer_config_with_configcenter.yml +++ b/config/testdata/consumer_config_with_configcenter.yml @@ -7,7 +7,7 @@ config_center: address: "127.0.0.1" references: "UserProvider": - registry: "hangzhouzk,shanghaizk" + registryIDs: "hangzhouzk,shanghaizk" filter: "" protocol : "dubbo" interface : "com.ikurento.user.UserProvider" diff --git a/config/testdata/consumer_config_withoutProtocol.yml b/config/testdata/consumer_config_withoutProtocol.yml index 6028a48db4..c5d399ea6b 100644 --- a/config/testdata/consumer_config_withoutProtocol.yml +++ b/config/testdata/consumer_config_withoutProtocol.yml @@ -33,7 +33,7 @@ registries : references: "UserProvider": - registry: "hangzhouzk,shanghaizk" + registryIDs: "hangzhouzk,shanghaizk" filter: "" version: "1.0" group: "as" diff --git a/config/testdata/provider_config.yml b/config/testdata/provider_config.yml index 3c081c0168..92689e6129 100644 --- a/config/testdata/provider_config.yml +++ b/config/testdata/provider_config.yml @@ -27,7 +27,7 @@ registries : services: "UserProvider": - registry: "hangzhouzk,shanghaizk" + registryIDs: "hangzhouzk,shanghaizk" filter: "" # the name of limiter tps.limiter: "default" diff --git a/config/testdata/provider_config_withoutProtocol.yml b/config/testdata/provider_config_withoutProtocol.yml index 651c2f4c6a..b2adb32e40 100644 --- a/config/testdata/provider_config_withoutProtocol.yml +++ b/config/testdata/provider_config_withoutProtocol.yml @@ -27,7 +27,7 @@ registries : services: "UserProvider": - registry: "hangzhouzk,shanghaizk" + registryIDs: "hangzhouzk,shanghaizk" filter: "" # equivalent to interface of dubbo.xml interface : "com.ikurento.user.UserProvider" diff --git a/go.mod b/go.mod index 4d2a899219..ea4b536592 100644 --- a/go.mod +++ b/go.mod @@ -35,7 +35,7 @@ require ( github.com/pkg/errors v0.9.1 github.com/prometheus/client_golang v1.11.0 github.com/prometheus/common v0.28.0 // indirect - github.com/satori/go.uuid v1.2.0 + github.com/satori/go.uuid v1.2.1-0.20181028125025-b2ce2384e17b github.com/stretchr/testify v1.7.0 github.com/zouyx/agollo/v3 v3.4.5 go.etcd.io/etcd/api/v3 v3.5.0 diff --git a/go.sum b/go.sum index 3f0db58753..75e5d2af51 100644 --- a/go.sum +++ b/go.sum @@ -181,8 +181,6 @@ github.com/dubbogo/gost v1.11.16/go.mod h1:vIcP9rqz2KsXHPjsAwIUtfJIJjppQLQDcYaZT github.com/dubbogo/jsonparser v1.0.1/go.mod h1:tYAtpctvSP/tWw4MeelsowSPgXQRVHHWbqL6ynps8jU= github.com/dubbogo/net v0.0.4 h1:Rn9aMPZwOiRE22YhtxmDEE3H0Q3cfVRNhuEjNMelJ/8= github.com/dubbogo/net v0.0.4/go.mod h1:1CGOnM7X3he+qgGNqjeADuE5vKZQx/eMSeUkpU3ujIc= -github.com/dubbogo/triple v1.0.6-0.20210904050749-5721796f3fd6 h1:ZrCFQ/a0rgK5EBF9FiiSYvCmtC2sLzOoFAbqBVmsA94= -github.com/dubbogo/triple v1.0.6-0.20210904050749-5721796f3fd6/go.mod h1:KbfU/uZDv+fJEqXYK3qI8m1iuBQ309QxiC0tvTf2pog= github.com/dubbogo/triple v1.0.6-0.20210909153707-3620c8d2d97c h1:/Qrdqo2JVrywDANk04DHrvdfREdIApAWZ6stbYZfNaM= github.com/dubbogo/triple v1.0.6-0.20210909153707-3620c8d2d97c/go.mod h1:KbfU/uZDv+fJEqXYK3qI8m1iuBQ309QxiC0tvTf2pog= github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= @@ -677,8 +675,8 @@ github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/ryanuber/go-glob v1.0.0/go.mod h1:807d1WSdnB0XRJzKNil9Om6lcp/3a0v4qIHxIXzX/Yc= github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E= -github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww= -github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= +github.com/satori/go.uuid v1.2.1-0.20181028125025-b2ce2384e17b h1:gQZ0qzfKHQIybLANtM3mBXNUtOfsCFXeTsnBqCsx1KM= +github.com/satori/go.uuid v1.2.1-0.20181028125025-b2ce2384e17b/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/shirou/gopsutil v3.20.11+incompatible h1:LJr4ZQK4mPpIV5gOa4jCOKOGb4ty4DZO54I4FGqIpto= github.com/shirou/gopsutil v3.20.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= diff --git a/metadata/service/exporter/configurable/exporter.go b/metadata/service/exporter/configurable/exporter.go index feee9480e4..551d79d56d 100644 --- a/metadata/service/exporter/configurable/exporter.go +++ b/metadata/service/exporter/configurable/exporter.go @@ -61,21 +61,20 @@ func (exporter *MetadataServiceExporter) Export(url *common.URL) error { version, _ := exporter.metadataService.Version() exporter.lock.Lock() defer exporter.lock.Unlock() - exporter.ServiceConfig = config.NewServiceConfig( - config.WithServiceID(constant.SIMPLE_METADATA_SERVICE_NAME), - config.WithServiceProtocolKeys(constant.DEFAULT_PROTOCOL), - config.WithServiceProtocol(constant.DEFAULT_PROTOCOL, config.NewProtocolConfig( - config.WithProtocolName(constant.DEFAULT_PROTOCOL), - config.WithProtocolPort(strconv.Itoa(constant.DEFAULT_METADATAPORT)), - )), - config.WithServiceRegistry("N/A"), - config.WithServiceInterface(constant.METADATA_SERVICE_NAME), - config.WithServiceGroup(config.GetApplicationConfig().Name), - config.WithServiceVersion(version), - config.WithProxyFactoryKey(constant.DEFAULT_Key), - config.WithServiceInterface(constant.METADATA_SERVICE_NAME), - config.WithServiceMetadataType(constant.REMOTE_METADATA_STORAGE_TYPE), - ) + exporter.ServiceConfig = config.NewServiceConfigBuilder(). + SetServiceID(constant.SIMPLE_METADATA_SERVICE_NAME). + SetProtocolIDs(constant.DEFAULT_PROTOCOL). + AddRCProtocol(constant.DEFAULT_PROTOCOL, config.NewProtocolConfigBuilder(). + SetName(constant.DEFAULT_PROTOCOL). + SetPort(strconv.Itoa(constant.DEFAULT_METADATAPORT)). + Build()). + SetRegistryIDs("N/A"). + SetInterface(constant.METADATA_SERVICE_NAME). + SetGroup(config.GetApplicationConfig().Name). + SetVersion(version). + SetProxyFactoryKey(constant.DEFAULT_Key). + SetMetadataType(constant.REMOTE_METADATA_STORAGE_TYPE). + Build() exporter.ServiceConfig.Implement(exporter.metadataService) err := exporter.ServiceConfig.Export() diff --git a/metadata/service/exporter/configurable/exporter_test.go b/metadata/service/exporter/configurable/exporter_test.go index 1fe775d9a5..772a8df8d8 100644 --- a/metadata/service/exporter/configurable/exporter_test.go +++ b/metadata/service/exporter/configurable/exporter_test.go @@ -70,7 +70,7 @@ func TestConfigurableExporter(t *testing.T) { assert.Equal(t, false, exported.IsExported()) assert.NoError(t, exported.Export(registryURL)) assert.Equal(t, true, exported.IsExported()) - assert.Regexp(t, "dubbo://127.0.0.1:20005/org.apache.dubbo.metadata.MetadataService*", exported.GetExportedURLs()[0].String()) + assert.Regexp(t, "dubbo://:20005/org.apache.dubbo.metadata.MetadataService*", exported.GetExportedURLs()[0].String()) exported.Unexport() assert.Equal(t, false, exported.IsExported()) }) @@ -78,8 +78,7 @@ func TestConfigurableExporter(t *testing.T) { // mockInitProviderWithSingleRegistry will init a mocked providerConfig func mockInitProviderWithSingleRegistry() { - providerConfig := config.GetProviderInstance( - config.WithProviderService("MockService", config.NewServiceConfig())) + providerConfig := config.NewProviderConfigBuilder().AddService("MockService", config.NewServiceConfigBuilder().Build()).Build() providerConfig.Services["MockService"].InitExported() config.SetRootConfig(config.RootConfig{ Application: &config.ApplicationConfig{ @@ -109,7 +108,7 @@ func mockInitProviderWithSingleRegistry() { Services: map[string]*config.ServiceConfig{ "MockService": { Interface: "com.MockService", - Protocol: []string{"mock"}, + ProtocolIDs: []string{"mock"}, Cluster: "failover", Loadbalance: "random", Retries: "3", diff --git a/metrics/prometheus/reporter.go b/metrics/prometheus/reporter.go index 96ec3093ae..295d018e76 100644 --- a/metrics/prometheus/reporter.go +++ b/metrics/prometheus/reporter.go @@ -218,6 +218,7 @@ func newPrometheusReporter() metrics.Reporter { prom.DefaultRegisterer.MustRegister(reporterInstance.consumerSummaryVec, reporterInstance.providerSummaryVec, reporterInstance.consumerHistogramVec, reporterInstance.providerHistogramVec) + // todo open prometheus metrics service //metricsExporter, err := ocprom.NewExporter(ocprom.Options{ // Registry: prom.DefaultRegisterer.(*prom.Registry), //}) diff --git a/protocol/dubbo3/internal/server.go b/protocol/dubbo3/internal/server.go index 5ba17651b3..97245dfa17 100644 --- a/protocol/dubbo3/internal/server.go +++ b/protocol/dubbo3/internal/server.go @@ -43,26 +43,23 @@ func (s *Server) SayHello(ctx context.Context, in *HelloRequest) (*HelloReply, e // InitDubboServer creates global gRPC server. func InitDubboServer() { - serviceConfig := config.NewServiceConfig( - config.WithServiceInterface("org.apache.dubbo.DubboGreeterImpl"), - config.WithServiceProtocolKeys("tripleKey"), - ) + serviceConfig := config.NewServiceConfigBuilder(). + SetInterface("org.apache.dubbo.DubboGreeterImpl"). + SetProtocolIDs("tripleKey").Build() - providerConfig := config.GetProviderInstance( - config.WithProviderService(common.GetReference(&Server{}), serviceConfig), - ) + providerConfig := config.NewProviderConfigBuilder().SetServices(map[string]*config.ServiceConfig{ + common.GetReference(&Server{}): serviceConfig, + }).Build() - protocolConfig := config.NewProtocolConfig( - config.WithProtocolName("tri"), - config.WithProtocolPort("20003"), - ) + protocolConfig := config.NewProtocolConfigBuilder().SetName("tri").SetPort("20003").Build() - rootConfig := config.GetInstance( - config.WithRootProviderConfig(providerConfig), - config.WithRootProtocolConfig("tripleKey", protocolConfig), - ) + rootConfig := config.NewRootConfigBuilder().SetProvider(providerConfig).SetProtocols(map[string]*config.ProtocolConfig{ + "tripleKey": protocolConfig, + }).Build() config.SetProviderService(&Server{}) - rootConfig.Init() + if err := rootConfig.Init(); err != nil { + panic(err) + } rootConfig.Start() } diff --git a/protocol/grpc/grpc_protocol_test.go b/protocol/grpc/grpc_protocol_test.go index d2d59a512d..9790843f95 100644 --- a/protocol/grpc/grpc_protocol_test.go +++ b/protocol/grpc/grpc_protocol_test.go @@ -47,8 +47,8 @@ func doInitProvider() { Services: map[string]*config.ServiceConfig{ "GrpcGreeterImpl": { Interface: "io.grpc.examples.helloworld.GreeterGrpc$IGreeter", - Protocol: []string{"grpc"}, - Registry: []string{"shanghai_reg1,shanghai_reg2,hangzhou_reg1,hangzhou_reg2,hangzhou_service_discovery_reg"}, + ProtocolIDs: []string{"grpc"}, + RegistryIDs: []string{"shanghai_reg1,shanghai_reg2,hangzhou_reg1,hangzhou_reg2,hangzhou_service_discovery_reg"}, Cluster: "failover", Loadbalance: "random", Retries: "3", diff --git a/registry/protocol/protocol.go b/registry/protocol/protocol.go index 37280c77b6..add0c5d157 100644 --- a/registry/protocol/protocol.go +++ b/registry/protocol/protocol.go @@ -260,7 +260,7 @@ func registerServiceMap(invoker protocol.Invoker) error { _, err := common.ServiceMap.Register(serviceConfig.Interface, // FIXME - serviceConfig.Protocol[0], serviceConfig.Group, + serviceConfig.ProtocolIDs[0], serviceConfig.Group, serviceConfig.Version, rpcService) if err != nil { s := "reExport can not re register ServiceMap. Error message is " + err.Error() diff --git a/remoting/nacos/builder_test.go b/remoting/nacos/builder_test.go index 89992d6cb8..eb4c1a6996 100644 --- a/remoting/nacos/builder_test.go +++ b/remoting/nacos/builder_test.go @@ -50,7 +50,7 @@ func TestNewNacosClient(t *testing.T) { assert.NotNil(t, err) rc.Address = "console.nacos.io:80" - rc.TimeoutStr = "10s" + rc.Timeout = "10s" client, err = NewNacosClient(rc) assert.NotNil(t, client) assert.Nil(t, err)