forked from Onyx-Protocol/Onyx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lookup.go
166 lines (140 loc) · 4.21 KB
/
lookup.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
package etcdname
import (
"context"
"encoding/json"
"errors"
"net"
"os"
"strconv"
"strings"
"time"
"github.com/coreos/etcd/client"
"chain/log"
)
var (
etcd client.Client
initErr error
)
func init() {
u := os.Getenv("ETCD_URLS")
if u == "" {
return
}
cfg := client.Config{
Endpoints: strings.Split(u, ","),
Transport: client.DefaultTransport,
HeaderTimeoutPerRequest: time.Second,
}
etcd, initErr = client.New(cfg)
}
// LookupHost looks up the given host using the configured etcd cluster, if any.
// It retrieves the address for a host by checking etcd's services directory, and
// returns an array of the provided host's addresses.
//
// when querying etcd, LookupHost expects the response from the services directory
// to be one of three things:
// 1. an IP address or comma-delimted string of IP addresses
// (like "127.0.0.1,128.0.0.1")
// 2. an etcd key (like "/fooDB/primary")
// 3. an etcd key and a JSON pointer, separated with a # (like
// "/fooDB/primary#primaryIP")
//
// If the services directory contains an IP address or string of addresses,
// LookupHost returns them. Otherwise, it checks the provided etcd key.
// If no JSON pointer is provided, LookupHost expects the value at that etcd key
// to be a string (a single address, or a comma-delimited string of addresses).
// Otherwise, it expects JSON, and it will parse that JSON using the provided JSON pointer.
//
// For more on JSON pointers, see RFC 6901: https://tools.ietf.org/html/rfc6901.
func LookupHost(host string) ([]string, error) {
ctx := context.TODO()
if initErr != nil {
log.Error(ctx, initErr)
return nil, initErr
} else if etcd == nil {
return nil, errors.New("etcd is not configured")
}
kapi := client.NewKeysAPI(etcd)
resp, err := kapi.Get(ctx, "/services/"+host, nil)
if err != nil {
return nil, err
}
if resp.Node.Value[0] != '/' {
// This isn't an etcd key.
return strings.Split(resp.Node.Value, ","), nil
}
etcdKey, jsonPointer := splitPointer(resp.Node.Value)
if err != nil {
return nil, err
}
resp, err = kapi.Get(ctx, etcdKey, nil)
if err != nil {
return nil, err
}
if jsonPointer == "" {
// If there's no JSON Pointer, just return the response from etcd.
return strings.Split(resp.Node.Value, ","), nil
}
addrs, err := unmarshalFromPointer([]byte(resp.Node.Value), jsonPointer)
if err != nil {
return nil, err
}
as := strings.Split(addrs, ",")
for _, a := range as {
if net.ParseIP(a) == nil {
return nil, errors.New("bad address: " + a)
}
}
return as, nil
}
// splitPointer splits a response from etcd's services directory into
// an etcd key and a JSON Pointer. If there isn't a JSON Pointer,
// parsePath will return an empty string as the JSON Pointer.
// If there's more than one JSON Pointer, parsePath will return
// an error.
func splitPointer(path string) (etcdKey, jsonPointer string) {
if idx := strings.IndexByte(path, '#'); idx >= 0 {
return path[:idx], path[idx+1:]
}
return path, ""
}
// unmarshalFromPointer parses a value inside the JSON-encoded data using the
// given pointer. See the JSON Pointer RFC (https://tools.ietf.org/html/rfc6901) for more.
func unmarshalFromPointer(data []byte, pointer string) (string, error) {
var v interface{}
err := json.Unmarshal(data, &v)
if err != nil {
return "", err
}
res := followJSONPointer(v, strings.Split(pointer, "/"))
if res == "" {
return "", errors.New("could not find value at that JSON pointer")
}
return res, nil
}
// followJSONPointer traverses the result of json.Unmarshal, looking for the value
// specified by the pointer. If it cannot find anything, it returns the empty string.
func followJSONPointer(v interface{}, pointer []string) string {
if len(pointer) == 0 {
str, _ := v.(string)
return str
}
switch v := v.(type) {
case map[string]interface{}:
// this is an object
k := pointer[0]
if strings.Contains(k, "~") {
k = strings.Replace(k, "~1", "/", -1)
k = strings.Replace(k, "~0", "~", -1)
}
return followJSONPointer(v[k], pointer[1:])
case []interface{}:
// this is an array
i, err := strconv.Atoi(pointer[0])
if err != nil || i >= len(v) || i < 0 {
return ""
}
return followJSONPointer(v[i], pointer[1:])
}
return ""
}