Skip to content
Snippets Groups Projects
listener.go 7.66 KiB
Newer Older
AlexStocks's avatar
AlexStocks committed
/*
 * 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.
 */
fangyincheng's avatar
fangyincheng committed

vito.he's avatar
vito.he committed
package zookeeper
AlexStocks's avatar
AlexStocks committed

import (
	"path"
	"sync"
	"time"
)

import (
fangyincheng's avatar
fangyincheng committed
	perrors "github.com/pkg/errors"
AlexStocks's avatar
AlexStocks committed
	"github.com/samuel/go-zookeeper/zk"
)

	"github.com/apache/dubbo-go/common/logger"
type ZkEventListener struct {
	client      *ZookeeperClient
	pathMapLock sync.Mutex
	pathMap     map[string]struct{}
	wg          sync.WaitGroup
AlexStocks's avatar
AlexStocks committed
}

func NewZkEventListener(client *ZookeeperClient) *ZkEventListener {
	return &ZkEventListener{
		client:  client,
		pathMap: make(map[string]struct{}),
AlexStocks's avatar
AlexStocks committed
	}
}
func (l *ZkEventListener) SetClient(client *ZookeeperClient) {
	l.client = client
}
func (l *ZkEventListener) listenServiceNodeEvent(zkPath string) bool {
AlexStocks's avatar
AlexStocks committed
	l.wg.Add(1)
	defer l.wg.Done()
	var zkEvent zk.Event
	for {
		keyEventCh, err := l.client.ExistW(zkPath)
AlexStocks's avatar
AlexStocks committed
		if err != nil {
fangyincheng's avatar
fangyincheng committed
			logger.Errorf("existW{key:%s} = error{%v}", zkPath, err)
AlexStocks's avatar
AlexStocks committed
			return false
		}

		select {
		case zkEvent = <-keyEventCh:
fangyincheng's avatar
fangyincheng committed
			logger.Warnf("get a zookeeper zkEvent{type:%s, server:%s, path:%s, state:%d-%s, err:%s}",
				zkEvent.Type.String(), zkEvent.Server, zkEvent.Path, zkEvent.State, StateToString(zkEvent.State), zkEvent.Err)
AlexStocks's avatar
AlexStocks committed
			switch zkEvent.Type {
			case zk.EventNodeDataChanged:
fangyincheng's avatar
fangyincheng committed
				logger.Warnf("zk.ExistW(key{%s}) = event{EventNodeDataChanged}", zkPath)
AlexStocks's avatar
AlexStocks committed
			case zk.EventNodeCreated:
fangyincheng's avatar
fangyincheng committed
				logger.Warnf("zk.ExistW(key{%s}) = event{EventNodeCreated}", zkPath)
AlexStocks's avatar
AlexStocks committed
			case zk.EventNotWatching:
fangyincheng's avatar
fangyincheng committed
				logger.Warnf("zk.ExistW(key{%s}) = event{EventNotWatching}", zkPath)
AlexStocks's avatar
AlexStocks committed
			case zk.EventNodeDeleted:
fangyincheng's avatar
fangyincheng committed
				logger.Warnf("zk.ExistW(key{%s}) = event{EventNodeDeleted}", zkPath)
AlexStocks's avatar
AlexStocks committed
				return true
			}
AlexStocks's avatar
AlexStocks committed
			return false
		}
	}

	return false
}

