package clientv3

import (
    "net/url"
    "strings"
    "sync"

    "golang.org/x/net/context"
    "google.golang.org/grpc"
    "google.golang.org/grpc/codes"
)

// ErrNoAddrAvilable is returned by Get() when the balancer does not have
// any active connection to endpoints at the time.
// This error is returned only when opts.BlockingWait is true.
var ErrNoAddrAvilable = grpc.Errorf(codes.Unavailable, "there is no address available")

// simpleBalancer does the bare minimum to expose multiple eps
// to the grpc reconnection code path
//简单均衡器
type simpleBalancer struct {
    // addrs are the client's endpoints for grpc
    addrs []grpc.Address  //nsqd 地址列表
    // notifyCh notifies grpc of the set of addresses for connecting
    notifyCh chan []grpc.Address  //链接通知地址

    // readyc closes once the first connection is up
//一旦连接上 ,就关闭链接  并且 只执行一次
    readyc    chan struct{}
    readyOnce sync.Once

    // mu protects upEps, pinAddr, and connectingAddr
    //锁  保护 upEps, pinAddr, and connectingAddr 的锁
    mu sync.RWMutex
    // upEps holds the current endpoints that have an active connection
//已经存活的链接地址
    upEps map[string]struct{}
    // upc closes when upEps transitions from empty to non-zero or the balancer closes.
//当upEps为空 转化为非空 或者均衡器关闭的时候 ,关闭此通道
    upc chan struct{}

    // grpc issues TLS cert checks using the string passed into dial so
    // that string must be the host. To recover the full scheme://host URL,
    // have a map from hosts to the original endpoint.
//host 到 endpoint 映射 map集合
    host2ep map[string]string

    // pinAddr is the currently pinned address; set to the empty string on
    // intialization and shutdown.
//当前固定的地址。当此变量被初始化或者关闭的时候  设置为空
    pinAddr string
//是否关闭的标志
    closed bool
}
//创建负载均衡器  
func newSimpleBalancer(eps []string) *simpleBalancer {
    notifyCh := make(chan []grpc.Address, 1)
    addrs := make([]grpc.Address, len(eps))
    for i := range eps {
        addrs[i].Addr = getHost(eps[i])
    }
    notifyCh <- addrs
    sb := &simpleBalancer{
        addrs:    addrs,
        notifyCh: notifyCh,
        readyc:   make(chan struct{}),
        upEps:    make(map[string]struct{}),
        upc:      make(chan struct{}),
        host2ep:  getHost2ep(eps),
    }
    return sb
}
//启动
func (b *simpleBalancer) Start(target string, config grpc.BalancerConfig) error { return nil }
//链接通知
func (b *simpleBalancer) ConnectNotify() <-chan struct{} {
    b.mu.Lock()
    defer b.mu.Unlock()
    return b.upc
}
//通过主机 转化为地址
func (b *simpleBalancer) getEndpoint(host string) string {
    b.mu.Lock()
    defer b.mu.Unlock()
    return b.host2ep[host]
}
//同上相反
func getHost2ep(eps []string) map[string]string {
    hm := make(map[string]string, len(eps))
    for i := range eps {
        _, host, _ := parseEndpoint(eps[i])
        hm[host] = eps[i]
    }
    return hm
}
//更新地址列表
func (b *simpleBalancer) updateAddrs(eps []string) {
    np := getHost2ep(eps)

    b.mu.Lock()
    defer b.mu.Unlock()

    match := len(np) == len(b.host2ep)
    for k, v := range np {
        if b.host2ep[k] != v {
            match = false
            break
        }
    }
    if match {
        // same endpoints, so no need to update address
        return
    }

    b.host2ep = np

    addrs := make([]grpc.Address, 0, len(eps))
    for i := range eps {
        addrs = append(addrs, grpc.Address{Addr: getHost(eps[i])})
    }
    b.addrs = addrs
    b.notifyCh <- addrs
}
//运行中的机器
func (b *simpleBalancer) Up(addr grpc.Address) func(error) {
    b.mu.Lock()
    defer b.mu.Unlock()

    // gRPC might call Up after it called Close. We add this check
    // to "fix" it up at application layer. Or our simplerBalancer
    // might panic since b.upc is closed.
    if b.closed {
        return func(err error) {}
    }

    if len(b.upEps) == 0 {
        // notify waiting Get()s and pin first connected address
        close(b.upc)
        b.pinAddr = addr.Addr
    }
    b.upEps[addr.Addr] = struct{}{}

    // notify client that a connection is up
    b.readyOnce.Do(func() { close(b.readyc) })

    return func(err error) {
        b.mu.Lock()
        delete(b.upEps, addr.Addr)
        if len(b.upEps) == 0 && b.pinAddr != "" {
            b.upc = make(chan struct{})
        } else if b.pinAddr == addr.Addr {
            // choose new random up endpoint
            for k := range b.upEps {
                b.pinAddr = k
                break
            }
        }
        b.mu.Unlock()
    }
}

