// this reuse zk connection if host list is the same // a new dedicated event chan is created for each call // zk events are duplicated to all those channels func NewSharedZkConnection(hosts []string, timeout time.Duration) (*SharedZkConnection, error) { zkConnectionsMutex.Lock() defer zkConnectionsMutex.Unlock() sort.Strings(hosts) hash := strings.Join(hosts, "") if _, ok := zkConnections[hash]; !ok { conn, channel, err := zk.Connect(hosts, timeout) conn.SetLogger(ZKLogger{}) zkConnections[hash] = &SharedZkConnection{ hash: hash, Conn: conn, err: err, sourceChan: channel, } go func(sharedZk *SharedZkConnection) { events := sharedZk.Subscribe() connectingCount := 0 for { select { case e, ok := <-events: if !ok { return } if e.Type == zk.EventSession && e.State == zk.StateHasSession { if sharedZk.connected == false { logs.WithF(data.WithField("servers", hosts)).Info("Connected to zk") connectingCount = 0 } sharedZk.connected = true } else if (e.Type == zk.EventSession || e.Type == zk.EventType(0)) && (e.State == zk.StateDisconnected || e.State == zk.StateExpired) { if sharedZk.connected == true { logs.WithF(data.WithField("servers", hosts)).Warn("Connection lost to zk") connectingCount = 0 } sharedZk.connected = false } else if (e.Type == zk.EventSession || e.Type == zk.EventType(0)) && (e.State == zk.StateAuthFailed) { logs.WithF(data.WithField("servers", hosts)).Error("Authentication failure on zk") } else if (e.Type == zk.EventSession || e.Type == zk.EventType(0)) && (e.State == zk.StateConnecting) { if connectingCount == 1 { logs.WithF(data.WithField("server", conn.Server())).Warn("Failed to connect to zk. Not reporting nexts servers try until connected") } connectingCount++ } } } }(zkConnections[hash]) } go zkConnections[hash].recipientListPublish() return zkConnections[hash], zkConnections[hash].err }
func checkWatchers(conf *bloorConfig, watchers []<-chan zk.Event) { // Check the watchers for i, event := range watchers { // Sync up _, err := conf.conns[i].Sync(conf.rootZnode) if err != nil { log.Fatal(err) } else { log.Printf("Synced connection %d", i) } log.Printf("Length of event channel for session %d is %d", i, len(event)) // Check how many waches fired if len(event) != 1 { log.Fatalf("Watcher for session %d missed event", i) } msg := <-event log.Printf("Event type %s occured on path %s with session %d", zk.EventType(msg.Type), msg.Path, i) } }