github.com/lingyao2333/mo-zero@v1.4.1/zrpc/internal/rpcpubserver.go (about)

     1  package internal
     2  
     3  import (
     4  	"os"
     5  	"strings"
     6  
     7  	"github.com/lingyao2333/mo-zero/core/discov"
     8  	"github.com/lingyao2333/mo-zero/core/netx"
     9  )
    10  
    11  const (
    12  	allEths  = "0.0.0.0"
    13  	envPodIp = "POD_IP"
    14  )
    15  
    16  // NewRpcPubServer returns a Server.
    17  func NewRpcPubServer(etcd discov.EtcdConf, listenOn string, opts ...ServerOption) (Server, error) {
    18  	registerEtcd := func() error {
    19  		pubListenOn := figureOutListenOn(listenOn)
    20  		var pubOpts []discov.PubOption
    21  		if etcd.HasAccount() {
    22  			pubOpts = append(pubOpts, discov.WithPubEtcdAccount(etcd.User, etcd.Pass))
    23  		}
    24  		if etcd.HasTLS() {
    25  			pubOpts = append(pubOpts, discov.WithPubEtcdTLS(etcd.CertFile, etcd.CertKeyFile,
    26  				etcd.CACertFile, etcd.InsecureSkipVerify))
    27  		}
    28  		pubClient := discov.NewPublisher(etcd.Hosts, etcd.Key, pubListenOn, pubOpts...)
    29  		return pubClient.KeepAlive()
    30  	}
    31  	server := keepAliveServer{
    32  		registerEtcd: registerEtcd,
    33  		Server:       NewRpcServer(listenOn, opts...),
    34  	}
    35  
    36  	return server, nil
    37  }
    38  
    39  type keepAliveServer struct {
    40  	registerEtcd func() error
    41  	Server
    42  }
    43  
    44  func (s keepAliveServer) Start(fn RegisterFn) error {
    45  	if err := s.registerEtcd(); err != nil {
    46  		return err
    47  	}
    48  
    49  	return s.Server.Start(fn)
    50  }
    51  
    52  func figureOutListenOn(listenOn string) string {
    53  	fields := strings.Split(listenOn, ":")
    54  	if len(fields) == 0 {
    55  		return listenOn
    56  	}
    57  
    58  	host := fields[0]
    59  	if len(host) > 0 && host != allEths {
    60  		return listenOn
    61  	}
    62  
    63  	ip := os.Getenv(envPodIp)
    64  	if len(ip) == 0 {
    65  		ip = netx.InternalIp()
    66  	}
    67  	if len(ip) == 0 {
    68  		return listenOn
    69  	}
    70  
    71  	return strings.Join(append([]string{ip}, fields[1:]...), ":")
    72  }