func (l *ZkEventListener) handleZkNodeEvent(zkPath string, children []string, listener common.DataListener) {
AlexStocks's avatar
AlexStocks committed
	contains := func(s []string, e string) bool {
		for _, a := range s {
			if a == e {
				return true
			}
		}

		return false
	}

	newChildren, err := l.client.GetChildren(zkPath)
AlexStocks's avatar
AlexStocks committed
	if err != nil {
fangyincheng's avatar
fangyincheng committed
		logger.Errorf("path{%s} child nodes changed, zk.Children() = error{%v}", zkPath, perrors.WithStack(err))
AlexStocks's avatar
AlexStocks committed
		return
	}

	// a node was added -- listen the new node
	var (
AlexStocks's avatar
AlexStocks committed
	)
	for _, n := range newChildren {
		if contains(children, n) {
			continue
		}

		newNode = path.Join(zkPath, n)
fangyincheng's avatar
fangyincheng committed
		logger.Infof("add zkNode{%s}", newNode)
		if !listener.DataChange(common.Event{Path: zkPath, Action: common.Add, Content: n}) {
AlexStocks's avatar
AlexStocks committed
			continue
		}
		// listen l service node
fangyincheng's avatar
fangyincheng committed
			logger.Infof("delete zkNode{%s}", node)
AlexStocks's avatar
AlexStocks committed
			if l.listenServiceNodeEvent(node) {
				logger.Infof("delete content{%s}", n)
				listener.DataChange(common.Event{Path: zkPath, Action: common.Del, Content: n})
AlexStocks's avatar
AlexStocks committed
			}
fangyincheng's avatar
fangyincheng committed
			logger.Warnf("listenSelf(zk path{%s}) goroutine exit now", zkPath)
AlexStocks's avatar
AlexStocks committed
	}

	// old node was deleted
	var oldNode string
	for _, n := range children {
		if contains(newChildren, n) {
			continue
		}

		oldNode = path.Join(zkPath, n)
fangyincheng's avatar
fangyincheng committed
		logger.Warnf("delete zkPath{%s}", oldNode)
		if !listener.DataChange(common.Event{Path: zkPath, Action: common.Add, Content: n}) {
AlexStocks's avatar
AlexStocks committed
			continue
		}
		logger.Warnf("delete content{%s}", n)
AlexStocks's avatar
AlexStocks committed
		if err != nil {
fangyincheng's avatar
fangyincheng committed
			logger.Errorf("NewURL(i{%s}) = error{%v}", n, perrors.WithStack(err))
AlexStocks's avatar
AlexStocks committed
			continue
		}
		listener.DataChange(common.Event{Path: zkPath, Action: common.Del, Content: n})
AlexStocks's avatar
AlexStocks committed
	}
}

func (l *ZkEventListener) listenDirEvent(zkPath string, listener common.DataListener) {
AlexStocks's avatar
AlexStocks committed
	l.wg.Add(1)
	defer l.wg.Done()

	var (
		failTimes int
		event     chan struct{}
		zkEvent   zk.Event
	)
	event = make(chan struct{}, 4)
AlexStocks's avatar
AlexStocks committed
	defer close(event)
	for {
		// get current children for a zkPath
		children, childEventCh, err := l.client.GetChildrenW(zkPath)
AlexStocks's avatar
AlexStocks committed
		if err != nil {
			failTimes++
			if MaxFailTimes <= failTimes {
				failTimes = MaxFailTimes
AlexStocks's avatar
AlexStocks committed
			}
fangyincheng's avatar
fangyincheng committed
			logger.Errorf("listenDirEvent(path{%s}) = error{%v}", zkPath, err)
AlexStocks's avatar
AlexStocks committed
			// clear the event channel
		CLEAR:
			for {
				select {
				case <-event:
				default:
					break CLEAR
				}
			}
			l.client.RegisterEvent(zkPath, &event)
AlexStocks's avatar
AlexStocks committed
			select {
			case <-time.After(timeSecondDuration(failTimes * ConnDelay)):
				l.client.UnregisterEvent(zkPath, &event)
AlexStocks's avatar
AlexStocks committed
				continue
			case <-l.client.Done():
				l.client.UnregisterEvent(zkPath, &event)
				logger.Warnf("client.done(), listen(path{%s}) goroutine exit now...", zkPath)
AlexStocks's avatar
AlexStocks committed
				return
			case <-event:
fangyincheng's avatar
fangyincheng committed
				logger.Infof("get zk.EventNodeDataChange notify event")
				l.client.UnregisterEvent(zkPath, &event)
				l.handleZkNodeEvent(zkPath, nil, listener)
AlexStocks's avatar
AlexStocks committed
				continue
			}
		}
		failTimes = 0

		select {
		case zkEvent = <-childEventCh:
fangyincheng's avatar
fangyincheng committed
			logger.Warnf("get a zookeeper zkEvent{type:%s, server:%s, path:%s, state:%d-%s, err:%s}",
				zkEvent.Type.String(), zkEvent.Server, zkEvent.Path, zkEvent.State, StateToString(zkEvent.State), zkEvent.Err)
AlexStocks's avatar
AlexStocks committed
			if zkEvent.Type != zk.EventNodeChildrenChanged {
				continue
			}
			l.handleZkNodeEvent(zkEvent.Path, children, listener)
		case <-l.client.Done():
			logger.Warnf("client.done(), listen(path{%s}) goroutine exit now...", zkPath)
AlexStocks's avatar
AlexStocks committed
			return
		}
	}
}

