diff --git a/cluster/cluster_impl/failover_cluster_test.go b/cluster/cluster_impl/failover_cluster_test.go index 7bde83ea66a49f9317732ec46da0f11800f846eb..46b7b28e0299b669f5ec48ed024e7aa80c39e3d8 100644 --- a/cluster/cluster_impl/failover_cluster_test.go +++ b/cluster/cluster_impl/failover_cluster_test.go @@ -79,8 +79,10 @@ type rest struct { func (bi *MockInvoker) Invoke(c context.Context, invocation protocol.Invocation) protocol.Result { count++ - var success bool - var err error = nil + var ( + success bool + err error + ) if count >= bi.successCount { success = true } else { diff --git a/cluster/cluster_impl/failsafe_cluster_test.go b/cluster/cluster_impl/failsafe_cluster_test.go index 930b4bb16628e2b363659a65fc174543b7f2cf6e..234995b8e522124fe9beff0937ca23a63aa63844 100644 --- a/cluster/cluster_impl/failsafe_cluster_test.go +++ b/cluster/cluster_impl/failsafe_cluster_test.go @@ -42,8 +42,8 @@ var ( failsafeUrl, _ = common.NewURL(context.TODO(), "dubbo://192.168.1.1:20000/com.ikurento.user.UserProvider") ) -// register_failsafe register failsafeCluster to cluster extension. -func register_failsafe(t *testing.T, invoker *mock.MockInvoker) protocol.Invoker { +// registerFailsafe register failsafeCluster to cluster extension. +func registerFailsafe(t *testing.T, invoker *mock.MockInvoker) protocol.Invoker { extension.SetLoadbalance("random", loadbalance.NewRandomLoadBalance) failsafeCluster := NewFailsafeCluster() @@ -62,7 +62,7 @@ func Test_FailSafeInvokeSuccess(t *testing.T) { defer ctrl.Finish() invoker := mock.NewMockInvoker(ctrl) - clusterInvoker := register_failsafe(t, invoker) + clusterInvoker := registerFailsafe(t, invoker) invoker.EXPECT().GetUrl().Return(failsafeUrl).AnyTimes() @@ -81,7 +81,7 @@ func Test_FailSafeInvokeFail(t *testing.T) { defer ctrl.Finish() invoker := mock.NewMockInvoker(ctrl) - clusterInvoker := register_failsafe(t, invoker) + clusterInvoker := registerFailsafe(t, invoker) invoker.EXPECT().GetUrl().Return(failsafeUrl).AnyTimes() diff --git a/cluster/cluster_impl/forking_cluster_invoker.go b/cluster/cluster_impl/forking_cluster_invoker.go index c830079ff6d3c29c3385eda289782f5e52877be2..058d7fefd6edf6c43e5eda4b8f2f6a9c161189e2 100644 --- a/cluster/cluster_impl/forking_cluster_invoker.go +++ b/cluster/cluster_impl/forking_cluster_invoker.go @@ -19,7 +19,6 @@ package cluster_impl import ( "context" - "errors" "fmt" "time" ) @@ -45,6 +44,7 @@ func newForkingClusterInvoker(directory cluster.Directory) protocol.Invoker { } } +// Invoke ... func (invoker *forkingClusterInvoker) Invoke(ctx context.Context, invocation protocol.Invocation) protocol.Result { err := invoker.checkWhetherDestroyed() if err != nil { @@ -87,14 +87,18 @@ func (invoker *forkingClusterInvoker) Invoke(ctx context.Context, invocation pro rsps, err := resultQ.Poll(1, time.Millisecond*time.Duration(timeouts)) if err != nil { return &protocol.RPCResult{ - Err: errors.New(fmt.Sprintf("failed to forking invoke provider %v, but no luck to perform the invocation. Last error is: %s", selected, err.Error()))} + Err: fmt.Errorf("failed to forking invoke provider %v, "+ + "but no luck to perform the invocation. Last error is: %v", selected, err), + } } if len(rsps) == 0 { - return &protocol.RPCResult{Err: errors.New(fmt.Sprintf("failed to forking invoke provider %v, but no resp", selected))} + return &protocol.RPCResult{Err: fmt.Errorf("failed to forking invoke provider %v, but no resp", selected)} } + result, ok := rsps[0].(protocol.Result) if !ok { - return &protocol.RPCResult{Err: errors.New(fmt.Sprintf("failed to forking invoke provider %v, but not legal resp", selected))} + return &protocol.RPCResult{Err: fmt.Errorf("failed to forking invoke provider %v, but not legal resp", selected)} } + return result } diff --git a/cluster/directory.go b/cluster/directory.go index 045296ce549b13c327b6f479ca0bd75d0b6ce131..c3a67e9473adbdc96f5729fa589f3f67e9502ebc 100644 --- a/cluster/directory.go +++ b/cluster/directory.go @@ -22,7 +22,7 @@ import ( "github.com/apache/dubbo-go/protocol" ) -// Extension - Directory +// Directory: Extension - Directory type Directory interface { common.Node List(invocation protocol.Invocation) []protocol.Invoker diff --git a/cluster/loadbalance.go b/cluster/loadbalance.go index 9ae4e4eb808b28581d12b72829c921c4f0cc9ac8..33170ac99fa7ba3092d7dda5cdcf3a84bd2e3344 100644 --- a/cluster/loadbalance.go +++ b/cluster/loadbalance.go @@ -21,7 +21,7 @@ import ( "github.com/apache/dubbo-go/protocol" ) -// Extension - LoadBalance +// LoadBalance: Extension - LoadBalance type LoadBalance interface { Select([]protocol.Invoker, protocol.Invocation) protocol.Invoker } diff --git a/cluster/loadbalance/consistent_hash.go b/cluster/loadbalance/consistent_hash.go index 8c5f8a5001347d10da4347827c1935ddda1f8a86..957c110663d6c56ada15543d372e210fa83bf74b 100644 --- a/cluster/loadbalance/consistent_hash.go +++ b/cluster/loadbalance/consistent_hash.go @@ -36,9 +36,12 @@ import ( ) const ( + // ConsistentHash ... ConsistentHash = "consistenthash" - HashNodes = "hash.nodes" - HashArguments = "hash.arguments" + // HashNodes ... + HashNodes = "hash.nodes" + // HashArguments ... + HashArguments = "hash.arguments" ) var ( diff --git a/cluster/loadbalance/least_active.go b/cluster/loadbalance/least_active.go index 773bb9323f02349a221a754f256b6c50ac2911a2..e7c41aac93e8d3dfcef5d49fa486483bd045f569 100644 --- a/cluster/loadbalance/least_active.go +++ b/cluster/loadbalance/least_active.go @@ -28,6 +28,7 @@ import ( ) const ( + // LeastActive ... LeastActive = "leastactive" ) @@ -53,12 +54,12 @@ func (lb *leastActiveLoadBalance) Select(invokers []protocol.Invoker, invocation } var ( - leastActive int32 = -1 // The least active value of all invokers - totalWeight int64 = 0 // The number of invokers having the same least active value (LEAST_ACTIVE) - firstWeight int64 = 0 // Initial value, used for comparison - leastIndexes = make([]int, count) // The index of invokers having the same least active value (LEAST_ACTIVE) - leastCount = 0 // The number of invokers having the same least active value (LEAST_ACTIVE) - sameWeight = true // Every invoker has the same weight value? + leastActive int32 = -1 // The least active value of all invokers + totalWeight int64 // The number of invokers having the same least active value (LEAST_ACTIVE) + firstWeight int64 // Initial value, used for comparison + leastCount int // The number of invokers having the same least active value (LEAST_ACTIVE) + leastIndexes = make([]int, count) // The index of invokers having the same least active value (LEAST_ACTIVE) + sameWeight = true // Every invoker has the same weight value? ) for i := 0; i < count; i++ { diff --git a/cluster/loadbalance/round_robin.go b/cluster/loadbalance/round_robin.go index 653e42c3b5d08cbefb25db98278fb6afa6f02c96..e720ab05b23ae3498bb1d7deb0f87e148c992a97 100644 --- a/cluster/loadbalance/round_robin.go +++ b/cluster/loadbalance/round_robin.go @@ -31,16 +31,19 @@ import ( ) const ( + // RoundRobin ... RoundRobin = "roundrobin" + // COMPLETE ... COMPLETE = 0 + // UPDATING ... UPDATING = 1 ) var ( - methodWeightMap sync.Map // [string]invokers - state int32 = COMPLETE // update lock acquired ? - recyclePeriod int64 = 60 * time.Second.Nanoseconds() + methodWeightMap sync.Map // [string]invokers + state = COMPLETE // update lock acquired ? + recyclePeriod = 60 * time.Second.Nanoseconds() ) func init() { diff --git a/cluster/router/condition_router.go b/cluster/router/condition_router.go index 28966e4eac8f289f34f2958a9509f01bdb54d23a..c4561130c2a5a91b833d2c206fa70bba30fc2714 100644 --- a/cluster/router/condition_router.go +++ b/cluster/router/condition_router.go @@ -37,9 +37,12 @@ import ( ) const ( + //ROUTE_PATTERN: route pattern regex ROUTE_PATTERN = `([&!=,]*)\\s*([^&!=,\\s]+)` - FORCE = "force" - PRIORITY = "priority" + // FORCE ... + FORCE = "force" + // PRIORITY ... + PRIORITY = "priority" ) //ConditionRouter condition router struct @@ -104,7 +107,7 @@ func newConditionRouter(url *common.URL) (*ConditionRouter, error) { }, nil } -//Router determine the target server list. +//Route: Router determine the target server list. func (c *ConditionRouter) Route(invokers []protocol.Invoker, url common.URL, invocation protocol.Invocation) []protocol.Invoker { if len(invokers) == 0 { return invokers @@ -212,7 +215,7 @@ func parseRule(rule string) (map[string]MatchPair, error) { return condition, nil } -// +//MatchWhen MatchWhen func (c *ConditionRouter) MatchWhen(url common.URL, invocation protocol.Invocation) (bool, error) { condition, err := MatchCondition(c.WhenCondition, &url, nil, invocation) return len(c.WhenCondition) == 0 || condition, err @@ -245,15 +248,15 @@ func MatchCondition(pairs map[string]MatchPair, url *common.URL, param *common.U if len(sampleValue) > 0 { if !matchPair.isMatch(sampleValue, param) { return false, nil - } else { - result = true } + + result = true } else { if !(matchPair.Matches.Empty()) { return false, nil - } else { - result = true } + + result = true } } return result, nil diff --git a/cluster/router/condition_router_test.go b/cluster/router/condition_router_test.go index 7acbdabc9b6c1976664fce7596ce22c187f48068..3844f503fae27a25f2379a6f20298a8baeb947d4 100644 --- a/cluster/router/condition_router_test.go +++ b/cluster/router/condition_router_test.go @@ -95,13 +95,17 @@ var count int func (bi *MockInvoker) Invoke(ctx context.Context, invocation protocol.Invocation) protocol.Result { count++ - var success bool - var err error = nil + + var ( + success bool + err error = nil + ) if count >= bi.successCount { success = true } else { err = perrors.New("error") } + result := &protocol.RPCResult{Err: err, Rest: rest{tried: count, success: success}} return result } diff --git a/common/config/environment.go b/common/config/environment.go index 256741b99968b292330b26cd6c46f6ee421a55a2..ec03ccf3eea4068ab527c05373be1556291af768 100644 --- a/common/config/environment.go +++ b/common/config/environment.go @@ -27,6 +27,7 @@ import ( "github.com/apache/dubbo-go/config_center" ) +// Environment: // There is dubbo.properties file and application level config center configuration which higner than normal config center in java. So in java the // configuration sequence will be config center > application level config center > dubbo.properties > spring bean configuration. // But in go, neither the dubbo.properties file or application level config center configuration will not support for the time being. diff --git a/common/constant/env.go b/common/constant/env.go index 759cb0be0a2bd36a2a345a360c541b7d56813d70..cb5394bb82ec29d1d24e02627e9d8fafff212efa 100644 --- a/common/constant/env.go +++ b/common/constant/env.go @@ -18,7 +18,10 @@ package constant const ( + // CONF_CONSUMER_FILE_PATH ... CONF_CONSUMER_FILE_PATH = "CONF_CONSUMER_FILE_PATH" + // CONF_PROVIDER_FILE_PATH ... CONF_PROVIDER_FILE_PATH = "CONF_PROVIDER_FILE_PATH" - APP_LOG_CONF_FILE = "APP_LOG_CONF_FILE" + // APP_LOG_CONF_FILE ... + APP_LOG_CONF_FILE = "APP_LOG_CONF_FILE" ) diff --git a/common/constant/version.go b/common/constant/version.go index 8ef9fae2c6088e78007abf8f7ddd81cc363c4ec3..f0c38f6864da16180b41b62ec006ff24bfe2cf75 100644 --- a/common/constant/version.go +++ b/common/constant/version.go @@ -18,7 +18,10 @@ package constant const ( + // Version: apache/dubbo-go version Version = "1.3.0" - Name = "dubbogo" - DATE = "2020/01/12" + // Name: module name + Name = "dubbogo" + // Date: release date + DATE = "2020/01/12" ) diff --git a/common/extension/configurator.go b/common/extension/configurator.go index 63bcc8c55dc48ce1feb43ea0dc82172f6ea48526..de98f8a260ea1f3a2e2a1f32c82dc869585e2789 100644 --- a/common/extension/configurator.go +++ b/common/extension/configurator.go @@ -22,7 +22,10 @@ import ( "github.com/apache/dubbo-go/config_center" ) -const DefaultKey = "default" +const ( + // DefaultKey ... + DefaultKey = "default" +) type getConfiguratorFunc func(url *common.URL) config_center.Configurator diff --git a/common/extension/graceful_shutdown.go b/common/extension/graceful_shutdown.go index bc03a2ff4a440aabfef4233374308fc486f5618e..1a1fb92058f5140bbd9ee2c64a7c31ec1835420e 100644 --- a/common/extension/graceful_shutdown.go +++ b/common/extension/graceful_shutdown.go @@ -26,7 +26,7 @@ var ( ) /** - * you should not make any assumption about the order. + * AddCustomShutdownCallback: you should not make any assumption about the order. * For example, if you have more than one callbacks, and you wish the order is: * callback1() * callback2() diff --git a/common/extension/proxy_factory.go b/common/extension/proxy_factory.go index 7b9a5b860ba1413f69d46e0657b1145e3c285304..19826bb0560ea0d3fa471c04873b20a6878f57d8 100644 --- a/common/extension/proxy_factory.go +++ b/common/extension/proxy_factory.go @@ -22,12 +22,12 @@ import ( ) var ( - proxy_factories = make(map[string]func(...proxy.Option) proxy.ProxyFactory) + proxyFactories = make(map[string]func(...proxy.Option) proxy.ProxyFactory) ) // SetProxyFactory ... func SetProxyFactory(name string, f func(...proxy.Option) proxy.ProxyFactory) { - proxy_factories[name] = f + proxyFactories[name] = f } // GetProxyFactory ... @@ -35,8 +35,8 @@ func GetProxyFactory(name string) proxy.ProxyFactory { if name == "" { name = "default" } - if proxy_factories[name] == nil { + if proxyFactories[name] == nil { panic("proxy factory for " + name + " is not existing, make sure you have import the package.") } - return proxy_factories[name]() + return proxyFactories[name]() } diff --git a/common/proxy/proxy.go b/common/proxy/proxy.go index d0be491d406170ea4c52e65f70f0dfbe7b1b3cb6..b9e85a03fb6f9f3dad928e10052f07d0ced16eb0 100644 --- a/common/proxy/proxy.go +++ b/common/proxy/proxy.go @@ -51,7 +51,7 @@ func NewProxy(invoke protocol.Invoker, callBack interface{}, attachments map[str } } -// proxy implement +// Implement: proxy implement // In consumer, RPCService like: // type XxxProvider struct { // Yyy func(ctx context.Context, args []interface{}, rsp *Zzz) error diff --git a/common/rpc_service.go b/common/rpc_service.go index b819cf28f5c2499d39ac3bcd977c0d1b442daff5..5fec12b2975338c41e3c9c06ae10ccc1f478369f 100644 --- a/common/rpc_service.go +++ b/common/rpc_service.go @@ -34,19 +34,21 @@ import ( "github.com/apache/dubbo-go/common/logger" ) -// rpc service interface +// RPCService: rpc service interface type RPCService interface { - Reference() string // rpc service id or reference id + // Reference: + // rpc service id or reference id + Reference() string } //AsyncCallbackService callback interface for async type AsyncCallbackService interface { - CallBack(response CallbackResponse) // callback + // Callback: callback + CallBack(response CallbackResponse) } //CallbackResponse for different protocol -type CallbackResponse interface { -} +type CallbackResponse interface{} //AsyncCallback async callback method type AsyncCallback func(response CallbackResponse) @@ -55,7 +57,10 @@ type AsyncCallback func(response CallbackResponse) // func MethodMapper() map[string][string] { // return map[string][string]{} // } -const METHOD_MAPPER = "MethodMapper" +const ( + // METHOD_MAPPER ... + METHOD_MAPPER = "MethodMapper" +) var ( // Precompute the reflect type for error. Can't use error directly @@ -63,6 +68,7 @@ var ( typeOfError = reflect.TypeOf((*error)(nil)).Elem() // todo: lowerecas? + // ServiceMap ... ServiceMap = &serviceMap{ serviceMap: make(map[string]map[string]*Service), } diff --git a/common/rpc_service_test.go b/common/rpc_service_test.go index 7df039b905d3cc064c5d6d9404fc874cf693dac9..8c9b9d15cdd4061dbe2f445b5fff7a868e5ae67e 100644 --- a/common/rpc_service_test.go +++ b/common/rpc_service_test.go @@ -122,9 +122,8 @@ func TestServiceMap_UnRegister(t *testing.T) { func TestMethodType_SuiteContext(t *testing.T) { mt := &MethodType{ctxType: reflect.TypeOf(context.TODO())} - c := context.TODO() - c = context.WithValue(c, "key", "value") - assert.Equal(t, reflect.ValueOf(c), mt.SuiteContext(c)) + ctx := context.WithValue(context.Background(), "key", "value") + assert.Equal(t, reflect.ValueOf(ctx), mt.SuiteContext(ctx)) assert.Equal(t, reflect.Zero(mt.ctxType), mt.SuiteContext(nil)) } diff --git a/common/url.go b/common/url.go index 6283bf454135dc63e089a303f9131c65f9cded9e..a073e013f47a2acff4782ffa4444203fa0cec9b5 100644 --- a/common/url.go +++ b/common/url.go @@ -45,17 +45,23 @@ import ( // dubbo role type ///////////////////////////////// +// role constant const ( + // CONSUMER ... CONSUMER = iota + // CONFIGURATOR ... CONFIGURATOR + // ROUTER ... ROUTER + // PROVIDER ... PROVIDER ) var ( // DubboNodes ... DubboNodes = [...]string{"consumers", "configurators", "routers", "providers"} - DubboRole = [...]string{"consumer", "", "", "provider"} + // DubboRole ... + DubboRole = [...]string{"consumer", "", "", "provider"} ) // RoleType ... @@ -428,7 +434,7 @@ func (c URL) GetRawParam(key string) string { } } -// GetParamBool +// GetParamBool ... func (c URL) GetParamBool(s string, d bool) bool { var r bool diff --git a/config/base_config.go b/config/base_config.go index 4e4773fa48d70315c7049404407bca344bd00ecd..09495741153cf7caae4bb10ada0aaa686fbf0325 100644 --- a/config/base_config.go +++ b/config/base_config.go @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package config import ( @@ -90,6 +91,9 @@ func (c *BaseConfig) prepareEnvironment() error { configFile = c.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) @@ -295,8 +299,8 @@ func setFieldValue(val reflect.Value, id reflect.Value, config *config.InmemoryC func (c *BaseConfig) fresh() { configList := config.GetEnvInstance().Configuration() for element := configList.Front(); element != nil; element = element.Next() { - config := element.Value.(*config.InmemoryConfiguration) - c.freshInternalConfig(config) + cfg := element.Value.(*config.InmemoryConfiguration) + c.freshInternalConfig(cfg) } } diff --git a/config/config_loader.go b/config/config_loader.go index 43237be94bf10168557a99923735f2359cf76e73..a6df1a638edd13508ec5ad255f72ecab6415c662 100644 --- a/config/config_loader.go +++ b/config/config_loader.go @@ -69,7 +69,7 @@ func checkApplicationName(config *ApplicationConfig) { } } -// Dubbo Init +// Load: Dubbo Init func Load() { // reference config if consumerConfig == nil { @@ -153,12 +153,12 @@ func Load() { GracefulShutdownInit() } -// get rpc service for consumer +// GetRPCService: get rpc service for consumer func GetRPCService(name string) common.RPCService { return consumerConfig.References[name].GetRPCService() } -// create rpc service for consumer +// RPCService: create rpc service for consumer func RPCService(service common.RPCService) { consumerConfig.References[service.Reference()].Implement(service) } diff --git a/config/consumer_config.go b/config/consumer_config.go index 7a35d8ef7541a005c972ac261e9e95cf7b703ea5..7756f3b51c0f46a19687affb4dc6eadf9ef711c7 100644 --- a/config/consumer_config.go +++ b/config/consumer_config.go @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package config import ( diff --git a/config/generic_service.go b/config/generic_service.go index e0171418ceaa72ecb9ad64055781baa2e5afdc30..9895486e977a9848e576597f31b724d51d144d4e 100644 --- a/config/generic_service.go +++ b/config/generic_service.go @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package config // GenericService ... diff --git a/config/graceful_shutdown_signal_darwin.go b/config/graceful_shutdown_signal_darwin.go index c6932bf981d8857615f19c8ead3ef0f93dd74358..8ad79ffa62ceed4096c60bfb9139b7ff1586808e 100644 --- a/config/graceful_shutdown_signal_darwin.go +++ b/config/graceful_shutdown_signal_darwin.go @@ -22,11 +22,13 @@ import ( "syscall" ) -// ShutdownSignals ... -var ShutdownSignals = []os.Signal{os.Interrupt, os.Kill, syscall.SIGKILL, syscall.SIGSTOP, - syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGILL, syscall.SIGTRAP, - syscall.SIGABRT, syscall.SIGSYS} +var ( + // ShutdownSignals ... + ShutdownSignals = []os.Signal{os.Interrupt, os.Kill, syscall.SIGKILL, syscall.SIGSTOP, + syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGILL, syscall.SIGTRAP, + syscall.SIGABRT, syscall.SIGSYS} -// DumpHeapShutdownSignals ... -var DumpHeapShutdownSignals = []os.Signal{syscall.SIGQUIT, syscall.SIGILL, - syscall.SIGTRAP, syscall.SIGABRT, syscall.SIGSYS} + // DumpHeapShutdownSignals ... + DumpHeapShutdownSignals = []os.Signal{syscall.SIGQUIT, syscall.SIGILL, + syscall.SIGTRAP, syscall.SIGABRT, syscall.SIGSYS} +) diff --git a/config/graceful_shutdown_signal_linux.go b/config/graceful_shutdown_signal_linux.go index 59c1a5d149c2e9db8e9ac981adec107cafc863ad..8ad79ffa62ceed4096c60bfb9139b7ff1586808e 100644 --- a/config/graceful_shutdown_signal_linux.go +++ b/config/graceful_shutdown_signal_linux.go @@ -22,9 +22,13 @@ import ( "syscall" ) -var ShutdownSignals = []os.Signal{os.Interrupt, os.Kill, syscall.SIGKILL, syscall.SIGSTOP, - syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGILL, syscall.SIGTRAP, - syscall.SIGABRT, syscall.SIGSYS} +var ( + // ShutdownSignals ... + ShutdownSignals = []os.Signal{os.Interrupt, os.Kill, syscall.SIGKILL, syscall.SIGSTOP, + syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGILL, syscall.SIGTRAP, + syscall.SIGABRT, syscall.SIGSYS} -var DumpHeapShutdownSignals = []os.Signal{syscall.SIGQUIT, syscall.SIGILL, - syscall.SIGTRAP, syscall.SIGABRT, syscall.SIGSYS} + // DumpHeapShutdownSignals ... + DumpHeapShutdownSignals = []os.Signal{syscall.SIGQUIT, syscall.SIGILL, + syscall.SIGTRAP, syscall.SIGABRT, syscall.SIGSYS} +) diff --git a/config/graceful_shutdown_signal_windows.go b/config/graceful_shutdown_signal_windows.go index 91b2bce7c2311ecbe9a1255be3e7b7b357a9b403..815a05ecb20a8fc202debaf6f39d699845cd689e 100644 --- a/config/graceful_shutdown_signal_windows.go +++ b/config/graceful_shutdown_signal_windows.go @@ -22,8 +22,12 @@ import ( "syscall" ) -var ShutdownSignals = []os.Signal{os.Interrupt, os.Kill, syscall.SIGKILL, - syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGILL, syscall.SIGTRAP, - syscall.SIGABRT} +var ( + // ShutdownSignals ... + ShutdownSignals = []os.Signal{os.Interrupt, os.Kill, syscall.SIGKILL, + syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGILL, syscall.SIGTRAP, + syscall.SIGABRT} -var DumpHeapShutdownSignals = []os.Signal{syscall.SIGQUIT, syscall.SIGILL, syscall.SIGTRAP, syscall.SIGABRT} + // DumpHeapShutdownSignals ... + DumpHeapShutdownSignals = []os.Signal{syscall.SIGQUIT, syscall.SIGILL, syscall.SIGTRAP, syscall.SIGABRT} +) diff --git a/config/method_config.go b/config/method_config.go index 6dd8099a6310a861d6645d478b0c1688fcdebf77..8f196d9e2c03071a663db03cb185fb9106d6484a 100644 --- a/config/method_config.go +++ b/config/method_config.go @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package config import ( @@ -43,11 +44,11 @@ type MethodConfig struct { // Prefix ... func (c *MethodConfig) Prefix() string { - if c.InterfaceId != "" { + if len(c.InterfaceId) != 0 { return constant.DUBBO + "." + c.InterfaceName + "." + c.InterfaceId + "." + c.Name + "." - } else { - return constant.DUBBO + "." + c.InterfaceName + "." + c.Name + "." } + + return constant.DUBBO + "." + c.InterfaceName + "." + c.Name + "." } // UnmarshalYAML ... diff --git a/config/protocol_config.go b/config/protocol_config.go index 9495a7fd892354f2b7611a73760b0a2885794534..4828d6e5bd28de19d896340f39c5633d0acd4874 100644 --- a/config/protocol_config.go +++ b/config/protocol_config.go @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package config import ( diff --git a/config/provider_config.go b/config/provider_config.go index 537608d4b51e5a24b269f9baa295764f7c6330ed..0bfa78647b58d9b6eb961adc5485207faffe1e1e 100644 --- a/config/provider_config.go +++ b/config/provider_config.go @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package config import ( diff --git a/config/reference_config.go b/config/reference_config.go index e3fe856b1228d445c0f53c56991f5eb5a6fb2d34..fe3a72ca23e65631da422c4e6102dcdb43bad196 100644 --- a/config/reference_config.go +++ b/config/reference_config.go @@ -70,13 +70,13 @@ func (c *ReferenceConfig) Prefix() string { return constant.ReferenceConfigPrefix + c.InterfaceName + "." } -// The only way to get a new ReferenceConfig +// NewReferenceConfig: The only way to get a new ReferenceConfig func NewReferenceConfig(id string, ctx context.Context) *ReferenceConfig { return &ReferenceConfig{id: id, context: ctx} } // UnmarshalYAML ... -func (refconfig *ReferenceConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { +func (c *ReferenceConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { type rf ReferenceConfig raw := rf{} // Put your defaults here @@ -84,8 +84,8 @@ func (refconfig *ReferenceConfig) UnmarshalYAML(unmarshal func(interface{}) erro return err } - *refconfig = ReferenceConfig(raw) - if err := defaults.Set(refconfig); err != nil { + *c = ReferenceConfig(raw) + if err := defaults.Set(c); err != nil { return err } @@ -93,16 +93,16 @@ func (refconfig *ReferenceConfig) UnmarshalYAML(unmarshal func(interface{}) erro } // Refer ... -func (refconfig *ReferenceConfig) Refer(impl interface{}) { - url := common.NewURLWithOptions(common.WithPath(refconfig.id), - common.WithProtocol(refconfig.Protocol), - common.WithParams(refconfig.getUrlMap()), - common.WithParamsValue(constant.BEAN_NAME_KEY, refconfig.id), +func (c *ReferenceConfig) Refer(impl interface{}) { + url := common.NewURLWithOptions(common.WithPath(c.id), + common.WithProtocol(c.Protocol), + common.WithParams(c.getUrlMap()), + common.WithParamsValue(constant.BEAN_NAME_KEY, c.id), ) //1. user specified URL, could be peer-to-peer address, or register center's address. - if refconfig.Url != "" { - urlStrings := gxstrings.RegSplit(refconfig.Url, "\\s*[;]+\\s*") + if c.Url != "" { + urlStrings := gxstrings.RegSplit(c.Url, "\\s*[;]+\\s*") for _, urlStr := range urlStrings { serviceUrl, err := common.NewURL(context.Background(), urlStr) if err != nil { @@ -110,32 +110,32 @@ func (refconfig *ReferenceConfig) Refer(impl interface{}) { } if serviceUrl.Protocol == constant.REGISTRY_PROTOCOL { serviceUrl.SubURL = url - refconfig.urls = append(refconfig.urls, &serviceUrl) + c.urls = append(c.urls, &serviceUrl) } else { if serviceUrl.Path == "" { - serviceUrl.Path = "/" + refconfig.id + serviceUrl.Path = "/" + c.id } // merge url need to do newUrl := common.MergeUrl(&serviceUrl, url) - refconfig.urls = append(refconfig.urls, newUrl) + c.urls = append(c.urls, newUrl) } } } else { //2. assemble SubURL from register center's configuration模式 - refconfig.urls = loadRegistries(refconfig.Registry, consumerConfig.Registries, common.CONSUMER) + c.urls = loadRegistries(c.Registry, consumerConfig.Registries, common.CONSUMER) //set url to regUrls - for _, regUrl := range refconfig.urls { + for _, regUrl := range c.urls { regUrl.SubURL = url } } - if len(refconfig.urls) == 1 { - refconfig.invoker = extension.GetProtocol(refconfig.urls[0].Protocol).Refer(*refconfig.urls[0]) + if len(c.urls) == 1 { + c.invoker = extension.GetProtocol(c.urls[0].Protocol).Refer(*c.urls[0]) } else { invokers := []protocol.Invoker{} var regUrl *common.URL - for _, u := range refconfig.urls { + for _, u := range c.urls { invokers = append(invokers, extension.GetProtocol(u.Protocol).Refer(*u)) if u.Protocol == constant.REGISTRY_PROTOCOL { regUrl = u @@ -143,53 +143,53 @@ func (refconfig *ReferenceConfig) Refer(impl interface{}) { } if regUrl != nil { cluster := extension.GetCluster("registryAware") - refconfig.invoker = cluster.Join(directory.NewStaticDirectory(invokers)) + c.invoker = cluster.Join(directory.NewStaticDirectory(invokers)) } else { - cluster := extension.GetCluster(refconfig.Cluster) - refconfig.invoker = cluster.Join(directory.NewStaticDirectory(invokers)) + cluster := extension.GetCluster(c.Cluster) + c.invoker = cluster.Join(directory.NewStaticDirectory(invokers)) } } //create proxy - if refconfig.Async { - callback := GetCallback(refconfig.id) - refconfig.pxy = extension.GetProxyFactory(consumerConfig.ProxyFactory).GetAsyncProxy(refconfig.invoker, callback, url) + if c.Async { + callback := GetCallback(c.id) + c.pxy = extension.GetProxyFactory(consumerConfig.ProxyFactory).GetAsyncProxy(c.invoker, callback, url) } else { - refconfig.pxy = extension.GetProxyFactory(consumerConfig.ProxyFactory).GetProxy(refconfig.invoker, url) + c.pxy = extension.GetProxyFactory(consumerConfig.ProxyFactory).GetProxy(c.invoker, url) } } // @v is service provider implemented RPCService -func (refconfig *ReferenceConfig) Implement(v common.RPCService) { - refconfig.pxy.Implement(v) +func (c *ReferenceConfig) Implement(v common.RPCService) { + c.pxy.Implement(v) } // GetRPCService ... -func (refconfig *ReferenceConfig) GetRPCService() common.RPCService { - return refconfig.pxy.Get() +func (c *ReferenceConfig) GetRPCService() common.RPCService { + return c.pxy.Get() } -func (refconfig *ReferenceConfig) getUrlMap() url.Values { +func (c *ReferenceConfig) getUrlMap() url.Values { urlMap := url.Values{} //first set user params - for k, v := range refconfig.Params { + for k, v := range c.Params { urlMap.Set(k, v) } - urlMap.Set(constant.INTERFACE_KEY, refconfig.InterfaceName) + urlMap.Set(constant.INTERFACE_KEY, c.InterfaceName) urlMap.Set(constant.TIMESTAMP_KEY, strconv.FormatInt(time.Now().Unix(), 10)) - urlMap.Set(constant.CLUSTER_KEY, refconfig.Cluster) - urlMap.Set(constant.LOADBALANCE_KEY, refconfig.Loadbalance) - urlMap.Set(constant.RETRIES_KEY, refconfig.Retries) - urlMap.Set(constant.GROUP_KEY, refconfig.Group) - urlMap.Set(constant.VERSION_KEY, refconfig.Version) - urlMap.Set(constant.GENERIC_KEY, strconv.FormatBool(refconfig.Generic)) + urlMap.Set(constant.CLUSTER_KEY, c.Cluster) + urlMap.Set(constant.LOADBALANCE_KEY, c.Loadbalance) + urlMap.Set(constant.RETRIES_KEY, c.Retries) + urlMap.Set(constant.GROUP_KEY, c.Group) + urlMap.Set(constant.VERSION_KEY, c.Version) + urlMap.Set(constant.GENERIC_KEY, strconv.FormatBool(c.Generic)) urlMap.Set(constant.ROLE_KEY, strconv.Itoa(common.CONSUMER)) - if len(refconfig.RequestTimeout) != 0 { - urlMap.Set(constant.TIMEOUT_KEY, refconfig.RequestTimeout) + if len(c.RequestTimeout) != 0 { + urlMap.Set(constant.TIMEOUT_KEY, c.RequestTimeout) } //getty invoke async or sync - urlMap.Set(constant.ASYNC_KEY, strconv.FormatBool(refconfig.Async)) - urlMap.Set(constant.STICKY_KEY, strconv.FormatBool(refconfig.Sticky)) + urlMap.Set(constant.ASYNC_KEY, strconv.FormatBool(c.Async)) + urlMap.Set(constant.STICKY_KEY, strconv.FormatBool(c.Sticky)) //application info urlMap.Set(constant.APPLICATION_KEY, consumerConfig.ApplicationConfig.Name) @@ -202,12 +202,12 @@ func (refconfig *ReferenceConfig) getUrlMap() url.Values { //filter var defaultReferenceFilter = constant.DEFAULT_REFERENCE_FILTERS - if refconfig.Generic { + if c.Generic { defaultReferenceFilter = constant.GENERIC_REFERENCE_FILTERS + "," + defaultReferenceFilter } - urlMap.Set(constant.REFERENCE_FILTER_KEY, mergeValue(consumerConfig.Filter, refconfig.Filter, defaultReferenceFilter)) + urlMap.Set(constant.REFERENCE_FILTER_KEY, mergeValue(consumerConfig.Filter, c.Filter, defaultReferenceFilter)) - for _, v := range refconfig.Methods { + for _, v := range c.Methods { urlMap.Set("methods."+v.Name+"."+constant.LOADBALANCE_KEY, v.Loadbalance) urlMap.Set("methods."+v.Name+"."+constant.RETRIES_KEY, v.Retries) urlMap.Set("methods."+v.Name+"."+constant.STICKY_KEY, strconv.FormatBool(v.Sticky)) @@ -221,11 +221,11 @@ func (refconfig *ReferenceConfig) getUrlMap() url.Values { } // GenericLoad ... -func (refconfig *ReferenceConfig) GenericLoad(id string) { - genericService := NewGenericService(refconfig.id) +func (c *ReferenceConfig) GenericLoad(id string) { + genericService := NewGenericService(c.id) SetConsumerService(genericService) - refconfig.id = id - refconfig.Refer(genericService) - refconfig.Implement(genericService) + c.id = id + c.Refer(genericService) + c.Implement(genericService) return } diff --git a/config/registry_config.go b/config/registry_config.go index b387f6fdb8755536b20e6e1130d0007938102a08..c347c2c2348018a66114c56a1c982d57d4f2783f 100644 --- a/config/registry_config.go +++ b/config/registry_config.go @@ -117,15 +117,16 @@ func loadRegistries(targetRegistries string, registries map[string]*RegistryConf return urls } -func (regconfig *RegistryConfig) getUrlMap(roleType common.RoleType) url.Values { +func (c *RegistryConfig) getUrlMap(roleType common.RoleType) url.Values { urlMap := url.Values{} - urlMap.Set(constant.GROUP_KEY, regconfig.Group) + urlMap.Set(constant.GROUP_KEY, c.Group) urlMap.Set(constant.ROLE_KEY, strconv.Itoa(int(roleType))) - urlMap.Set(constant.REGISTRY_KEY, regconfig.Protocol) - urlMap.Set(constant.REGISTRY_TIMEOUT_KEY, regconfig.TimeoutStr) - for k, v := range regconfig.Params { + urlMap.Set(constant.REGISTRY_KEY, c.Protocol) + urlMap.Set(constant.REGISTRY_TIMEOUT_KEY, c.TimeoutStr) + for k, v := range c.Params { urlMap.Set(k, v) } + return urlMap } diff --git a/config/service.go b/config/service.go index b2ff15c7895f357b501cb2d066de0a729e4f73a0..b7e7dc2a425b42363d570fc37a70e2e5094e7d9d 100644 --- a/config/service.go +++ b/config/service.go @@ -26,12 +26,12 @@ var ( proServices = map[string]common.RPCService{} // service name -> service ) -// SetConService is called by init() of implement of RPCService +// SetConsumerService is called by init() of implement of RPCService func SetConsumerService(service common.RPCService) { conServices[service.Reference()] = service } -// SetProService is called by init() of implement of RPCService +// SetProviderService is called by init() of implement of RPCService func SetProviderService(service common.RPCService) { proServices[service.Reference()] = service } diff --git a/config/service_config.go b/config/service_config.go index 2e947bb6c322e52c643569c5bc06ca10b2851ec5..92977307ab68282beaebc1d9b0257e864007e9b4 100644 --- a/config/service_config.go +++ b/config/service_config.go @@ -92,7 +92,7 @@ func (c *ServiceConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { return nil } -// The only way to get a new ServiceConfig +// NewServiceConfig: The only way to get a new ServiceConfig func NewServiceConfig(id string, context context.Context) *ServiceConfig { return &ServiceConfig{ @@ -105,58 +105,58 @@ func NewServiceConfig(id string, context context.Context) *ServiceConfig { } // Export ... -func (srvconfig *ServiceConfig) Export() error { +func (c *ServiceConfig) Export() error { // TODO: config center start here // TODO:delay export - if srvconfig.unexported != nil && srvconfig.unexported.Load() { - err := perrors.Errorf("The service %v has already unexported! ", srvconfig.InterfaceName) + if c.unexported != nil && c.unexported.Load() { + err := perrors.Errorf("The service %v has already unexported! ", c.InterfaceName) logger.Errorf(err.Error()) return err } - if srvconfig.unexported != nil && srvconfig.exported.Load() { - logger.Warnf("The service %v has already exported! ", srvconfig.InterfaceName) + if c.unexported != nil && c.exported.Load() { + logger.Warnf("The service %v has already exported! ", c.InterfaceName) return nil } - regUrls := loadRegistries(srvconfig.Registry, providerConfig.Registries, common.PROVIDER) - urlMap := srvconfig.getUrlMap() - protocolConfigs := loadProtocol(srvconfig.Protocol, providerConfig.Protocols) + regUrls := loadRegistries(c.Registry, providerConfig.Registries, common.PROVIDER) + urlMap := c.getUrlMap() + protocolConfigs := loadProtocol(c.Protocol, providerConfig.Protocols) if len(protocolConfigs) == 0 { - logger.Warnf("The service %v's '%v' protocols don't has right protocolConfigs ", srvconfig.InterfaceName, srvconfig.Protocol) + logger.Warnf("The service %v's '%v' protocols don't has right protocolConfigs ", c.InterfaceName, c.Protocol) return nil } for _, proto := range protocolConfigs { // registry the service reflect - methods, err := common.ServiceMap.Register(proto.Name, srvconfig.rpcService) + methods, err := common.ServiceMap.Register(proto.Name, c.rpcService) if err != nil { - err := perrors.Errorf("The service %v export the protocol %v error! Error message is %v .", srvconfig.InterfaceName, proto.Name, err.Error()) + err := perrors.Errorf("The service %v export the protocol %v error! Error message is %v .", c.InterfaceName, proto.Name, err.Error()) logger.Errorf(err.Error()) return err } - url := common.NewURLWithOptions(common.WithPath(srvconfig.id), + url := common.NewURLWithOptions(common.WithPath(c.id), common.WithProtocol(proto.Name), common.WithIp(proto.Ip), common.WithPort(proto.Port), common.WithParams(urlMap), - common.WithParamsValue(constant.BEAN_NAME_KEY, srvconfig.id), + common.WithParamsValue(constant.BEAN_NAME_KEY, c.id), common.WithMethods(strings.Split(methods, ",")), - common.WithToken(srvconfig.Token), + common.WithToken(c.Token), ) if len(regUrls) > 0 { for _, regUrl := range regUrls { regUrl.SubURL = url - srvconfig.cacheMutex.Lock() - if srvconfig.cacheProtocol == nil { + c.cacheMutex.Lock() + if c.cacheProtocol == nil { logger.Infof(fmt.Sprintf("First load the registry protocol , url is {%v}!", url)) - srvconfig.cacheProtocol = extension.GetProtocol("registry") + c.cacheProtocol = extension.GetProtocol("registry") } - srvconfig.cacheMutex.Unlock() + c.cacheMutex.Unlock() invoker := extension.GetProxyFactory(providerConfig.ProxyFactory).GetInvoker(*regUrl) - exporter := srvconfig.cacheProtocol.Export(invoker) + exporter := c.cacheProtocol.Export(invoker) if exporter == nil { panic(perrors.New(fmt.Sprintf("Registry protocol new exporter error,registry is {%v},url is {%v}", regUrl, url))) } @@ -175,24 +175,24 @@ func (srvconfig *ServiceConfig) Export() error { } // Implement ... -func (srvconfig *ServiceConfig) Implement(s common.RPCService) { - srvconfig.rpcService = s +func (c *ServiceConfig) Implement(s common.RPCService) { + c.rpcService = s } -func (srvconfig *ServiceConfig) getUrlMap() url.Values { +func (c *ServiceConfig) getUrlMap() url.Values { urlMap := url.Values{} // first set user params - for k, v := range srvconfig.Params { + for k, v := range c.Params { urlMap.Set(k, v) } - urlMap.Set(constant.INTERFACE_KEY, srvconfig.InterfaceName) + urlMap.Set(constant.INTERFACE_KEY, c.InterfaceName) urlMap.Set(constant.TIMESTAMP_KEY, strconv.FormatInt(time.Now().Unix(), 10)) - urlMap.Set(constant.CLUSTER_KEY, srvconfig.Cluster) - urlMap.Set(constant.LOADBALANCE_KEY, srvconfig.Loadbalance) - urlMap.Set(constant.WARMUP_KEY, srvconfig.Warmup) - urlMap.Set(constant.RETRIES_KEY, srvconfig.Retries) - urlMap.Set(constant.GROUP_KEY, srvconfig.Group) - urlMap.Set(constant.VERSION_KEY, srvconfig.Version) + urlMap.Set(constant.CLUSTER_KEY, c.Cluster) + urlMap.Set(constant.LOADBALANCE_KEY, c.Loadbalance) + urlMap.Set(constant.WARMUP_KEY, c.Warmup) + urlMap.Set(constant.RETRIES_KEY, c.Retries) + urlMap.Set(constant.GROUP_KEY, c.Group) + urlMap.Set(constant.VERSION_KEY, c.Version) urlMap.Set(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER)) // application info urlMap.Set(constant.APPLICATION_KEY, providerConfig.ApplicationConfig.Name) @@ -204,22 +204,22 @@ func (srvconfig *ServiceConfig) getUrlMap() url.Values { urlMap.Set(constant.ENVIRONMENT_KEY, providerConfig.ApplicationConfig.Environment) // filter - urlMap.Set(constant.SERVICE_FILTER_KEY, mergeValue(providerConfig.Filter, srvconfig.Filter, constant.DEFAULT_SERVICE_FILTERS)) + urlMap.Set(constant.SERVICE_FILTER_KEY, mergeValue(providerConfig.Filter, c.Filter, constant.DEFAULT_SERVICE_FILTERS)) // filter special config - urlMap.Set(constant.ACCESS_LOG_KEY, srvconfig.AccessLog) + urlMap.Set(constant.ACCESS_LOG_KEY, c.AccessLog) // tps limiter - urlMap.Set(constant.TPS_LIMIT_STRATEGY_KEY, srvconfig.TpsLimitStrategy) - urlMap.Set(constant.TPS_LIMIT_INTERVAL_KEY, srvconfig.TpsLimitInterval) - urlMap.Set(constant.TPS_LIMIT_RATE_KEY, srvconfig.TpsLimitRate) - urlMap.Set(constant.TPS_LIMITER_KEY, srvconfig.TpsLimiter) - urlMap.Set(constant.TPS_REJECTED_EXECUTION_HANDLER_KEY, srvconfig.TpsLimitRejectedHandler) + urlMap.Set(constant.TPS_LIMIT_STRATEGY_KEY, c.TpsLimitStrategy) + urlMap.Set(constant.TPS_LIMIT_INTERVAL_KEY, c.TpsLimitInterval) + urlMap.Set(constant.TPS_LIMIT_RATE_KEY, c.TpsLimitRate) + urlMap.Set(constant.TPS_LIMITER_KEY, c.TpsLimiter) + urlMap.Set(constant.TPS_REJECTED_EXECUTION_HANDLER_KEY, c.TpsLimitRejectedHandler) // execute limit filter - urlMap.Set(constant.EXECUTE_LIMIT_KEY, srvconfig.ExecuteLimit) - urlMap.Set(constant.EXECUTE_REJECTED_EXECUTION_HANDLER_KEY, srvconfig.ExecuteLimitRejectedHandler) + urlMap.Set(constant.EXECUTE_LIMIT_KEY, c.ExecuteLimit) + urlMap.Set(constant.EXECUTE_REJECTED_EXECUTION_HANDLER_KEY, c.ExecuteLimitRejectedHandler) - for _, v := range srvconfig.Methods { + for _, v := range c.Methods { prefix := "methods." + v.Name + "." urlMap.Set(prefix+constant.LOADBALANCE_KEY, v.Loadbalance) urlMap.Set(prefix+constant.RETRIES_KEY, v.Retries) diff --git a/config_center/apollo/factory.go b/config_center/apollo/factory.go index 47011be4a3e0e421ca7a314620a3547d665111c8..a5a69e121598bea4194398423775a99f04b61ced 100644 --- a/config_center/apollo/factory.go +++ b/config_center/apollo/factory.go @@ -20,7 +20,7 @@ package apollo import ( "github.com/apache/dubbo-go/common" "github.com/apache/dubbo-go/common/extension" - . "github.com/apache/dubbo-go/config_center" + "github.com/apache/dubbo-go/config_center" "github.com/apache/dubbo-go/config_center/parser" ) @@ -28,13 +28,13 @@ func init() { extension.SetConfigCenterFactory("apollo", createDynamicConfigurationFactory) } -func createDynamicConfigurationFactory() DynamicConfigurationFactory { +func createDynamicConfigurationFactory() config_center.DynamicConfigurationFactory { return &apolloConfigurationFactory{} } type apolloConfigurationFactory struct{} -func (f *apolloConfigurationFactory) GetDynamicConfiguration(url *common.URL) (DynamicConfiguration, error) { +func (f *apolloConfigurationFactory) GetDynamicConfiguration(url *common.URL) (config_center.DynamicConfiguration, error) { dynamicConfiguration, err := newApolloConfiguration(url) if err != nil { return nil, err diff --git a/config_center/apollo/impl.go b/config_center/apollo/impl.go index f72f988e6c1426c9f0e481bff99e0ce78263330e..85dff14a1ec9ba3905890bf37dc1e1827d59d80f 100644 --- a/config_center/apollo/impl.go +++ b/config_center/apollo/impl.go @@ -32,7 +32,7 @@ import ( import ( "github.com/apache/dubbo-go/common" "github.com/apache/dubbo-go/common/constant" - . "github.com/apache/dubbo-go/config_center" + cc "github.com/apache/dubbo-go/config_center" "github.com/apache/dubbo-go/config_center/parser" "github.com/apache/dubbo-go/remoting" ) @@ -58,7 +58,7 @@ func newApolloConfiguration(url *common.URL) (*apolloConfiguration, error) { configCluster := url.GetParam(constant.CONFIG_CLUSTER_KEY, "") appId := url.GetParam(constant.CONFIG_APP_ID_KEY, "") - namespaces := getProperties(url.GetParam(constant.CONFIG_NAMESPACE_KEY, DEFAULT_GROUP)) + namespaces := getProperties(url.GetParam(constant.CONFIG_NAMESPACE_KEY, cc.DEFAULT_GROUP)) c.appConf = &agollo.AppConfig{ AppId: appId, Cluster: configCluster, @@ -84,8 +84,8 @@ func getChangeType(change agollo.ConfigChangeType) remoting.EventType { } } -func (c *apolloConfiguration) AddListener(key string, listener ConfigurationListener, opts ...Option) { - k := &Options{} +func (c *apolloConfiguration) AddListener(key string, listener cc.ConfigurationListener, opts ...cc.Option) { + k := &cc.Options{} for _, opt := range opts { opt(k) } @@ -95,8 +95,8 @@ func (c *apolloConfiguration) AddListener(key string, listener ConfigurationList l.(*apolloListener).AddListener(listener) } -func (c *apolloConfiguration) RemoveListener(key string, listener ConfigurationListener, opts ...Option) { - k := &Options{} +func (c *apolloConfiguration) RemoveListener(key string, listener cc.ConfigurationListener, opts ...cc.Option) { + k := &cc.Options{} for _, opt := range opts { opt(k) } @@ -116,7 +116,7 @@ func getNamespaceName(namespace string, configFileFormat agollo.ConfigFileFormat return fmt.Sprintf(apolloConfigFormat, namespace, configFileFormat) } -func (c *apolloConfiguration) GetInternalProperty(key string, opts ...Option) (string, error) { +func (c *apolloConfiguration) GetInternalProperty(key string, opts ...cc.Option) (string, error) { config := agollo.GetConfig(c.appConf.NamespaceName) if config == nil { return "", errors.New(fmt.Sprintf("nothing in namespace:%s ", key)) @@ -124,11 +124,11 @@ func (c *apolloConfiguration) GetInternalProperty(key string, opts ...Option) (s return config.GetStringValue(key, ""), nil } -func (c *apolloConfiguration) GetRule(key string, opts ...Option) (string, error) { +func (c *apolloConfiguration) GetRule(key string, opts ...cc.Option) (string, error) { return c.GetInternalProperty(key, opts...) } -func (c *apolloConfiguration) GetProperties(key string, opts ...Option) (string, error) { +func (c *apolloConfiguration) GetProperties(key string, opts ...cc.Option) (string, error) { /** * when group is not null, we are getting startup configs(config file) from Config Center, for example: * key=dubbo.propertie diff --git a/config_center/apollo/listener.go b/config_center/apollo/listener.go index 1355be0b76b5c886e81861ef3f846cede5f9e0e7..2b366206199f6e5c76dfb3bb0ac5b1ca7d5b2067 100644 --- a/config_center/apollo/listener.go +++ b/config_center/apollo/listener.go @@ -48,6 +48,7 @@ func NewApolloListener() *apolloListener { } } +// AddListener ... func (al *apolloListener) AddListener(l config_center.ConfigurationListener) { if _, ok := al.listeners[l]; !ok { al.listeners[l] = struct{}{} @@ -55,6 +56,7 @@ func (al *apolloListener) AddListener(l config_center.ConfigurationListener) { } } +// RemoveListener ... func (al *apolloListener) RemoveListener(l config_center.ConfigurationListener) { delete(al.listeners, l) } diff --git a/config_center/configurator/mock.go b/config_center/configurator/mock.go index cf418924893bdf6407d3bc082cb18b2bd3f78022..d294b9195db9cfe60056bc29ec26816f740ea396 100644 --- a/config_center/configurator/mock.go +++ b/config_center/configurator/mock.go @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package configurator import ( @@ -31,10 +32,12 @@ type mockConfigurator struct { configuratorUrl *common.URL } +// GetUrl ... func (c *mockConfigurator) GetUrl() *common.URL { return c.configuratorUrl } +// Configure ... func (c *mockConfigurator) Configure(url *common.URL) { if cluster := c.GetUrl().GetParam(constant.CLUSTER_KEY, ""); cluster != "" { url.SetParam(constant.CLUSTER_KEY, cluster) diff --git a/config_center/configurator/override.go b/config_center/configurator/override.go index 8e8fe5cc1ab91eb779a73f85e3a71984f0ba6798..d0b23ef2f20d065135547536c2cebcec3eec0ce1 100644 --- a/config_center/configurator/override.go +++ b/config_center/configurator/override.go @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package configurator import ( diff --git a/config_center/configurator/override_test.go b/config_center/configurator/override_test.go index a585f4217f81a5d600ec9a48c12b3b47ff2d5322..b8f417b4602e135d114be99637061851088d4e44 100644 --- a/config_center/configurator/override_test.go +++ b/config_center/configurator/override_test.go @@ -38,6 +38,7 @@ func Test_configureVerison2p6(t *testing.T) { assert.Equal(t, "override", configurator.GetUrl().Protocol) providerUrl, err := common.NewURL(context.Background(), "jsonrpc://127.0.0.1:20001/com.ikurento.user.UserProvider?anyhost=true&app.version=0.0.1&application=BDTService&category=providers&cluster=failover&dubbo=dubbo-provider-golang-2.6.0&environment=dev&group=&interface=com.ikurento.user.UserProvider&ip=10.32.20.124&loadbalance=random&methods.GetUser.loadbalance=random&methods.GetUser.retries=1&methods.GetUser.weight=0&module=dubbogo+user-info+server&name=BDTService&organization=ikurento.com&owner=ZX&pid=64225&retries=0&service.filter=echo&side=provider×tamp=1562076628&version=&warmup=100") + assert.NoError(t, err) configurator.Configure(&providerUrl) assert.Equal(t, "failfast", providerUrl.GetParam(constant.CLUSTER_KEY, "")) @@ -49,6 +50,7 @@ func Test_configureVerisonOverrideAddr(t *testing.T) { assert.Equal(t, "override", configurator.GetUrl().Protocol) providerUrl, err := common.NewURL(context.Background(), "jsonrpc://127.0.0.1:20001/com.ikurento.user.UserProvider?anyhost=true&app.version=0.0.1&application=BDTService&category=providers&cluster=failover&dubbo=dubbo-provider-golang-2.6.0&environment=dev&group=&interface=com.ikurento.user.UserProvider&ip=10.32.20.124&loadbalance=random&methods.GetUser.loadbalance=random&methods.GetUser.retries=1&methods.GetUser.weight=0&module=dubbogo+user-info+server&name=BDTService&organization=ikurento.com&owner=ZX&pid=64225&retries=0&service.filter=echo&side=provider×tamp=1562076628&version=&warmup=100") + assert.NoError(t, err) configurator.Configure(&providerUrl) assert.Equal(t, "failover", providerUrl.GetParam(constant.CLUSTER_KEY, "")) @@ -60,6 +62,7 @@ func Test_configureVerison2p6WithIp(t *testing.T) { assert.Equal(t, "override", configurator.GetUrl().Protocol) providerUrl, err := common.NewURL(context.Background(), "jsonrpc://127.0.0.1:20001/com.ikurento.user.UserProvider?anyhost=true&app.version=0.0.1&application=BDTService&category=providers&cluster=failover&dubbo=dubbo-provider-golang-2.6.0&environment=dev&group=&interface=com.ikurento.user.UserProvider&ip=10.32.20.124&loadbalance=random&methods.GetUser.loadbalance=random&methods.GetUser.retries=1&methods.GetUser.weight=0&module=dubbogo+user-info+server&name=BDTService&organization=ikurento.com&owner=ZX&pid=64225&retries=0&service.filter=echo&side=provider×tamp=1562076628&version=&warmup=100") + assert.NoError(t, err) configurator.Configure(&providerUrl) assert.Equal(t, "failfast", providerUrl.GetParam(constant.CLUSTER_KEY, "")) @@ -71,6 +74,7 @@ func Test_configureVerison2p7(t *testing.T) { configurator := extension.GetConfigurator("default", &url) providerUrl, err := common.NewURL(context.Background(), "jsonrpc://127.0.0.1:20001/com.ikurento.user.UserProvider?anyhost=true&app.version=0.0.1&application=BDTService&category=providers&cluster=failover&dubbo=dubbo-provider-golang-2.6.0&environment=dev&group=&interface=com.ikurento.user.UserProvider&ip=10.32.20.124&loadbalance=random&methods.GetUser.loadbalance=random&methods.GetUser.retries=1&methods.GetUser.weight=0&module=dubbogo+user-info+server&name=BDTService&organization=ikurento.com&owner=ZX&pid=64225&retries=0&service.filter=echo&side=provider×tamp=1562076628&version=&warmup=100") + assert.NoError(t, err) configurator.Configure(&providerUrl) assert.Equal(t, "failfast", providerUrl.GetParam(constant.CLUSTER_KEY, "")) diff --git a/config_center/dynamic_configuration.go b/config_center/dynamic_configuration.go index 4e815234bb76c89860cb9bbbb213b79bd23e9ee3..90cd3bbb1d502a0e9ceb8fed5c94a4091bc0578e 100644 --- a/config_center/dynamic_configuration.go +++ b/config_center/dynamic_configuration.go @@ -28,8 +28,12 @@ import ( ////////////////////////////////////////// // DynamicConfiguration ////////////////////////////////////////// -const DEFAULT_GROUP = "dubbo" -const DEFAULT_CONFIG_TIMEOUT = "10s" +const ( + // DEFAULT_GROUP: default group + DEFAULT_GROUP = "dubbo" + // DEFAULT_CONFIG_TIMEOUT: default config timeout + DEFAULT_CONFIG_TIMEOUT = "10s" +) // DynamicConfiguration ... type DynamicConfiguration interface { diff --git a/config_center/mock_dynamic_config.go b/config_center/mock_dynamic_config.go index f0a5dfec1ab6af64b2227acf62c2fed788b5f5bf..6f66570540a696abfd4050646d0bd4ec3f336ce4 100644 --- a/config_center/mock_dynamic_config.go +++ b/config_center/mock_dynamic_config.go @@ -103,7 +103,7 @@ func (c *MockDynamicConfiguration) GetConfig(key string, opts ...Option) (string return c.content, nil } -//For zookeeper, getConfig and getConfigs have the same meaning. +// GetConfigs: For zookeeper, getConfig and getConfigs have the same meaning. func (c *MockDynamicConfiguration) GetConfigs(key string, opts ...Option) (string, error) { return c.GetConfig(key, opts...) } @@ -123,7 +123,7 @@ func (c *MockDynamicConfiguration) GetProperties(key string, opts ...Option) (st return c.content, nil } -//For zookeeper, getConfig and getConfigs have the same meaning. +// GetInternalProperty: For zookeeper, getConfig and getConfigs have the same meaning. func (c *MockDynamicConfiguration) GetInternalProperty(key string, opts ...Option) (string, error) { return c.GetProperties(key, opts...) } diff --git a/config_center/parser/configuration_parser.go b/config_center/parser/configuration_parser.go index b0c0db34bc8a8c4dfb68c3493e7ed772bb6f54d1..55f23225e607721d867c348f161d8cdd7d74fc21 100644 --- a/config_center/parser/configuration_parser.go +++ b/config_center/parser/configuration_parser.go @@ -36,8 +36,10 @@ import ( ) const ( + // ScopeApplication ... ScopeApplication = "application" - GeneralType = "general" + // GeneralType ... + GeneralType = "general" ) // ConfigurationParser ... diff --git a/config_center/zookeeper/impl.go b/config_center/zookeeper/impl.go index 504d4910581aff52afa74b13fdfce61c9170ca48..b0274d6a8a736d2c561c520b533b381bb85ec0e1 100644 --- a/config_center/zookeeper/impl.go +++ b/config_center/zookeeper/impl.go @@ -37,7 +37,10 @@ import ( "github.com/apache/dubbo-go/remoting/zookeeper" ) -const ZkClient = "zk config_center" +const ( + // ZkClient: zookeeper client name + ZkClient = "zk config_center" +) type zookeeperDynamicConfiguration struct { url *common.URL @@ -156,57 +159,57 @@ func (c *zookeeperDynamicConfiguration) SetParser(p parser.ConfigurationParser) c.parser = p } -func (r *zookeeperDynamicConfiguration) ZkClient() *zookeeper.ZookeeperClient { - return r.client +func (c *zookeeperDynamicConfiguration) ZkClient() *zookeeper.ZookeeperClient { + return c.client } -func (r *zookeeperDynamicConfiguration) SetZkClient(client *zookeeper.ZookeeperClient) { - r.client = client +func (c *zookeeperDynamicConfiguration) SetZkClient(client *zookeeper.ZookeeperClient) { + c.client = client } -func (r *zookeeperDynamicConfiguration) ZkClientLock() *sync.Mutex { - return &r.cltLock +func (c *zookeeperDynamicConfiguration) ZkClientLock() *sync.Mutex { + return &c.cltLock } -func (r *zookeeperDynamicConfiguration) WaitGroup() *sync.WaitGroup { - return &r.wg +func (c *zookeeperDynamicConfiguration) WaitGroup() *sync.WaitGroup { + return &c.wg } -func (r *zookeeperDynamicConfiguration) GetDone() chan struct{} { - return r.done +func (c *zookeeperDynamicConfiguration) GetDone() chan struct{} { + return c.done } -func (r *zookeeperDynamicConfiguration) GetUrl() common.URL { - return *r.url +func (c *zookeeperDynamicConfiguration) GetUrl() common.URL { + return *c.url } -func (r *zookeeperDynamicConfiguration) Destroy() { - if r.listener != nil { - r.listener.Close() +func (c *zookeeperDynamicConfiguration) Destroy() { + if c.listener != nil { + c.listener.Close() } - close(r.done) - r.wg.Wait() - r.closeConfigs() + close(c.done) + c.wg.Wait() + c.closeConfigs() } -func (r *zookeeperDynamicConfiguration) IsAvailable() bool { +func (c *zookeeperDynamicConfiguration) IsAvailable() bool { select { - case <-r.done: + case <-c.done: return false default: return true } } -func (r *zookeeperDynamicConfiguration) closeConfigs() { - r.cltLock.Lock() - defer r.cltLock.Unlock() +func (c *zookeeperDynamicConfiguration) closeConfigs() { + c.cltLock.Lock() + defer c.cltLock.Unlock() logger.Infof("begin to close provider zk client") // Close the old client first to close the tmp node - r.client.Close() - r.client = nil + c.client.Close() + c.client = nil } -func (r *zookeeperDynamicConfiguration) RestartCallBack() bool { +func (c *zookeeperDynamicConfiguration) RestartCallBack() bool { return true } diff --git a/filter/filter.go b/filter/filter.go index 6c9e4455476b42d97718b5364d9687ac9671f687..0da0d800fc126fc562b06218bdec022c6adaf8f6 100644 --- a/filter/filter.go +++ b/filter/filter.go @@ -24,7 +24,7 @@ import ( "github.com/apache/dubbo-go/protocol" ) -// Extension - Filter +// Filter: Extension - Filter type Filter interface { Invoke(context.Context, protocol.Invoker, protocol.Invocation) protocol.Result OnResponse(context.Context, protocol.Result, protocol.Invoker, protocol.Invocation) protocol.Result diff --git a/filter/filter_impl/access_log_filter.go b/filter/filter_impl/access_log_filter.go index a07f479742a578038f1beeeb12c4950fe850ba32..a2367254d9b7367664ea04eb3556fc9612cb411f 100644 --- a/filter/filter_impl/access_log_filter.go +++ b/filter/filter_impl/access_log_filter.go @@ -35,13 +35,19 @@ import ( const ( //used in URL. - FileDateFormat = "2006-01-02" + // FileDateFormat ... + FileDateFormat = "2006-01-02" + // MessageDateLayout ... MessageDateLayout = "2006-01-02 15:04:05" - LogMaxBuffer = 5000 - LogFileMode = 0600 + // LogMaxBuffer ... + LogMaxBuffer = 5000 + // LogFileMode ... + LogFileMode = 0600 // those fields are the data collected by this filter - Types = "types" + // Types ... + Types = "types" + // Arguments ... Arguments = "arguments" ) diff --git a/filter/filter_impl/echo_filter.go b/filter/filter_impl/echo_filter.go index 4ccecc2dbc68383071b789692babadac2c80c7fd..e1181e412a0a96cd8a175652ba5ad85e78a12d2a 100644 --- a/filter/filter_impl/echo_filter.go +++ b/filter/filter_impl/echo_filter.go @@ -20,6 +20,7 @@ package filter_impl import ( "context" ) + import ( "github.com/apache/dubbo-go/common/constant" "github.com/apache/dubbo-go/common/extension" @@ -29,6 +30,7 @@ import ( ) const ( + // ECHO: echo module name ECHO = "echo" ) @@ -36,6 +38,7 @@ func init() { extension.SetFilter(ECHO, GetFilter) } +// EchoFilter: // RPCService need a Echo method in consumer, if you want to use EchoFilter // eg: // Echo func(ctx context.Context, arg interface{}, rsp *Xxx) error diff --git a/filter/filter_impl/execute_limit_filter.go b/filter/filter_impl/execute_limit_filter.go index f9dab06ebe7d7e02be5b6ae23587495d2df7d95b..4c5805a79b6dffc197d9605020466ebce27dac4c 100644 --- a/filter/filter_impl/execute_limit_filter.go +++ b/filter/filter_impl/execute_limit_filter.go @@ -37,14 +37,16 @@ import ( "github.com/apache/dubbo-go/protocol" ) -const name = "execute" +const ( + name = "execute" +) func init() { extension.SetFilter(name, GetExecuteLimitFilter) } /** - * The filter will limit the number of in-progress request and it's thread-safe. + * ExecuteLimitFilter: The filter will limit the number of in-progress request and it's thread-safe. * example: * "UserProvider": * registry: "hangzhouzk" diff --git a/filter/filter_impl/generic_filter.go b/filter/filter_impl/generic_filter.go index fec1c3aa51451d5cb18e037b14ec778393072a93..9dfd125547c4de0628058a8e37dac71f9df5e1ae 100644 --- a/filter/filter_impl/generic_filter.go +++ b/filter/filter_impl/generic_filter.go @@ -22,9 +22,11 @@ import ( "reflect" "strings" ) + import ( hessian "github.com/apache/dubbo-go-hessian2" ) + import ( "github.com/apache/dubbo-go/common/constant" "github.com/apache/dubbo-go/common/extension" @@ -34,6 +36,7 @@ import ( ) const ( + // GENERIC: generic module name GENERIC = "generic" ) diff --git a/filter/filter_impl/generic_filter_test.go b/filter/filter_impl/generic_filter_test.go index c4dc19270e8a81d65e8b56664d4ab0af204f29c5..22948353fc16a99696a85489ce5df7dc9b18a7ba 100644 --- a/filter/filter_impl/generic_filter_test.go +++ b/filter/filter_impl/generic_filter_test.go @@ -21,6 +21,7 @@ import ( "reflect" "testing" ) + import ( "github.com/stretchr/testify/assert" ) diff --git a/filter/filter_impl/generic_service_filter.go b/filter/filter_impl/generic_service_filter.go index c577ae2077fbd042def0a7209459ec59c62b684f..6272df6b39b0c18a77721f3a8c9e92618133aa6c 100644 --- a/filter/filter_impl/generic_service_filter.go +++ b/filter/filter_impl/generic_service_filter.go @@ -40,7 +40,9 @@ import ( ) const ( - GENERIC_SERVICE = "generic_service" + // GENERIC_SERVICE ... + GENERIC_SERVICE = "generic_service" + // GENERIC_SERIALIZATION_DEFAULT ... GENERIC_SERIALIZATION_DEFAULT = "true" ) diff --git a/filter/filter_impl/generic_service_filter_test.go b/filter/filter_impl/generic_service_filter_test.go index 8211e717564465bba3009772715a3ab1cd3322dd..0ba5e27d04099514063c4075944602010046f61e 100644 --- a/filter/filter_impl/generic_service_filter_test.go +++ b/filter/filter_impl/generic_service_filter_test.go @@ -52,6 +52,7 @@ func (c *TestStruct) JavaClassName() string { type TestService struct { } +// MethodOne ... func (ts *TestService) MethodOne(ctx context.Context, test1 *TestStruct, test2 []TestStruct, test3 interface{}, test4 []interface{}, test5 *string) (*TestStruct, error) { if test1 == nil { @@ -72,6 +73,7 @@ func (ts *TestService) MethodOne(ctx context.Context, test1 *TestStruct, test2 [ return &TestStruct{}, nil } +// Reference ... func (s *TestService) Reference() string { return "com.test.Path" } diff --git a/filter/filter_impl/hystrix_filter.go b/filter/filter_impl/hystrix_filter.go index c2834480e72b81d1c8d5d8973db06e9487692118..9fd97b57b677c9aa8ec492151df9aace6dc78b62 100644 --- a/filter/filter_impl/hystrix_filter.go +++ b/filter/filter_impl/hystrix_filter.go @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package filter_impl import ( @@ -36,9 +37,12 @@ import ( ) const ( + // HYSTRIX_CONSUMER ... HYSTRIX_CONSUMER = "hystrix_consumer" + // HYSTRIX_PROVIDER ... HYSTRIX_PROVIDER = "hystrix_provider" - HYSTRIX = "hystrix" + // HYSTRIX ... + HYSTRIX = "hystrix" ) var ( diff --git a/filter/filter_impl/hystrix_filter_test.go b/filter/filter_impl/hystrix_filter_test.go index 894573036ae6dd9edca88e8e4cdd92e7643abcb5..66c17d920c14e23f1562773c152e99955a48bfb9 100644 --- a/filter/filter_impl/hystrix_filter_test.go +++ b/filter/filter_impl/hystrix_filter_test.go @@ -21,11 +21,13 @@ import ( "regexp" "testing" ) + import ( "github.com/afex/hystrix-go/hystrix" "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) + import ( "github.com/apache/dubbo-go/protocol" "github.com/apache/dubbo-go/protocol/invocation" @@ -126,9 +128,9 @@ type testMockSuccessInvoker struct { protocol.BaseInvoker } -func (iv *testMockSuccessInvoker) Invoke(context context.Context, invocation protocol.Invocation) protocol.Result { +func (iv *testMockSuccessInvoker) Invoke(_ context.Context, _ protocol.Invocation) protocol.Result { return &protocol.RPCResult{ - Rest: "Sucess", + Rest: "Success", Err: nil, } } @@ -137,7 +139,7 @@ type testMockFailInvoker struct { protocol.BaseInvoker } -func (iv *testMockFailInvoker) Invoke(ctx context.Context, invocation protocol.Invocation) protocol.Result { +func (iv *testMockFailInvoker) Invoke(_ context.Context, _ protocol.Invocation) protocol.Result { return &protocol.RPCResult{ Err: errors.Errorf("exception"), } diff --git a/filter/filter_impl/token_filter.go b/filter/filter_impl/token_filter.go index 2340e7271fb6ae0dac582341c3537931b7fbc4aa..4605416c40a616361868c313881ae784257e6742 100644 --- a/filter/filter_impl/token_filter.go +++ b/filter/filter_impl/token_filter.go @@ -34,6 +34,7 @@ import ( ) const ( + // TOKEN ... TOKEN = "token" ) diff --git a/filter/filter_impl/tps/tps_limit_fix_window_strategy.go b/filter/filter_impl/tps/tps_limit_fix_window_strategy.go index a985724028835f236e8db6c7dd9220b1c5952fbe..96eede8531b13cbd564726d50d12dd20e3c3e29c 100644 --- a/filter/filter_impl/tps/tps_limit_fix_window_strategy.go +++ b/filter/filter_impl/tps/tps_limit_fix_window_strategy.go @@ -29,6 +29,7 @@ import ( ) const ( + // FixedWindowKey ... FixedWindowKey = "fixedWindow" ) @@ -39,6 +40,7 @@ func init() { } /** + * FixedWindowTpsLimitStrategyImpl: * It's the same as default implementation in Java * It's not a thread-safe implementation. * It you want to use the thread-safe implementation, please use ThreadSafeFixedWindowTpsLimitStrategyImpl diff --git a/filter/filter_impl/tps/tps_limit_sliding_window_strategy.go b/filter/filter_impl/tps/tps_limit_sliding_window_strategy.go index c647380641676b8992df332a81406c331d1d5bce..251b11e23b8617b0f4b707ce7df6aecc1b997a20 100644 --- a/filter/filter_impl/tps/tps_limit_sliding_window_strategy.go +++ b/filter/filter_impl/tps/tps_limit_sliding_window_strategy.go @@ -33,6 +33,7 @@ func init() { } /** + * SlidingWindowTpsLimitStrategyImpl: * it's thread-safe. * "UserProvider": * registry: "hangzhouzk" diff --git a/filter/filter_impl/tps/tps_limit_thread_safe_fix_window_strategy.go b/filter/filter_impl/tps/tps_limit_thread_safe_fix_window_strategy.go index ee0558dd29c641ec4f4dccd843e82c9486d5ecd8..259cbfcd07bcf5296a9134346a94651bcccc087b 100644 --- a/filter/filter_impl/tps/tps_limit_thread_safe_fix_window_strategy.go +++ b/filter/filter_impl/tps/tps_limit_thread_safe_fix_window_strategy.go @@ -33,6 +33,7 @@ func init() { } /** + * ThreadSafeFixedWindowTpsLimitStrategyImpl: * it's the thread-safe implementation. * Also, it's a thread-safe decorator of FixedWindowTpsLimitStrategyImpl * "UserProvider": diff --git a/filter/filter_impl/tps/tps_limiter_method_service.go b/filter/filter_impl/tps/tps_limiter_method_service.go index 49f785f354031b1d130f7316d540a9b4f41f1a05..709bb68c42a2dcb703cad1bbf0da7339d9f89c91 100644 --- a/filter/filter_impl/tps/tps_limiter_method_service.go +++ b/filter/filter_impl/tps/tps_limiter_method_service.go @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package tps import ( @@ -42,6 +43,7 @@ func init() { } /** + * MethodServiceTpsLimiterImpl: * This implementation allows developer to config both method-level and service-level tps limiter. * for example: * "UserProvider": diff --git a/filter/filter_impl/tracing_filter_test.go b/filter/filter_impl/tracing_filter_test.go index 30d9d2b7dde318e2ca86127ba480c9a53d7e6f66..c6d6673f3a45e7d73ffd71373b5a7a2860d36a52 100644 --- a/filter/filter_impl/tracing_filter_test.go +++ b/filter/filter_impl/tracing_filter_test.go @@ -59,7 +59,6 @@ func TestTracingFilter_Invoke(t *testing.T) { // has previous span tf.Invoke(ctx, invoker, inv) - ctx = context.Background() // has remote ctx ctx = context.WithValue(context.Background(), constant.TRACING_REMOTE_SPAN_CTX, span.Context()) tf.Invoke(ctx, invoker, inv) diff --git a/filter/rejected_execution_handler.go b/filter/rejected_execution_handler.go index ce95b54b14d01e0aec6f6089799df8378b5bcca5..2507596e9818082833616cd0b200f8a1c6c9015c 100644 --- a/filter/rejected_execution_handler.go +++ b/filter/rejected_execution_handler.go @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package filter import ( @@ -22,6 +23,7 @@ import ( ) /** + * RejectedExecutionHandler: * If the invocation cannot pass any validation in filter, like ExecuteLimitFilter and TpsLimitFilter, * the implementation will be used. * The common case is that sometimes you want to return the default value when the request was rejected. diff --git a/filter/tps_limit_strategy.go b/filter/tps_limit_strategy.go index ad7133ca69468b348e76858c493b434114ce8c11..f002ab2ded2e631128fc22bff20668d68d66f164 100644 --- a/filter/tps_limit_strategy.go +++ b/filter/tps_limit_strategy.go @@ -18,7 +18,7 @@ package filter /* - * please register your implementation by invoking SetTpsLimitStrategy + * TpsLimitStrategy: please register your implementation by invoking SetTpsLimitStrategy * "UserProvider": * registry: "hangzhouzk" * protocol : "dubbo" diff --git a/filter/tps_limiter.go b/filter/tps_limiter.go index 1d2b2341ac7d9b12f75d373909b0baa58bc7295f..584b22922de52a6035b1c9dc90cb5960c486b346 100644 --- a/filter/tps_limiter.go +++ b/filter/tps_limiter.go @@ -23,7 +23,7 @@ import ( ) /* - * please register your implementation by invoking SetTpsLimiter + * TpsLimiter: please register your implementation by invoking SetTpsLimiter * The usage, for example: * "UserProvider": * registry: "hangzhouzk" diff --git a/protocol/dubbo/client.go b/protocol/dubbo/client.go index a39c271a4ad77eda39dba5cf5bd05f57e1c0c5b0..a9b2981f1d71f8d72f962abef1dc33dc667ac5da 100644 --- a/protocol/dubbo/client.go +++ b/protocol/dubbo/client.go @@ -191,13 +191,13 @@ func NewResponse(reply interface{}, atta map[string]string) *Response { } } -// call one way +// CallOneway: call one way func (c *Client) CallOneway(request *Request) error { return perrors.WithStack(c.call(CT_OneWay, request, NewResponse(nil, nil), nil)) } -// if @response is nil, the transport layer will get the response without notify the invoker. +// Call: if @response is nil, the transport layer will get the response without notify the invoker. func (c *Client) Call(request *Request, response *Response) error { ct := CT_TwoWay diff --git a/protocol/dubbo/codec.go b/protocol/dubbo/codec.go index 64d9477ce543d4151812f3c40411b44cce0d1203..c626053943fe1cbf31de6f6930eef7649ff9ed9c 100644 --- a/protocol/dubbo/codec.go +++ b/protocol/dubbo/codec.go @@ -34,6 +34,7 @@ import ( type SerialID byte const ( + // S_Dubbo: dubbo serial id S_Dubbo SerialID = 2 ) @@ -41,9 +42,12 @@ const ( type CallType int32 const ( + // CT_UNKNOWN: unknown call type CT_UNKNOWN CallType = 0 - CT_OneWay CallType = 1 - CT_TwoWay CallType = 2 + // CT_OneWay: call one way + CT_OneWay CallType = 1 + // CT_TwoWay: call in request/response + CT_TwoWay CallType = 2 ) //////////////////////////////////////////// diff --git a/protocol/dubbo/config.go b/protocol/dubbo/config.go index fde3904079d5708dfe735dedc1c589776227a825..8c1a363ad12f7cef04768927d56835b70fb8493a 100644 --- a/protocol/dubbo/config.go +++ b/protocol/dubbo/config.go @@ -47,7 +47,7 @@ type ( SessionName string `default:"rpc" yaml:"session_name" json:"session_name,omitempty"` } - // Config holds supported types by the multiconfig package + // ServerConfig: Config holds supported types by the multiconfig package ServerConfig struct { // session SessionTimeout string `default:"60s" yaml:"session_timeout" json:"session_timeout,omitempty"` @@ -63,7 +63,7 @@ type ( GettySessionParam GettySessionParam `required:"true" yaml:"getty_session_param" json:"getty_session_param,omitempty"` } - // Config holds supported types by the multiconfig package + // ClientConfig: Config holds supported types by the multiconfig package ClientConfig struct { ReconnectInterval int `default:"0" yaml:"reconnect_interval" json:"reconnect_interval,omitempty"` diff --git a/protocol/dubbo/dubbo_invoker.go b/protocol/dubbo/dubbo_invoker.go index 4131c4533742858db1827f0e6256d3080f38f118..607ef007b5302fe07ff6090a463eab96d6ae4fa9 100644 --- a/protocol/dubbo/dubbo_invoker.go +++ b/protocol/dubbo/dubbo_invoker.go @@ -35,8 +35,10 @@ import ( invocation_impl "github.com/apache/dubbo-go/protocol/invocation" ) -// Err_No_Reply ... -var Err_No_Reply = perrors.New("request need @response") +var ( + // ErrNoReply ... + ErrNoReply = perrors.New("request need @response") +) var ( attachmentKey = []string{constant.INTERFACE_KEY, constant.GROUP_KEY, constant.TOKEN_KEY, constant.TIMEOUT_KEY} @@ -86,7 +88,7 @@ func (di *DubboInvoker) Invoke(ctx context.Context, invocation protocol.Invocati } } else { if inv.Reply() == nil { - result.Err = Err_No_Reply + result.Err = ErrNoReply } else { result.Err = di.client.Call(NewRequest(url.Location, url, inv.MethodName(), inv.Arguments(), inv.Attachments()), response) } diff --git a/protocol/dubbo/dubbo_protocol.go b/protocol/dubbo/dubbo_protocol.go index 9d47cae2f5c310c3245d522f796ee5014eb5298f..355dbc802488338ef4dbdd7290166038b312f183 100644 --- a/protocol/dubbo/dubbo_protocol.go +++ b/protocol/dubbo/dubbo_protocol.go @@ -31,7 +31,9 @@ import ( "github.com/apache/dubbo-go/protocol" ) +// dubbo protocol constant const ( + // DUBBO ... DUBBO = "dubbo" ) diff --git a/protocol/dubbo/listener.go b/protocol/dubbo/listener.go index c8c792df957cb85381fc07d1cd7ac0888dc4fb49..204e8a1c5d2607d3158ff4f68334a39fd1fb7861 100644 --- a/protocol/dubbo/listener.go +++ b/protocol/dubbo/listener.go @@ -41,7 +41,10 @@ import ( ) // todo: WritePkg_Timeout will entry *.yml -const WritePkg_Timeout = 5 * time.Second +const ( + // WritePkg_Timeout ... + WritePkg_Timeout = 5 * time.Second +) var ( errTooManySessions = perrors.New("too many sessions") diff --git a/protocol/grpc/common_test.go b/protocol/grpc/common_test.go index 165b82fabc5703a720766b04659b158d2b3fdbdf..3d0823b1061a61cfa391358e270c8b9081e9031c 100644 --- a/protocol/grpc/common_test.go +++ b/protocol/grpc/common_test.go @@ -77,7 +77,7 @@ func (g *greeterProviderBase) ServiceDesc() *native_grpc.ServiceDesc { Methods: []native_grpc.MethodDesc{ { MethodName: "SayHello", - Handler: _DUBBO_Greeter_SayHello_Handler, + Handler: dubboGreeterSayHelloHandler, }, }, Streams: []native_grpc.StreamDesc{}, @@ -85,7 +85,9 @@ func (g *greeterProviderBase) ServiceDesc() *native_grpc.ServiceDesc { } } -func _DUBBO_Greeter_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor native_grpc.UnaryServerInterceptor) (interface{}, error) { +func dubboGreeterSayHelloHandler(srv interface{}, ctx context.Context, + dec func(interface{}) error, interceptor native_grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(internal.HelloRequest) if err := dec(in); err != nil { return nil, err diff --git a/protocol/grpc/grpc_protocol.go b/protocol/grpc/grpc_protocol.go index ae6fdf13016a32ab37024ccdbd4db8f2ebebc1c5..1c1cca3b7ba6badb84d88ab1414e27d4425b4462 100644 --- a/protocol/grpc/grpc_protocol.go +++ b/protocol/grpc/grpc_protocol.go @@ -28,7 +28,10 @@ import ( "github.com/apache/dubbo-go/protocol" ) -const GRPC = "grpc" +const ( + // GRPC: module name + GRPC = "grpc" +) func init() { extension.SetProtocol(GRPC, GetProtocol) diff --git a/protocol/grpc/internal/client.go b/protocol/grpc/internal/client.go index eb7dc1a456396afccb69293a410a650c200fc943..5ff409ac0557979e421c4ec9ec983c6a9880f52a 100644 --- a/protocol/grpc/internal/client.go +++ b/protocol/grpc/internal/client.go @@ -33,7 +33,7 @@ func init() { config.SetConsumerService(&GrpcGreeterImpl{}) } -// used for dubbo-grpc biz client +// GrpcGreeterImpl: used for dubbo-grpc biz client type GrpcGreeterImpl struct { SayHello func(ctx context.Context, in *HelloRequest, out *HelloReply) error } diff --git a/protocol/grpc/protoc-gen-dubbo/plugin/dubbo/doc.go b/protocol/grpc/protoc-gen-dubbo/plugin/dubbo/doc.go index 90799f3b4a0899fae607d803c63233c67d624152..064c738a53d2200223b0ca81aca77358afad032b 100644 --- a/protocol/grpc/protoc-gen-dubbo/plugin/dubbo/doc.go +++ b/protocol/grpc/protoc-gen-dubbo/plugin/dubbo/doc.go @@ -15,5 +15,5 @@ See the License for the specific language governing permissions and limitations under the License. */ -// dubbo plugin for protobuf. +// Package dubbo plugin for protobuf. package dubbo diff --git a/protocol/invocation/rpcinvocation.go b/protocol/invocation/rpcinvocation.go index 0f42e96d5453229591a47fbc0a3c8f794312fa4a..da3df3297217cb23e9013696460b5d0a765ae011 100644 --- a/protocol/invocation/rpcinvocation.go +++ b/protocol/invocation/rpcinvocation.go @@ -30,6 +30,7 @@ import ( // Invocation Impletment of RPC // /////////////////////////// // todo: is it necessary to separate fields of consumer(provider) from RPCInvocation +// RPCInvocation ... type RPCInvocation struct { methodName string parameterTypes []reflect.Type diff --git a/protocol/invoker.go b/protocol/invoker.go index 6805f3fd034ac553e701b7dcbc4e23d93adb1c63..bb71bab1cfa2ede7fb035912ae996f9adb7411e0 100644 --- a/protocol/invoker.go +++ b/protocol/invoker.go @@ -20,11 +20,13 @@ package protocol import ( "context" ) + import ( "github.com/apache/dubbo-go/common" "github.com/apache/dubbo-go/common/logger" ) +// Invoker ... //go:generate mockgen -source invoker.go -destination mock/mock_invoker.go -self_package github.com/apache/dubbo-go/protocol/mock --package mock Invoker // Extension - Invoker type Invoker interface { diff --git a/protocol/jsonrpc/http.go b/protocol/jsonrpc/http.go index 7ae825e1eb0f4846982bad3237bc0197024b073d..eac32f11767f4e80c8b93509ddee4fa9c1daf6e8 100644 --- a/protocol/jsonrpc/http.go +++ b/protocol/jsonrpc/http.go @@ -159,6 +159,7 @@ func (c *HTTPClient) Call(ctx context.Context, service common.URL, req *Request, return perrors.WithStack(codec.Read(rspBody, rsp)) } +// Do: // !!The high level of complexity and the likelihood that the fasthttp client has not been extensively used // in production means that you would need to expect a very large benefit to justify the adoption of fasthttp today. func (c *HTTPClient) Do(addr, path string, httpHeader http.Header, body []byte) ([]byte, error) { diff --git a/protocol/jsonrpc/json.go b/protocol/jsonrpc/json.go index 9f63e5000bce779cb2d1aa146905954b4d95bc83..cd6498e772a85a21d39f46715fdbae8dc081c33a 100644 --- a/protocol/jsonrpc/json.go +++ b/protocol/jsonrpc/json.go @@ -31,8 +31,10 @@ import ( ) const ( + // MAX_JSONRPC_ID: max jsonrpc request/response id MAX_JSONRPC_ID = 0x7FFFFFFF - VERSION = "2.0" + // VERSION : jsonrpc version + VERSION = "2.0" ) // CodecData ... @@ -55,7 +57,7 @@ const ( codeServerErrorEnd = -32000 ) -// rsponse Error +// Error: response Error type Error struct { Code int `json:"code"` Message string `json:"message"` diff --git a/protocol/jsonrpc/jsonrpc_protocol.go b/protocol/jsonrpc/jsonrpc_protocol.go index a1669df7d3178518842d9df34f00c2b18e2bebb5..17607ab41701f1cf9944bee4a910160142d845f2 100644 --- a/protocol/jsonrpc/jsonrpc_protocol.go +++ b/protocol/jsonrpc/jsonrpc_protocol.go @@ -32,7 +32,10 @@ import ( "github.com/apache/dubbo-go/protocol" ) -const JSONRPC = "jsonrpc" +const ( + // JSONRPC: module name + JSONRPC = "jsonrpc" +) func init() { extension.SetProtocol(JSONRPC, GetProtocol) diff --git a/protocol/jsonrpc/server.go b/protocol/jsonrpc/server.go index 2e1bc16986abe1933088dd76ddf31c39e87a9f06..a50780040e0c71ed60b7dd65112d55122a4193b3 100644 --- a/protocol/jsonrpc/server.go +++ b/protocol/jsonrpc/server.go @@ -51,9 +51,12 @@ var ( ) const ( - DefaultMaxSleepTime = 1 * time.Second // accept中间最大sleep interval + // DefaultMaxSleepTime: max sleep interval in accept + DefaultMaxSleepTime = 1 * time.Second + // DefaultHTTPRspBufferSize ... DefaultHTTPRspBufferSize = 1024 - PathPrefix = byte('/') + // PathPrefix ... + PathPrefix = byte('/') ) // Server ... diff --git a/protocol/protocol.go b/protocol/protocol.go index 948da995edf6fe1834b749c00e76e61ff6fdd226..152550a184a43325d56f0f7371ac9e5e3d3e1c01 100644 --- a/protocol/protocol.go +++ b/protocol/protocol.go @@ -26,14 +26,14 @@ import ( "github.com/apache/dubbo-go/common/logger" ) -// Extension - protocol +// Protocol: Extension - protocol type Protocol interface { Export(invoker Invoker) Exporter Refer(url common.URL) Invoker Destroy() } -// wrapping invoker +// Exporter: wrapping invoker type Exporter interface { GetInvoker() Invoker Unexport() diff --git a/protocol/protocolwrapper/protocol_filter_wrapper.go b/protocol/protocolwrapper/protocol_filter_wrapper.go index 08479fe9d139e31821a0a41a851ded52687f87b3..a630e99f2ac43828e934b2dd89c7bc8e8064f3fe 100644 --- a/protocol/protocolwrapper/protocol_filter_wrapper.go +++ b/protocol/protocolwrapper/protocol_filter_wrapper.go @@ -31,6 +31,7 @@ import ( ) const ( + // FILTER ... FILTER = "filter" ) diff --git a/registry/consul/registry.go b/registry/consul/registry.go index 73bf3975bc7c73f4a7748f46280ffb1aa5525ca8..c5b8510a6c87068a5b4f1ce52203d401a896a6c2 100644 --- a/registry/consul/registry.go +++ b/registry/consul/registry.go @@ -36,6 +36,7 @@ import ( ) const ( + // RegistryConnDelay ... RegistryConnDelay = 3 ) @@ -137,14 +138,15 @@ func (r *consulRegistry) subscribe(url *common.URL, notifyListener registry.Noti } for { - if serviceEvent, err := listener.Next(); err != nil { + serviceEvent, err := listener.Next() + if err != nil { logger.Warnf("Selector.watch() = error{%v}", perrors.WithStack(err)) listener.Close() return - } else { - logger.Infof("update begin, service event: %v", serviceEvent.String()) - notifyListener.Notify(serviceEvent) } + + logger.Infof("update begin, service event: %v", serviceEvent.String()) + notifyListener.Notify(serviceEvent) } } } diff --git a/registry/directory/directory.go b/registry/directory/directory.go index 4e221087f9f9c7214d81f9fc35da5f32bee678f5..f9670af7ea566ce35e89d9173b54752fd16f92bf 100644 --- a/registry/directory/directory.go +++ b/registry/directory/directory.go @@ -225,13 +225,14 @@ func (dir *registryDirectory) List(invocation protocol.Invocation) []protocol.In func (dir *registryDirectory) IsAvailable() bool { if !dir.BaseDirectory.IsAvailable() { return dir.BaseDirectory.IsAvailable() - } else { - for _, ivk := range dir.cacheInvokers { - if ivk.IsAvailable() { - return true - } + } + + for _, ivk := range dir.cacheInvokers { + if ivk.IsAvailable() { + return true } } + return false } diff --git a/registry/etcdv3/registry.go b/registry/etcdv3/registry.go index b058113c69b8007803a8a18c1b5e0c3af8c184f4..8c0b5708fe42587c768a505c9e24754f06298a81 100644 --- a/registry/etcdv3/registry.go +++ b/registry/etcdv3/registry.go @@ -48,7 +48,9 @@ var ( ) const ( - Name = "etcdv3" + // Name: module name + Name = "etcdv3" + // RegistryConnDelay ... RegistryConnDelay = 3 ) diff --git a/registry/etcdv3/registry_test.go b/registry/etcdv3/registry_test.go index 6c05a8a83fce50053272181902aeaecdaee9597c..ab997b2916b09e5a6807030707b1872f955a2c4c 100644 --- a/registry/etcdv3/registry_test.go +++ b/registry/etcdv3/registry_test.go @@ -46,7 +46,8 @@ func initRegistry(t *testing.T) *etcdV3Registry { } out := reg.(*etcdV3Registry) - out.client.CleanKV() + err = out.client.CleanKV() + assert.NoError(t, err) return out } @@ -58,6 +59,7 @@ func (suite *RegistryTestSuite) TestRegister() { reg := initRegistry(t) err := reg.Register(url) + assert.NoError(t, err) children, _, err := reg.client.GetChildrenKVList("/dubbo/com.ikurento.user.UserProvider/providers") if err != nil { t.Fatal(err) @@ -83,7 +85,8 @@ func (suite *RegistryTestSuite) TestSubscribe() { regurl.SetParam(constant.ROLE_KEY, strconv.Itoa(common.CONSUMER)) reg2 := initRegistry(t) - reg2.Register(url) + err = reg2.Register(url) + assert.NoError(t, err) listener, err := reg2.subscribe(&url) if err != nil { t.Fatal(err) @@ -120,7 +123,8 @@ func (suite *RegistryTestSuite) TestProviderDestory() { t := suite.T() reg := initRegistry(t) url, _ := common.NewURL(context.Background(), "dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithMethods([]string{"GetUser", "AddUser"})) - reg.Register(url) + err := reg.Register(url) + assert.NoError(t, err) //listener.Close() time.Sleep(1e9) diff --git a/registry/mock_registry.go b/registry/mock_registry.go index 0b5cbf0658e6a9af162a35250bfb25156e72dc24..9591928eebd22bf2a99ec9dcfeb285c4519a3b90 100644 --- a/registry/mock_registry.go +++ b/registry/mock_registry.go @@ -92,17 +92,16 @@ func (r *MockRegistry) Subscribe(url *common.URL, notifyListener NotifyListener) } for { - if serviceEvent, err := listener.Next(); err != nil { + serviceEvent, err := listener.Next() + if err != nil { listener.Close() time.Sleep(time.Duration(3) * time.Second) return - } else { - logger.Infof("update begin, service event: %v", serviceEvent.String()) - notifyListener.Notify(serviceEvent) } + logger.Infof("update begin, service event: %v", serviceEvent.String()) + notifyListener.Notify(serviceEvent) } - } }() } diff --git a/registry/nacos/registry.go b/registry/nacos/registry.go index a8b9fa83fa73858064e570722341c14f974f5c9e..5a1ae60ef5edbc0b38259309c6acd541aa3ef983 100644 --- a/registry/nacos/registry.go +++ b/registry/nacos/registry.go @@ -47,6 +47,7 @@ var ( ) const ( + // RegistryConnDelay: registry connection delay RegistryConnDelay = 3 ) @@ -209,15 +210,15 @@ func (nr *nacosRegistry) Subscribe(url *common.URL, notifyListener registry.Noti } for { - if serviceEvent, err := listener.Next(); err != nil { + serviceEvent, err := listener.Next() + if err != nil { logger.Warnf("Selector.watch() = error{%v}", perrors.WithStack(err)) listener.Close() return - } else { - logger.Infof("update begin, service event: %v", serviceEvent.String()) - notifyListener.Notify(serviceEvent) } + logger.Infof("update begin, service event: %v", serviceEvent.String()) + notifyListener.Notify(serviceEvent) } } diff --git a/registry/registry.go b/registry/registry.go index e8cf5ecbb9e781d8c15e3e3c1bc8c2070e1526cc..f9e686004f7ff7e2634bf6d4a99051dac60f6e9f 100644 --- a/registry/registry.go +++ b/registry/registry.go @@ -21,7 +21,7 @@ import ( "github.com/apache/dubbo-go/common" ) -// Extension - Registry +// Registry: Extension - Registry type Registry interface { common.Node //used for service provider calling , register services to registry @@ -44,7 +44,7 @@ type NotifyListener interface { Notify(*ServiceEvent) } -//Deprecated! +// Listener: Deprecated! type Listener interface { Next() (*ServiceEvent, error) Close() diff --git a/registry/zookeeper/registry.go b/registry/zookeeper/registry.go index e08266f71304aa8d2244ec459f979a7255e85839..b7c83c5409fbfeebca08cf0ab672a4acc35f3767 100644 --- a/registry/zookeeper/registry.go +++ b/registry/zookeeper/registry.go @@ -44,9 +44,12 @@ import ( ) const ( - RegistryZkClient = "zk registry" + // RegistryZkClient: zk client name + RegistryZkClient = "zk registry" + // RegistryConnDelay: connection delay RegistryConnDelay = 3 - MaxWaitInterval = time.Duration(3e9) + // MaxWaitInterval: max wait interval + MaxWaitInterval = 3 * time.Second ) var ( diff --git a/remoting/etcdv3/client.go b/remoting/etcdv3/client.go index 0e4b09bcf8552362f58bf3a3e3fbd80cf55affac..ae9ba05f0027cc9dddedfc8487557b32f0da5c05 100644 --- a/remoting/etcdv3/client.go +++ b/remoting/etcdv3/client.go @@ -36,15 +36,19 @@ import ( ) const ( - ConnDelay = 3 - MaxFailTimes = 15 + // ConnDelay: connection dalay + ConnDelay = 3 + // MaxFailTimes: max failure times + MaxFailTimes = 15 + // RegistryETCDV3Client: client name RegistryETCDV3Client = "etcd registry" ) var ( // ErrNilETCDV3Client ... ErrNilETCDV3Client = perrors.New("etcd raw client is nil") // full describe the ERR - ErrKVPairNotFound = perrors.New("k/v pair not found") + // ErrKVPairNotFound ... + ErrKVPairNotFound = perrors.New("k/v pair not found") ) // Options ... diff --git a/remoting/etcdv3/listener.go b/remoting/etcdv3/listener.go index 4d2970fe3375e7f0286e5b4038b7062ed0a730a1..47416e598628be67eb06f5cb88bd2345a7729687 100644 --- a/remoting/etcdv3/listener.go +++ b/remoting/etcdv3/listener.go @@ -49,7 +49,7 @@ func NewEventListener(client *Client) *EventListener { } } -// Listen on a spec key +// ListenServiceNodeEvent: Listen on a spec key // this method will return true when spec key deleted, // this method will return false when deep layer connection lose func (l *EventListener) ListenServiceNodeEvent(key string, listener ...remoting.DataListener) bool { @@ -136,7 +136,7 @@ func (l *EventListener) handleEvents(event *clientv3.Event, listeners ...remotin panic("unreachable") } -// Listen on a set of key with spec prefix +// ListenServiceNodeEventWithPrefix: Listen on a set of key with spec prefix func (l *EventListener) ListenServiceNodeEventWithPrefix(prefix string, listener ...remoting.DataListener) { l.wg.Add(1) @@ -182,7 +182,7 @@ func timeSecondDuration(sec int) time.Duration { return time.Duration(sec) * time.Second } -// this func is invoked by etcdv3 ConsumerRegistry::Registe/ etcdv3 ConsumerRegistry::get/etcdv3 ConsumerRegistry::getListener +// ListenServiceEvent is invoked by etcdv3 ConsumerRegistry::Registe/ etcdv3 ConsumerRegistry::get/etcdv3 ConsumerRegistry::getListener // registry.go:Listen -> listenServiceEvent -> listenDirEvent -> ListenServiceNodeEvent // | // --------> ListenServiceNodeEvent diff --git a/remoting/listener.go b/remoting/listener.go index 12e2d50e5537dd0e0559ebd97e581fe0277cb245..3713ba0ccf9d98d4470741785a9490e657cf051c 100644 --- a/remoting/listener.go +++ b/remoting/listener.go @@ -34,8 +34,11 @@ type DataListener interface { type EventType int const ( + // EventTypeAdd ... EventTypeAdd = iota + // EventTypeDel ... EventTypeDel + // EventTypeUpdate ... EventTypeUpdate ) diff --git a/remoting/zookeeper/client.go b/remoting/zookeeper/client.go index 095d04ed0f0e49211a6c2a8ccdaa64ed31edb186..8d2cbd016a219e08a0d20d64190901248ca1bc98 100644 --- a/remoting/zookeeper/client.go +++ b/remoting/zookeeper/client.go @@ -35,6 +35,7 @@ import ( ) const ( + // ConnDelay: connection delay interval ConnDelay = 3 MaxFailTimes = 15 ) diff --git a/remoting/zookeeper/listener.go b/remoting/zookeeper/listener.go index 25805e8deb33685652abe0e4687e830ffac839f6..407cd8a230d730724dc6a40c2a885723f5087d60 100644 --- a/remoting/zookeeper/listener.go +++ b/remoting/zookeeper/listener.go @@ -267,7 +267,7 @@ func timeSecondDuration(sec int) time.Duration { return time.Duration(sec) * time.Second } -// this func is invoked by ZkConsumerRegistry::Register/ZkConsumerRegistry::get/ZkConsumerRegistry::getListener +// ListenServiceEvent is invoked by ZkConsumerRegistry::Register/ZkConsumerRegistry::get/ZkConsumerRegistry::getListener // registry.go:Listen -> listenServiceEvent -> listenDirEvent -> ListenServiceNodeEvent // | // --------> ListenServiceNodeEvent