package concurrency

import (
    "errors"
    "fmt"

    v3 "github.com/coreos/etcd/clientv3"
    "github.com/coreos/etcd/mvcc/mvccpb"
    "golang.org/x/net/context"
)

var (
    ErrElectionNotLeader = errors.New("election: not leader")
    ErrElectionNoLeader  = errors.New("election: no leader")
)

type Election struct {
    session *Session

    keyPrefix string

    leaderKey     string
    leaderRev     int64
    leaderSession *Session
}

// NewElection returns a new election on a given key prefix.
func NewElection(s *Session, pfx string) *Election {
    return &Election{session: s, keyPrefix: pfx + "/"}
}

// Campaign puts a value as eligible for the election. It blocks until
// it is elected, an error occurs, or the context is cancelled.
func (e *Election) Campaign(ctx context.Context, val string) error {
    s := e.session
    client := e.session.Client()

    k := fmt.Sprintf("%s%x", e.keyPrefix, s.Lease())
    txn := client.Txn(ctx).If(v3.Compare(v3.CreateRevision(k), "=", 0))
    txn = txn.Then(v3.OpPut(k, val, v3.WithLease(s.Lease())))
    txn = txn.Else(v3.OpGet(k))
    resp, err := txn.Commit()
    if err != nil {
        return err
    }
    e.leaderKey, e.leaderRev, e.leaderSession = k, resp.Header.Revision, s
    if !resp.Succeeded {
        kv := resp.Responses[0].GetResponseRange().Kvs[0]
        e.leaderRev = kv.CreateRevision
        if string(kv.Value) != val {
            if err = e.Proclaim(ctx, val); err != nil {
                e.Resign(ctx)
                return err
            }
        }
    }

    err = waitDeletes(ctx, client, e.keyPrefix, e.leaderRev-1)
    if err != nil {
        // clean up in case of context cancel
        select {
        case <-ctx.Done():
            e.Resign(client.Ctx())
        default:
            e.leaderSession = nil
        }
        return err
    }

    return nil
}

// Proclaim lets the leader announce a new value without another election.
func (e *Election) Proclaim(ctx context.Context, val string) error {
    if e.leaderSession == nil {
        return ErrElectionNotLeader
    }
    client := e.session.Client()
    cmp := v3.Compare(v3.CreateRevision(e.leaderKey), "=", e.leaderRev)
    txn := client.Txn(ctx).If(cmp)
    txn = txn.Then(v3.OpPut(e.leaderKey, val, v3.WithLease(e.leaderSession.Lease())))
    tresp, terr := txn.Commit()
    if terr != nil {
        return terr
    }
    if !tresp.Succeeded {
        e.leaderKey = ""
        return ErrElectionNotLeader
    }
    return nil
}

// Resign lets a leader start a new election.
func (e *Election) Resign(ctx context.Context) (err error) {
    if e.leaderSession == nil {
        return nil
    }
    client := e.session.Client()
    _, err = client.Delete(ctx, e.leaderKey)
    e.leaderKey = ""
    e.leaderSession = nil
    return err
}

// Leader returns the leader value for the current election.
func (e *Election) Leader(ctx context.Context) (string, error) {
    client := e.session.Client()
    resp, err := client.Get(ctx, e.keyPrefix, v3.WithFirstCreate()...)
    if err != nil {
        return "", err
    } else if len(resp.Kvs) == 0 {
        // no leader currently elected
        return "", ErrElectionNoLeader
    }
    return string(resp.Kvs[0].Value), nil
}

// Observe returns a channel that observes all leader proposal values as
// GetResponse values on the current leader key. The channel closes when
// the context is cancelled or the underlying watcher is otherwise disrupted.
func (e *Election) Observe(ctx context.Context) <-chan v3.GetResponse {
    retc := make(chan v3.GetResponse)
    go e.observe(ctx, retc)
    return retc
}

func (e *Election) observe(ctx context.Context, ch chan<- v3.GetResponse) {
    client := e.session.Client()

    defer close(ch)
    for {
        resp, err := client.Get(ctx, e.keyPrefix, v3.WithFirstCreate()...)
        if err != nil {
            return
        }

        var kv *mvccpb.KeyValue

        cctx, cancel := context.WithCancel(ctx)
        if len(resp.Kvs) == 0 {
            // wait for first key put on prefix
            opts := []v3.OpOption{v3.WithRev(resp.Header.Revision), v3.WithPrefix()}
            wch := client.Watch(cctx, e.keyPrefix, opts...)

            for kv == nil {
                wr, ok := <-wch
                if !ok || wr.Err() != nil {
                    cancel()
                    return
                }
                // only accept PUTs; a DELETE will make observe() spin
                for _, ev := range wr.Events {
                    if ev.Type == mvccpb.PUT {
                        kv = ev.Kv
                        break
                    }
                }
            }
        } else {
            kv = resp.Kvs[0]
        }

        wch := client.Watch(cctx, string(kv.Key), v3.WithRev(kv.ModRevision))
        keyDeleted := false
        for !keyDeleted {
            wr, ok := <-wch
            if !ok {
                return
            }
            for _, ev := range wr.Events {
                if ev.Type == mvccpb.DELETE {
                    keyDeleted = true
                    break
                }
                resp.Header = &wr.Header
                resp.Kvs = []*mvccpb.KeyValue{ev.Kv}
                select {
                case ch <- *resp:
                case <-cctx.Done():
                    return
                }
            }
        }
        cancel()
    }
}