func timeSecondDuration(sec int) time.Duration {
	return time.Duration(sec) * time.Second
}

AlexStocks's avatar
AlexStocks committed
// this func is invoked by ZkConsumerRegistry::Registe/ZkConsumerRegistry::get/ZkConsumerRegistry::getListener
// registry.go:Listen -> listenServiceEvent -> listenDirEvent -> listenServiceNodeEvent
//                            |
//                            --------> listenServiceNodeEvent
func (l *ZkEventListener) ListenServiceEvent(zkPath string, listener common.DataListener) {
AlexStocks's avatar
AlexStocks committed
	var (
		err        error
		dubboPath  string
		children   []string
vito.he's avatar
vito.he committed
		serviceURL common.URL
AlexStocks's avatar
AlexStocks committed
	)

	l.pathMapLock.Lock()
	_, ok := l.pathMap[zkPath]
	l.pathMapLock.Unlock()
AlexStocks's avatar
AlexStocks committed
	if ok {
fangyincheng's avatar
fangyincheng committed
		logger.Warnf("@zkPath %s has already been listened.", zkPath)
AlexStocks's avatar
AlexStocks committed
		return
	}

	l.pathMapLock.Lock()
	l.pathMap[zkPath] = struct{}{}
	l.pathMapLock.Unlock()
AlexStocks's avatar
AlexStocks committed

fangyincheng's avatar
fangyincheng committed
	logger.Infof("listen dubbo provider path{%s} event and wait to get all provider zk nodes", zkPath)
	children, err = l.client.GetChildren(zkPath)
AlexStocks's avatar
AlexStocks committed
	if err != nil {
		children = nil
fangyincheng's avatar
fangyincheng committed
		logger.Errorf("fail to get children of zk path{%s}", zkPath)
AlexStocks's avatar
AlexStocks committed
	}

	for _, c := range children {
		if !listener.DataChange(common.Event{Path: zkPath, Action: common.Add, Content: c}) {
AlexStocks's avatar
AlexStocks committed
			continue
		}

		// listen l service node
		dubboPath = path.Join(zkPath, c)
fangyincheng's avatar
fangyincheng committed
		logger.Infof("listen dubbo service key{%s}", dubboPath)
vito.he's avatar
vito.he committed
		go func(zkPath string, serviceURL common.URL) {
AlexStocks's avatar
AlexStocks committed
			if l.listenServiceNodeEvent(dubboPath) {
fangyincheng's avatar
fangyincheng committed
				logger.Debugf("delete serviceUrl{%s}", serviceURL)
				listener.DataChange(common.Event{Path: zkPath, Action: common.Del, Content: c})
AlexStocks's avatar
AlexStocks committed
			}
fangyincheng's avatar
fangyincheng committed
			logger.Warnf("listenSelf(zk path{%s}) goroutine exit now", zkPath)
AlexStocks's avatar
AlexStocks committed
		}(dubboPath, serviceURL)
	}

fangyincheng's avatar
fangyincheng committed
	logger.Infof("listen dubbo path{%s}", zkPath)
	go func(zkPath string, listener common.DataListener) {
fangyincheng's avatar
fangyincheng committed
		logger.Warnf("listenDirEvent(zkPath{%s}) goroutine exit now", zkPath)
AlexStocks's avatar
AlexStocks committed
}

func (l *ZkEventListener) valid() bool {
	return l.client.ZkConnValid()
AlexStocks's avatar
AlexStocks committed
}

AlexStocks's avatar
AlexStocks committed
	l.wg.Wait()
}