github.heygears.com/openimsdk/tools@v0.0.49/discovery/zookeeper/verify.go (about)

     1  // Copyright © 2023 OpenIM. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package zookeeper
    16  
    17  import (
    18  	"context"
    19  	"sync"
    20  	"time"
    21  
    22  	"github.com/go-zookeeper/zk"
    23  	"github.com/openimsdk/tools/errs"
    24  	"google.golang.org/grpc"
    25  )
    26  
    27  func Check(ctx context.Context, ZkServers []string, scheme string, options ...ZkOption) error {
    28  	client := &ZkClient{
    29  		ZkServers:  ZkServers,
    30  		zkRoot:     "/",
    31  		scheme:     scheme,
    32  		timeout:    timeout,
    33  		localConns: make(map[string][]*grpc.ClientConn),
    34  		resolvers:  make(map[string]*Resolver),
    35  		lock:       &sync.Mutex{},
    36  		logger:     nilLog{},
    37  	}
    38  	for _, option := range options {
    39  		option(client)
    40  	}
    41  
    42  	// Establish a Zookeeper connection with a specified timeout and handle authentication.
    43  	conn, eventChan, err := zk.Connect(ZkServers, time.Duration(client.timeout)*time.Second)
    44  	if err != nil {
    45  		return errs.WrapMsg(err, "connect failed", "ZkServers", ZkServers)
    46  	}
    47  
    48  	_, cancel := context.WithCancel(context.Background())
    49  	client.cancel = cancel
    50  	client.ticker = time.NewTicker(defaultFreq)
    51  
    52  	// Ensure authentication is set if credentials are provided.
    53  	if client.username != "" && client.password != "" {
    54  		auth := []byte(client.username + ":" + client.password)
    55  		if err := conn.AddAuth("digest", auth); err != nil {
    56  			conn.Close()
    57  			return errs.WrapMsg(err, "AddAuth failed", "userName", client.username, "password", client.password)
    58  		}
    59  	}
    60  
    61  	client.zkRoot += scheme
    62  	client.eventChan = eventChan
    63  	client.conn = conn
    64  
    65  	// Verify root node existence and create if missing.
    66  	if err := client.ensureRoot(); err != nil {
    67  		conn.Close()
    68  		return errs.WrapMsg(err, "ensureRoot failed", "zkRoot", client.zkRoot)
    69  	}
    70  	return nil
    71  }