forked from hashicorp/consul-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
catalog_nodes.go
182 lines (150 loc) · 3.66 KB
/
catalog_nodes.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
package dependency
import (
"encoding/gob"
"errors"
"fmt"
"log"
"regexp"
"sort"
"sync"
"github.com/hashicorp/consul/api"
)
func init() {
gob.Register([]*Node{})
}
// Node is a node entry in Consul
type Node struct {
Node string
Address string
TaggedAddresses map[string]string
}
// CatalogNodes is the representation of all registered nodes in Consul.
type CatalogNodes struct {
sync.Mutex
rawKey string
DataCenter string
stopped bool
stopCh chan struct{}
}
// Fetch queries the Consul API defined by the given client and returns a slice
// of Node objects
func (d *CatalogNodes) Fetch(clients *ClientSet, opts *QueryOptions) (interface{}, *ResponseMetadata, error) {
d.Lock()
if d.stopped {
defer d.Unlock()
return nil, nil, ErrStopped
}
d.Unlock()
if opts == nil {
opts = &QueryOptions{}
}
consulOpts := opts.consulQueryOptions()
if d.DataCenter != "" {
consulOpts.Datacenter = d.DataCenter
}
consul, err := clients.Consul()
if err != nil {
return nil, nil, fmt.Errorf("catalog nodes: error getting client: %s", err)
}
var n []*api.Node
var qm *api.QueryMeta
dataCh := make(chan struct{})
go func() {
log.Printf("[DEBUG] (%s) querying Consul with %+v", d.Display(), consulOpts)
n, qm, err = consul.Catalog().Nodes(consulOpts)
close(dataCh)
}()
select {
case <-d.stopCh:
return nil, nil, ErrStopped
case <-dataCh:
}
if err != nil {
return nil, nil, fmt.Errorf("catalog nodes: error fetching: %s", err)
}
log.Printf("[DEBUG] (%s) Consul returned %d nodes", d.Display(), len(n))
nodes := make([]*Node, 0, len(n))
for _, node := range n {
nodes = append(nodes, &Node{
Node: node.Node,
Address: node.Address,
TaggedAddresses: node.TaggedAddresses,
})
}
sort.Stable(NodeList(nodes))
rm := &ResponseMetadata{
LastIndex: qm.LastIndex,
LastContact: qm.LastContact,
}
return nodes, rm, nil
}
// CanShare returns a boolean if this dependency is shareable.
func (d *CatalogNodes) CanShare() bool {
return true
}
// HashCode returns a unique identifier.
func (d *CatalogNodes) HashCode() string {
return fmt.Sprintf("CatalogNodes|%s", d.rawKey)
}
// Display prints the human-friendly output.
func (d *CatalogNodes) Display() string {
if d.rawKey == "" {
return fmt.Sprintf(`"nodes"`)
}
return fmt.Sprintf(`"nodes(%s)"`, d.rawKey)
}
// Stop halts the dependency's fetch function.
func (d *CatalogNodes) Stop() {
d.Lock()
defer d.Unlock()
if !d.stopped {
close(d.stopCh)
d.stopped = true
}
}
// ParseCatalogNodes parses a string of the format @dc.
func ParseCatalogNodes(s ...string) (*CatalogNodes, error) {
switch len(s) {
case 0:
cn := &CatalogNodes{
rawKey: "",
stopCh: make(chan struct{}),
}
return cn, nil
case 1:
dc := s[0]
re := regexp.MustCompile(`\A` +
`(@(?P<datacenter>[[:word:]\.\-]+))?` +
`\z`)
names := re.SubexpNames()
match := re.FindAllStringSubmatch(dc, -1)
if len(match) == 0 {
return nil, errors.New("invalid node dependency format")
}
r := match[0]
m := map[string]string{}
for i, n := range r {
if names[i] != "" {
m[names[i]] = n
}
}
cn := &CatalogNodes{
rawKey: dc,
DataCenter: m["datacenter"],
stopCh: make(chan struct{}),
}
return cn, nil
default:
return nil, fmt.Errorf("expected 0 or 1 arguments, got %d", len(s))
}
}
// NodeList is a sortable list of node objects by name and then IP address.
type NodeList []*Node
func (s NodeList) Len() int { return len(s) }
func (s NodeList) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s NodeList) Less(i, j int) bool {
if s[i].Node == s[j].Node {
return s[i].Address <= s[j].Address
}
return s[i].Node <= s[j].Node
}