forked from etcd-io/etcd
/
client.go
240 lines (200 loc) · 5.23 KB
/
client.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
package etcd
import (
"crypto/tls"
"errors"
"io/ioutil"
"net"
"net/http"
"path"
"strings"
"time"
)
const (
HTTP = iota
HTTPS
)
type Cluster struct {
Leader string
Machines []string
}
type Config struct {
CertFile string
KeyFile string
Scheme string
Timeout time.Duration
}
type Client struct {
cluster Cluster
config Config
httpClient *http.Client
}
// Setup a basic conf and cluster
func NewClient() *Client {
// default leader and machines
cluster := Cluster{
Leader: "0.0.0.0:4001",
Machines: make([]string, 1),
}
cluster.Machines[0] = "0.0.0.0:4001"
config := Config{
// default use http
Scheme: "http",
// default timeout is one second
Timeout: time.Second,
}
tr := &http.Transport{
Dial: dialTimeout,
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}
return &Client{
cluster: cluster,
config: config,
httpClient: &http.Client{Transport: tr},
}
}
func (c *Client) SetCertAndKey(cert string, key string) (bool, error) {
if cert != "" && key != "" {
tlsCert, err := tls.LoadX509KeyPair(cert, key)
if err != nil {
return false, err
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{
Certificates: []tls.Certificate{tlsCert},
InsecureSkipVerify: true,
},
Dial: dialTimeout,
}
c.httpClient = &http.Client{Transport: tr}
return true, nil
}
return false, errors.New("Require both cert and key path")
}
func (c *Client) SetScheme(scheme int) (bool, error) {
if scheme == HTTP {
c.config.Scheme = "http"
return true, nil
}
if scheme == HTTPS {
c.config.Scheme = "https"
return true, nil
}
return false, errors.New("Unknown Scheme")
}
// Try to sync from the given machine
func (c *Client) SetCluster(machines []string) bool {
success := c.internalSyncCluster(machines)
return success
}
// sycn cluster information using the existing machine list
func (c *Client) SyncCluster() bool {
success := c.internalSyncCluster(c.cluster.Machines)
return success
}
// sync cluster information by providing machine list
func (c *Client) internalSyncCluster(machines []string) bool {
for _, machine := range machines {
httpPath := c.createHttpPath(machine, "machines")
resp, err := c.httpClient.Get(httpPath)
if err != nil {
// try another machine in the cluster
continue
} else {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
// try another machine in the cluster
continue
}
// update Machines List
c.cluster.Machines = strings.Split(string(b), ",")
logger.Debug("sync.machines ", c.cluster.Machines)
return true
}
}
return false
}
// serverName should contain both hostName and port
func (c *Client) createHttpPath(serverName string, _path string) string {
httpPath := path.Join(serverName, _path)
return httpPath
}
// Dial with timeout.
func dialTimeout(network, addr string) (net.Conn, error) {
return net.DialTimeout(network, addr, time.Second)
}
func (c *Client) getHttpPath(s ...string) string {
httpPath := path.Join(c.cluster.Leader, version)
for _, seg := range s {
httpPath = path.Join(httpPath, seg)
}
httpPath = c.config.Scheme + "://" + httpPath
return httpPath
}
func (c *Client) updateLeader(httpPath string) {
// httpPath http://127.0.0.1:4001/v1...
leader := strings.Split(httpPath, "://")[1]
// we want to have 127.0.0.1:4001
leader = strings.Split(leader, "/")[0]
logger.Debugf("update.leader[%s,%s]", c.cluster.Leader, leader)
c.cluster.Leader = leader
}
// Wrap GET, POST and internal error handling
func (c *Client) sendRequest(method string, _path string, body string) (*http.Response, error) {
var resp *http.Response
var err error
var req *http.Request
retry := 0
// if we connect to a follower, we will retry until we found a leader
for {
httpPath := c.getHttpPath(_path)
logger.Debug("send.request.to ", httpPath)
if body == "" {
req, _ = http.NewRequest(method, httpPath, nil)
} else {
req, _ = http.NewRequest(method, httpPath, strings.NewReader(body))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value")
}
resp, err = c.httpClient.Do(req)
logger.Debug("recv.response.from ", httpPath)
// network error, change a machine!
if err != nil {
retry++
if retry > 2*len(c.cluster.Machines) {
return nil, errors.New("Cannot reach servers")
}
num := retry % len(c.cluster.Machines)
logger.Debug("update.leader[", c.cluster.Leader, ",", c.cluster.Machines[num], "]")
c.cluster.Leader = c.cluster.Machines[num]
time.Sleep(time.Millisecond * 200)
continue
}
if resp != nil {
if resp.StatusCode == http.StatusTemporaryRedirect {
httpPath := resp.Header.Get("Location")
resp.Body.Close()
if httpPath == "" {
return nil, errors.New("Cannot get redirection location")
}
c.updateLeader(httpPath)
logger.Debug("send.redirect")
// try to connect the leader
continue
} else if resp.StatusCode == http.StatusInternalServerError {
retry++
if retry > 2*len(c.cluster.Machines) {
return nil, errors.New("Cannot reach servers")
}
resp.Body.Close()
continue
} else {
logger.Debug("send.return.response ", httpPath)
break
}
}
logger.Debug("error.from ", httpPath, " ", err.Error())
return nil, err
}
return resp, nil
}