forked from gliderlabs/registrator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconsulkv.go
83 lines (71 loc) · 1.96 KB
/
consulkv.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
81
82
83
package consul
import (
"log"
"net"
"net/url"
"strconv"
"strings"
"github.com/gliderlabs/registrator/bridge"
consulapi "github.com/hashicorp/consul/api"
)
func init() {
f := new(Factory)
bridge.Register(f, "consulkv")
bridge.Register(f, "consulkv-unix")
}
type Factory struct{}
func (f *Factory) New(uri *url.URL) bridge.RegistryAdapter {
config := consulapi.DefaultConfig()
path := uri.Path
if uri.Scheme == "consulkv-unix" {
spl := strings.SplitN(uri.Path, ":", 2)
config.Address, path = "unix://"+spl[0], spl[1]
} else if uri.Host != "" {
config.Address = uri.Host
}
client, err := consulapi.NewClient(config)
if err != nil {
log.Fatal("consulkv: ", uri.Scheme)
}
return &ConsulKVAdapter{client: client, path: path}
}
type ConsulKVAdapter struct {
client *consulapi.Client
path string
}
// Ping will try to connect to consul by attempting to retrieve the current leader.
func (r *ConsulKVAdapter) Ping() error {
status := r.client.Status()
leader, err := status.Leader()
if err != nil {
return err
}
log.Println("consulkv: current leader ", leader)
return nil
}
func (r *ConsulKVAdapter) Register(service *bridge.Service) error {
log.Println("Register")
path := r.path[1:] + "/" + service.Name + "/" + service.ID
port := strconv.Itoa(service.Port)
addr := net.JoinHostPort(service.IP, port)
log.Printf("path: %s", path)
_, err := r.client.KV().Put(&consulapi.KVPair{Key: path, Value: []byte(addr)}, nil)
if err != nil {
log.Println("consulkv: failed to register service:", err)
}
return err
}
func (r *ConsulKVAdapter) Deregister(service *bridge.Service) error {
path := r.path[1:] + "/" + service.Name + "/" + service.ID
_, err := r.client.KV().Delete(path, nil)
if err != nil {
log.Println("consulkv: failed to deregister service:", err)
}
return err
}
func (r *ConsulKVAdapter) Refresh(service *bridge.Service) error {
return nil
}
func (r *ConsulKVAdapter) Services() ([]*bridge.Service, error) {
return []*bridge.Service{}, nil
}