func (b *simpleBalancer) Get(ctx context.Context, opts grpc.BalancerGetOptions) (grpc.Address, func(), error) {
    var addr string

    // If opts.BlockingWait is false (for fail-fast RPCs), it should return
    // an address it has notified via Notify immediately instead of blocking.
    if !opts.BlockingWait {
        b.mu.RLock()
        closed := b.closed
        addr = b.pinAddr
        upEps := len(b.upEps)
        b.mu.RUnlock()
        if closed {
            return grpc.Address{Addr: ""}, nil, grpc.ErrClientConnClosing
        }

        if upEps == 0 {
            return grpc.Address{Addr: ""}, nil, ErrNoAddrAvilable
        }
        return grpc.Address{Addr: addr}, func() {}, nil
    }

    for {
        b.mu.RLock()
        ch := b.upc
        b.mu.RUnlock()
        select {
        case <-ch:
        case <-ctx.Done():
            return grpc.Address{Addr: ""}, nil, ctx.Err()
        }
        b.mu.RLock()
        addr = b.pinAddr
        upEps := len(b.upEps)
        b.mu.RUnlock()
        if addr == "" {
            return grpc.Address{Addr: ""}, nil, grpc.ErrClientConnClosing
        }
        if upEps > 0 {
            break
        }
    }
    return grpc.Address{Addr: addr}, func() {}, nil
}

func (b *simpleBalancer) Notify() <-chan []grpc.Address { return b.notifyCh }

func (b *simpleBalancer) Close() error {
    b.mu.Lock()
    defer b.mu.Unlock()
    // In case gRPC calls close twice. TODO: remove the checking
    // when we are sure that gRPC wont call close twice.
    if b.closed {
        return nil
    }
    b.closed = true
    close(b.notifyCh)
    // terminate all waiting Get()s
    b.pinAddr = ""
    if len(b.upEps) == 0 {
        close(b.upc)
    }
    return nil
}

func getHost(ep string) string {
    url, uerr := url.Parse(ep)
    if uerr != nil || !strings.Contains(ep, "://") {
        return ep
    }
    return url.Host
}