// Key returns the leader key if elected, empty string otherwise.
func (e *Election) Key() string { return e.leaderKey }

election.go的更多相关文章

  1. [译]ZOOKEEPER RECIPES-Leader Election

    选主 使用ZooKeeper选主的一个简单方法是,在创建znode时使用Sequence和Ephemeral标志.主要思想是,使用一个znode,比如"/election",每个客 ...

  2. hihoCoder 1426 : What a Ridiculous Election(总统夶选)

    hihoCoder #1426 : What a Ridiculous Election(总统夶选) 时间限制:1000ms 单点时限:1000ms 内存限制:256MB Description - ...

  3. berkeley db replica机制 - election algorithm

    repmgr_method.c, __repmgr_start_int() 初始2个elect线程. repmgr_elect.c, __repmgr_init_election() __repmgr ...

  4. Election Time

    Election Time Time Limit: 1000MS Memory limit: 65536K 题目描述 The cows are having their first election ...

  5. zookeeper 集群 Cannot open channel to X at election address Error contacting service. It is probably not running.

    zookeeper集群   启动 1.问题现象. 启动每一个都提示  STARTED 但是查看 status时全部节点都报错 [root@ip-172-31-19-246 bin]# sh zkSer ...

  6. bzoj1675 [Usaco2005 Feb]Rigging the Bovine Election 竞选划区

    Description It's election time. The farm is partitioned into a 5x5 grid of cow locations, each of wh ...

  7. 1675: [Usaco2005 Feb]Rigging the Bovine Election 竞选划区(题解第二弹)

    1675: [Usaco2005 Feb]Rigging the Bovine Election 竞选划区 Time Limit: 5 Sec  Memory Limit: 64 MBSubmit:  ...

  8. 1675: [Usaco2005 Feb]Rigging the Bovine Election 竞选划区(题解第一弹)

    1675: [Usaco2005 Feb]Rigging the Bovine Election 竞选划区 Time Limit: 5 Sec  Memory Limit: 64 MBSubmit:  ...

  9. A Bayesian election prediction, implemented with R and Stan

    If the media coverage is anything to go by, people are desperate to know who will win the US electio ...

  10. bzoj:1675 [Usaco2005 Feb]Rigging the Bovine Election 竞选划区

    Description It's election time. The farm is partitioned into a 5x5 grid of cow locations, each of wh ...

随机推荐

  1. IIS部署asp.net mvc网站

    iis配置简单的ASP.NET MVC网站编译器:VS 2013本地IIS:IIS 7操作系统:win 7MVC版本:ASP.NET MVC4sql server版本: 2008 r2 打开VS 20 ...

  2. wait和notify的理解与使用

    1.对于wait()和notify()的理解 对于wait()和notify()的理解,还是要从jdk官方文档中开始,在Object类方法中有: void notify() Wakes up a si ...

  3. Spring Boot通过命令行启动发生FileNotFoundException

    Spring Boot + Jersey 通过命令行启动会发生错误FileNotFoundException异常 异常信息如下: ERROR o.a.c.c.C.[Tomcat].[localhost ...

  4. reorder list(链表重新排序)

    Given a singly linked list L: L0→L1→-→Ln-1→Ln,reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→- You must do thi ...

  5. 手机号 验证函数 C++

    直接上代码 #include <regex> bool IsValidPhoneNumber(const std::string& strPhone) { std::regex  ...

  6. SAE提供服务分析

    这个分析列表主要关注两个问题,服务能做什么,移植实现难度. AppConfig: 这个东西主要面向SAE本身的一些配置选项,移植时放弃这个东西,所以就不谈难度了Counter :这个东西提供某个操作的 ...

  7. 简单而强大的bitset

    简单而强大的bitset 介绍 有些程序需要处理二进制有序集,标准库提供了bitset 类型,事实上,bitset 是一个二进制容器,容器中每一个元素都是一位二进制码,或为 0,或为 1. 基础 bi ...

  8. memcached server install(WSL)

    prepare:0) libevent-dev1) libseccomp-dev2) build-essential3) automake install: https://www.liquidweb ...

  9. cxf webservice生成客户端代码及调用服务端遇到的问题

    1.  从网上下载cxf开发的工具 apache-cxf-3.1.4.zip, 解压文件,找到apache-cxf-3.1.4\bin目录,里面包含一个wsdl2java文件 2. 设置环境变量 1. ...

  10. 2017阿里Java编程题第2题

    题意是给一组数字+符号(自增1:^,相乘*,相加+)和一个长度为16的stack.栈空取数返回-1,栈满推数返回-2. 输入样例是1 1 + 2 ^ 3 * 这样子,做的时候紧张忽略了空格,用char ...