Skip to content
Snippets Groups Projects
listener.go 5.7 KiB
Newer Older
/*
 * 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.
 */

vito.he's avatar
vito.he committed
	"strings"
import (
	perrors "github.com/pkg/errors"
)
	"github.com/apache/dubbo-go/common"
	"github.com/apache/dubbo-go/common/logger"
	"github.com/apache/dubbo-go/config_center"
	"github.com/apache/dubbo-go/registry"
vito.he's avatar
vito.he committed
	"github.com/apache/dubbo-go/remoting"
	zk "github.com/apache/dubbo-go/remoting/zookeeper"
)

CodingSinger's avatar
CodingSinger committed
// RegistryDataListener contains all URL information subscribed by zookeeper registry
	subscribed map[string]config_center.ConfigurationListener
	mutex      sync.Mutex
	closed     bool
CodingSinger's avatar
CodingSinger committed
// NewRegistryDataListener constructs a new RegistryDataListener
func NewRegistryDataListener() *RegistryDataListener {
	return &RegistryDataListener{
		subscribed: make(map[string]config_center.ConfigurationListener)}
// SubscribeURL is used to set a watch listener for url
func (l *RegistryDataListener) SubscribeURL(url *common.URL, listener config_center.ConfigurationListener) {
	if l.closed {
		return
	}
邹毅贤's avatar
邹毅贤 committed
	l.subscribed[url.ServiceKey()] = listener
邹毅贤's avatar
邹毅贤 committed
// UnSubscribeURL is used to set a watch listener for url
邹毅贤's avatar
邹毅贤 committed
func (l *RegistryDataListener) UnSubscribeURL(url *common.URL) config_center.ConfigurationListener {
	if l.closed {
		return nil
	}
邹毅贤's avatar
邹毅贤 committed
	listener := l.subscribed[url.ServiceKey()]
	delete(l.subscribed, url.ServiceKey())
邹毅贤's avatar
邹毅贤 committed
	return listener
}

CodingSinger's avatar
CodingSinger committed
// DataChange accepts all events sent from the zookeeper server and trigger the corresponding listener for processing
func (l *RegistryDataListener) DataChange(eventType remoting.Event) bool {
	// Intercept the last bit
pantianying's avatar
pantianying committed
	index := strings.Index(eventType.Path, "/providers/")
	if index == -1 {
pantianying's avatar
pantianying committed
		logger.Warnf("Listen with no url, event.path={%v}", eventType.Path)
pantianying's avatar
pantianying committed
		return false
	}
	url := eventType.Path[index+len("/providers/"):]
	serviceURL, err := common.NewURL(url)
pantianying's avatar
pantianying committed
		logger.Errorf("Listen NewURL(r{%s}) = error{%v} eventType.Path={%v}", url, err, eventType.Path)
	l.mutex.Lock()
	defer l.mutex.Unlock()
	if l.closed {
		return false
	}
邹毅贤's avatar
邹毅贤 committed
	for serviceKey, listener := range l.subscribed {
		if serviceURL.ServiceKey() == serviceKey {
scott's avatar
scott committed
				&config_center.ConfigChangeEvent{
					Key:        eventType.Path,
					Value:      serviceURL,
					ConfigType: eventType.Action,
				},
			)
			return true
		}
scott's avatar
scott committed
	return false
CodingSinger's avatar
CodingSinger committed
// Close all RegistryConfigurationListener in subscribed
CodingSinger's avatar
CodingSinger committed
func (l *RegistryDataListener) Close() {
	l.mutex.Lock()
	defer l.mutex.Unlock()
	for _, listener := range l.subscribed {
		listener.(*RegistryConfigurationListener).Close()
	}
}

CodingSinger's avatar
CodingSinger committed
// RegistryConfigurationListener represent the processor of zookeeper watcher
type RegistryConfigurationListener struct {
邹毅贤's avatar
邹毅贤 committed
	client       *zk.ZookeeperClient
	registry     *zkRegistry
	events       chan *config_center.ConfigChangeEvent
	isClosed     bool
	close        chan struct{}
	closeOnce    sync.Once
	subscribeURL *common.URL
// NewRegistryConfigurationListener for listening the event of zk.
邹毅贤's avatar
邹毅贤 committed
func NewRegistryConfigurationListener(client *zk.ZookeeperClient, reg *zkRegistry, conf *common.URL) *RegistryConfigurationListener {
	reg.WaitGroup().Add(1)
邹毅贤's avatar
邹毅贤 committed
	return &RegistryConfigurationListener{
		client:       client,
		registry:     reg,
		events:       make(chan *config_center.ConfigChangeEvent, 32),
		isClosed:     false,
		close:        make(chan struct{}, 1),
		subscribeURL: conf}
CodingSinger's avatar
CodingSinger committed
// Process submit the ConfigChangeEvent to the event chan to notify all observer
func (l *RegistryConfigurationListener) Process(configType *config_center.ConfigChangeEvent) {
CodingSinger's avatar
CodingSinger committed
// Next will observe the registry state and events chan
func (l *RegistryConfigurationListener) Next() (*registry.ServiceEvent, error) {
	for {
		select {
		case <-l.client.Done():
CodingSinger's avatar
CodingSinger committed
			logger.Warnf("listener's zk client connection (address {%s}) is broken, so zk event listener exit now.", l.client.ZkAddrs)
			return nil, perrors.New("zookeeper client stopped")
CodingSinger's avatar
CodingSinger committed
			return nil, perrors.New("listener have been closed")
		case <-l.registry.Done():
CodingSinger's avatar
CodingSinger committed
			logger.Warnf("zk consumer register has quit, so zk event listener exit now. (registry url {%v}", l.registry.BaseRegistry.URL)
			return nil, perrors.New("zookeeper registry, (registry url{%v}) stopped")
		case e := <-l.events:
			logger.Debugf("got zk event %s", e)
			if e.ConfigType == remoting.EventTypeDel && !l.valid() {
				logger.Warnf("update @result{%s}. But its connection to registry is invalid", e.Value)
				continue
			}
			//r.update(e.res)
			//write to invoker
			//r.outerEventCh <- e.res
			return &registry.ServiceEvent{Action: e.ConfigType, Service: e.Value.(common.URL)}, nil
		}
	}
}
CodingSinger's avatar
CodingSinger committed
// Close RegistryConfigurationListener only once
func (l *RegistryConfigurationListener) Close() {
	// ensure that the listener will be closed at most once.
	l.closeOnce.Do(func() {
pantianying's avatar
pantianying committed
		l.isClosed = true
		l.registry.WaitGroup().Done()
CodingSinger's avatar
CodingSinger committed
// valid return the true if the client conn isn't nil
func (l *RegistryConfigurationListener) valid() bool {
	return l.client.ZkConnValid()
}