balancer.go的更多相关文章

  1. sudo -u hdfs hdfs balancer出现异常 No lease on /system/balancer.id

    16/06/02 20:34:05 INFO balancer.Balancer: namenodes = [hdfs://dlhtHadoop101:8022, hdfs://dlhtHadoop1 ...

  2. 【转】HADOOP HDFS BALANCER介绍及经验总结

    转自:http://www.aboutyun.com/thread-7354-1-1.html 集群平衡介绍 Hadoop的HDFS集群非常容易出现机器与机器之间磁盘利用率不平衡的情况,比如集群中添加 ...

  3. CDH版HDFS Block Balancer方法

    命令: sudo -u hdfs hdfs balancer 默认会检查每个datanode的磁盘使用情况,对磁盘使用超过整个集群10%的datanode移动block到其他datanode达到均衡作 ...

  4. 负载均衡server load balancer

    负载均衡(Server Load Balancer,简称SLB)是对多台云服务器进行流量分发的负载均衡服务.SLB可以通过流量分发扩展应用系统对外的服务能力,通过消除单点故障提升应用系统的可用性. ( ...

  5. HDFS 上传文件的不平衡,Balancer问题是过慢

    至HDFS上传文件.假定从datanode开始上传文件,上传的数据将导致目前的当务之急是全datanode圆盘.这是一个分布式程序的执行是非常不利. 解决方案: 1.从其他非datanode节点上传 ...

  6. 【转载】漫谈HADOOP HDFS BALANCER

    Hadoop的HDFS集群非常容易出现机器与机器之间磁盘利用率不平衡的情况,比如集群中添加新的数据节点.当HDFS出现不平衡状况的时候,将引发很多问题,比如MR程序无法很好地利用本地计算的优势,机器之 ...

  7. 【转载】HDFS 上传文件不均衡和Balancer太慢的问题

    向HDFS上传文件,如果是从某个datanode开始上传文件,会导致上传的数据优先写满当前datanode的磁盘,这对于运行分布式程序是非常不利的. 解决的办法: 1.从其他非datanode节点上传 ...

  8. Feign报错Caused by: com.netflix.client.ClientException: Load balancer does not have available server for client

    问题描述 使用Feign调用微服务接口报错,如下: java.lang.RuntimeException: com.netflix.client.ClientException: Load balan ...

  9. Load balancer does not have available server for client

    最近在研究spring-cloud,研究zuul组件时发生下列错误: Caused by: com.netflix.client.ClientException: Load balancer does ...

随机推荐

  1. Jfinal调用Orcale存储过程

    因为项目需要,最近一直在学习Orcale存储过程,但发现在网上很少有人写Jave中Jfinal调用Orcale存储过程的文章,即使有也是几年前的,很多都不能用,今天给大家分享一段Jfinal调用Orc ...

  2. Python_linux环境变量和软链接(个人理解)

    --------------------------------------- 最近在服务器上想运行个脚本,装了个python3.6,但是他还自带了个2.7版本,后来发现上面还有3.5版本的pytho ...

  3. Nuget发布教程

    nuget setApiKey Your-API-Key -Source https://www.nuget.org/api/v2/package nuget spec nuget pack Monk ...

  4. Android开发之深入理解Android 7.0系统权限更改相关文档

    http://www.cnblogs.com/dazhao/p/6547811.html 摘要: Android 6.0之后的版本增加了运行时权限,应用程序在执行每个需要系统权限的功能时,需要添加权限 ...

  5. RA layer request failed

    新整的Eclipse环境出现这个问题,细化内容是不能connect,后来想起切换Eclipse底层库的事情,然后打开Eclipse的SVN设置.把SVN Client借口由JavaHL改为PureJa ...

  6. Android Studio 插件开发详解四:填坑

    转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/78265540 本文出自[赵彦军的博客] 在前面我介绍了插件开发的基本流程 [And ...

  7. Python 30分钟入门指南

    Python 30分钟入门指南 为什么 OIer 要学 Python? Python 语言特性简洁明了,使用 Python 写测试数据生成器和对拍器,比编写 C++ 事半功倍. Python 学习成本 ...

  8. Yii2表单提交(带文件上传)

    今天写一个php的表单提交接口,除了基本的字符串数据,还带文件上传,不用说前端form标签内应该有这些属性 <form enctype="multipart/form-data&quo ...

  9. UE4中如何使物体始终朝向摄像头?

    要使物体始终正面朝向摄像头需要用到一个关键节点:Find Look at Rotation 其中Start连接需要旋转的物体位置矢量,Target连接摄像头位置矢量 最后设置SetActorRotat ...

  10. python笔记:#003#PyCharm 的初始设置

    PyCharm 的初始设置(知道) 目标 恢复 PyCharm 的初始设置 第一次启动 PyCharm 新建一个 Python 项目 设置 PyCharm 的字体显示 PyCharm 的升级以及其他 ...