forked from st3v/go-plugins
/
etcd.go
80 lines (66 loc) · 1.44 KB
/
etcd.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package etcd
import (
"fmt"
"time"
"github.com/coreos/etcd/client"
"github.com/micro/go-log"
"github.com/micro/go-micro/registry"
"github.com/micro/go-os/sync"
"github.com/pborman/uuid"
)
type etcdSync struct {
opts sync.Options
client client.Client
}
func (e *etcdSync) Lock(id string, opts ...sync.LockOption) (sync.Lock, error) {
var options sync.LockOptions
for _, o := range opts {
o(&options)
}
return &etcdLock{
path: e.opts.Namespace,
id: id,
node: fmt.Sprintf("%s-%d", uuid.NewUUID().String(), time.Now().UnixNano()),
api: client.NewKeysAPI(e.client),
opts: options,
}, nil
}
func (e *etcdSync) Leader(id string, opts ...sync.LeaderOption) (sync.Leader, error) {
return &etcdLeader{
path: e.opts.Namespace,
id: id,
node: ®istry.Node{Id: uuid.NewUUID().String()},
api: client.NewKeysAPI(e.client),
}, nil
}
func (e *etcdSync) String() string {
return "etcd"
}
func NewSync(opts ...sync.Option) sync.Sync {
options := sync.Options{
Namespace: sync.DefaultNamespace,
}
for _, o := range opts {
o(&options)
}
var endpoints []string
for _, addr := range options.Nodes {
if len(addr) > 0 {
endpoints = append(endpoints, addr)
}
}
if len(endpoints) == 0 {
endpoints = []string{"http://127.0.0.1:2379"}
}
// TODO: parse addresses
c, err := client.New(client.Config{
Endpoints: endpoints,
})
if err != nil {
log.Fatal(err)
}
return &etcdSync{
client: c,
opts: options,
}
}