forked from rqlite/gorqlite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcluster.go
264 lines (210 loc) · 7.16 KB
/
cluster.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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package gorqlite
/*
this file holds most of the cluster-related stuff:
types:
peer
rqliteCluster
Connection methods:
assembleURL (from a peer)
updateClusterInfo (does the full cluster discovery via status)
*/
/* *****************************************************************
imports
* *****************************************************************/
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net"
"net/url"
"strings"
)
/* *****************************************************************
type: peer
this is an internal type to abstact peer info.
note that hostname is sometimes used for "has this struct been
inialized" checks.
* *****************************************************************/
type peer struct {
hostname string // hostname or "localhost"
port string // "4001" or port, only ever used as a string
}
func (p *peer) String() string {
return fmt.Sprintf("%s:%s", p.hostname, p.port)
}
/* *****************************************************************
type: rqliteCluster
internal type that abstracts the full cluster state (leader, peers)
* *****************************************************************/
type rqliteCluster struct {
leader peer
otherPeers []peer
conn *Connection
}
/* *****************************************************************
method: rqliteCluster.makePeerList()
in the api calls, we'll want to try the leader first, then the other
peers. to make looping easy, this function returns a list of peers
in the order the try them: leader, other peer, other peer, etc.
* *****************************************************************/
func (rc *rqliteCluster) makePeerList() []peer {
trace("%s: makePeerList() called", rc.conn.ID)
var peerList []peer
peerList = append(peerList, rc.leader)
for _, p := range rc.otherPeers {
peerList = append(peerList, p)
}
trace("%s: makePeerList() returning this list:", rc.conn.ID)
for n, v := range peerList {
trace("%s: makePeerList() peer %d -> %s", rc.conn.ID, n, v.hostname+":"+v.port)
}
return peerList
}
/* *****************************************************************
method: Connection.assembleURL()
tell it what peer to talk to and what kind of API operation you're
making, and it will return the full URL, from start to finish.
e.g.:
https://mary:[email protected]:1234/db/query?transaction&level=strong
note: this func needs to live at the Connection level because the
Connection holds the username, password, consistencyLevel, etc.
* *****************************************************************/
func (conn *Connection) assembleURL(apiOp apiOperation, p peer) string {
var stringBuffer bytes.Buffer
if conn.wantsHTTPS == true {
stringBuffer.WriteString("https")
} else {
stringBuffer.WriteString("http")
}
stringBuffer.WriteString("://")
if conn.username != "" && conn.password != "" {
stringBuffer.WriteString(conn.username)
stringBuffer.WriteString(":")
stringBuffer.WriteString(conn.password)
stringBuffer.WriteString("@")
}
stringBuffer.WriteString(p.hostname)
stringBuffer.WriteString(":")
stringBuffer.WriteString(p.port)
switch apiOp {
case api_STATUS:
stringBuffer.WriteString("/status")
case api_NODES:
stringBuffer.WriteString("/nodes")
case api_QUERY:
stringBuffer.WriteString("/db/query")
case api_WRITE:
stringBuffer.WriteString("/db/execute")
}
if apiOp == api_QUERY || apiOp == api_WRITE {
stringBuffer.WriteString("?timings&level=")
stringBuffer.WriteString(consistencyLevelNames[conn.consistencyLevel])
if conn.wantsTransactions {
stringBuffer.WriteString("&transaction")
}
}
switch apiOp {
case api_QUERY:
trace("%s: assembled URL for an api_QUERY: %s", conn.ID, stringBuffer.String())
case api_STATUS:
trace("%s: assembled URL for an api_STATUS: %s", conn.ID, stringBuffer.String())
case api_NODES:
trace("%s: assembled URL for an api_NODES: %s", conn.ID, stringBuffer.String())
case api_WRITE:
trace("%s: assembled URL for an api_WRITE: %s", conn.ID, stringBuffer.String())
}
return stringBuffer.String()
}
/* *****************************************************************
method: Connection.updateClusterInfo()
upon invocation, updateClusterInfo() completely erases and refreshes
the Connection's cluster info, replacing its rqliteCluster object
with current info.
the web heavy lifting (retrying, etc.) is done in rqliteApiGet()
* *****************************************************************/
func (conn *Connection) updateClusterInfo() error {
trace("%s: updateClusterInfo() called", conn.ID)
// start with a fresh new cluster
var rc rqliteCluster
rc.conn = conn
responseBody, err := conn.rqliteApiGet(api_STATUS)
if err != nil {
return err
}
trace("%s: updateClusterInfo() back from api call OK", conn.ID)
sections := make(map[string]interface{})
err = json.Unmarshal(responseBody, §ions)
if err != nil {
return err
}
sMap := sections["store"].(map[string]interface{})
leaderMap, ok := sMap["leader"].(map[string]interface{})
var leaderRaftAddr string
if ok {
leaderRaftAddr = leaderMap["node_id"].(string)
} else {
leaderRaftAddr = sMap["leader"].(string)
}
trace("%s: leader from store section is %s", conn.ID, leaderRaftAddr)
// In 5.x and earlier, "metadata" is available
// leader in this case is the RAFT address
// we want the HTTP address, so we'll use this as
// a key as we sift through APIPeers
apiPeers, ok := sMap["metadata"].(map[string]interface{})
if !ok {
apiPeers = map[string]interface{}{}
}
if apiAddrMap, ok := apiPeers[leaderRaftAddr]; ok {
if _httpAddr, ok := apiAddrMap.(map[string]interface{}); ok {
if peerHttp, ok := _httpAddr["api_addr"]; ok {
parts := strings.Split(peerHttp.(string), ":")
rc.leader = peer{parts[0], parts[1]}
}
}
}
if rc.leader.hostname == "" {
// nodes/ API is available in 6.0+
trace("getting leader from metadata failed, trying nodes/")
responseBody, err := conn.rqliteApiGet(api_NODES)
if err != nil {
return errors.New("could not determine leader from API nodes call")
}
trace("%s: updateClusterInfo() back from api call OK", conn.ID)
nodes := make(map[string]struct {
APIAddr string `json:"api_addr,omitempty"`
Addr string `json:"addr,omitempty"`
Reachable bool `json:"reachable,omitempty"`
Leader bool `json:"leader"`
})
err = json.Unmarshal(responseBody, &nodes)
if err != nil {
return errors.New("could not unmarshal nodes/ response")
}
for _, v := range nodes {
if v.Leader {
u, err := url.Parse(v.APIAddr)
if err != nil {
return errors.New("could not parse API address")
}
trace("nodes/ indicates %s as API Addr", u.String())
var host, port string
if host, port, err = net.SplitHostPort(u.Host); err != nil {
return fmt.Errorf("could not split host: %s", err)
}
rc.leader = peer{host, port}
}
}
} else {
trace("leader successfully determined using metadata")
}
// dump to trace
trace("%s: here is my cluster config:", conn.ID)
trace("%s: leader : %s", conn.ID, rc.leader.String())
for n, v := range rc.otherPeers {
trace("%s: otherPeer #%d: %s", conn.ID, n, v.String())
}
// now make it official
conn.cluster = rc
return nil
}