forked from docker-archive/classicswarm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
discovery.go
78 lines (62 loc) · 1.62 KB
/
discovery.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
package discovery
import (
"errors"
"fmt"
"net"
"strings"
log "github.com/Sirupsen/logrus"
)
type Node struct {
Host string
Port string
}
func NewNode(url string) (*Node, error) {
host, port, err := net.SplitHostPort(url)
if err != nil {
return nil, err
}
return &Node{host, port}, nil
}
func (n Node) String() string {
return fmt.Sprintf("%s:%s", n.Host, n.Port)
}
type WatchCallback func(nodes []*Node)
type DiscoveryService interface {
Initialize(string, int) error
Fetch() ([]*Node, error)
Watch(WatchCallback)
Register(string) error
}
var (
discoveries map[string]DiscoveryService
ErrNotSupported = errors.New("discovery service not supported")
ErrNotImplemented = errors.New("not implemented in this discovery service")
)
func init() {
discoveries = make(map[string]DiscoveryService)
}
func Register(scheme string, d DiscoveryService) error {
if _, exists := discoveries[scheme]; exists {
return fmt.Errorf("scheme already registered %s", scheme)
}
log.Debugf("Registering %q discovery service", scheme)
discoveries[scheme] = d
return nil
}
func parse(rawurl string) (string, string) {
parts := strings.SplitN(rawurl, "://", 2)
// nodes:port,node2:port => nodes://node1:port,node2:port
if len(parts) == 1 {
return "nodes", parts[0]
}
return parts[0], parts[1]
}
func New(rawurl string, heartbeat int) (DiscoveryService, error) {
scheme, uri := parse(rawurl)
if discovery, exists := discoveries[scheme]; exists {
log.Debugf("Initializing %q discovery service with %q", scheme, uri)
err := discovery.Initialize(uri, heartbeat)
return discovery, err
}
return nil, ErrNotSupported
}