forked from ailidani/paxi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
367 lines (334 loc) · 7.86 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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
package paxi
import (
"bytes"
"encoding/json"
"errors"
"io"
"io/ioutil"
"math/rand"
"net/http"
"net/http/httputil"
"strconv"
"sync"
"github.com/ailidani/paxi/lib"
"github.com/ailidani/paxi/log"
)
// Client interface provides get and put for key value store
type Client interface {
Get(Key) (Value, error)
Put(Key, Value) error
}
// AdminClient interface provides fault injection opeartion
type AdminClient interface {
Consensus(Key) bool
Crash(ID, int)
Drop(ID, ID, int)
Partition(int, ...ID)
}
// HTTPClient inplements Client interface with REST API
type HTTPClient struct {
Addrs map[ID]string
HTTP map[ID]string
ID ID // client id use the same id as servers in local site
N int // total number of nodes
LocalN int // number of nodes in local zone
CID int // command id
*http.Client
}
// NewHTTPClient creates a new Client from config
func NewHTTPClient(id ID) *HTTPClient {
c := &HTTPClient{
ID: id,
N: len(config.Addrs),
Addrs: config.Addrs,
HTTP: config.HTTPAddrs,
Client: &http.Client{},
}
if id != "" {
i := 0
for node := range c.Addrs {
if node.Zone() == id.Zone() {
i++
}
}
c.LocalN = i
}
return c
}
// Get gets value of given key (use REST)
// Default implementation of Client interface
func (c *HTTPClient) Get(key Key) (Value, error) {
c.CID++
v, _, err := c.RESTGet(c.ID, key)
return v, err
}
// Put puts new key value pair and return previous value (use REST)
// Default implementation of Client interface
func (c *HTTPClient) Put(key Key, value Value) error {
c.CID++
_, _, err := c.RESTPut(c.ID, key, value)
return err
}
func (c *HTTPClient) GetURL(id ID, key Key) string {
if id == "" {
for id = range c.HTTP {
if c.ID == "" || id.Zone() == c.ID.Zone() {
break
}
}
i := rand.Intn(len(c.HTTP))
for id = range c.HTTP {
if i == 0 {
break
}
i--
}
}
return c.HTTP[id] + "/" + strconv.Itoa(int(key))
}
// rest accesses server's REST API with url = http://ip:port/key
// if value == nil, it's a read
func (c *HTTPClient) rest(id ID, key Key, value Value) (Value, map[string]string, error) {
// get url
url := c.GetURL(id, key)
method := http.MethodGet
var body io.Reader
if value != nil {
method = http.MethodPut
body = bytes.NewBuffer(value)
}
req, err := http.NewRequest(method, url, body)
if err != nil {
log.Error(err)
return nil, nil, err
}
req.Header.Set(HTTPClientID, string(c.ID))
req.Header.Set(HTTPCommandID, strconv.Itoa(c.CID))
// r.Header.Set(HTTPTimestamp, strconv.FormatInt(time.Now().UnixNano(), 10))
rep, err := c.Client.Do(req)
if err != nil {
log.Error(err)
return nil, nil, err
}
defer rep.Body.Close()
// get headers
metadata := make(map[string]string)
for k := range rep.Header {
metadata[k] = rep.Header.Get(k)
}
if rep.StatusCode == http.StatusOK {
b, err := ioutil.ReadAll(rep.Body)
if err != nil {
log.Error(err)
return nil, metadata, err
}
if value == nil {
log.Debugf("node=%v type=%s key=%v value=%x", id, method, key, Value(b))
} else {
log.Debugf("node=%v type=%s key=%v value=%x", id, method, key, value)
}
return Value(b), metadata, nil
}
// http call failed
dump, _ := httputil.DumpResponse(rep, true)
log.Debugf("%q", dump)
return nil, metadata, errors.New(rep.Status)
}
// RESTGet issues a http call to node and return value and headers
func (c *HTTPClient) RESTGet(id ID, key Key) (Value, map[string]string, error) {
return c.rest(id, key, nil)
}
// RESTPut puts new value as http.request body and return previous value
func (c *HTTPClient) RESTPut(id ID, key Key, value Value) (Value, map[string]string, error) {
return c.rest(id, key, value)
}
func (c *HTTPClient) json(id ID, key Key, value Value) (Value, error) {
url := c.HTTP[id]
cmd := Command{
Key: key,
Value: value,
ClientID: c.ID,
CommandID: c.CID,
}
data, err := json.Marshal(cmd)
res, err := c.Client.Post(url, "json", bytes.NewBuffer(data))
if err != nil {
log.Error(err)
return nil, err
}
defer res.Body.Close()
if res.StatusCode == http.StatusOK {
b, _ := ioutil.ReadAll(res.Body)
log.Debugf("key=%v value=%x", key, Value(b))
return Value(b), nil
}
dump, _ := httputil.DumpResponse(res, true)
log.Debugf("%q", dump)
return nil, errors.New(res.Status)
}
// JSONGet posts get request in json format to server url
func (c *HTTPClient) JSONGet(key Key) (Value, error) {
return c.json(c.ID, key, nil)
}
// JSONPut posts put request in json format to server url
func (c *HTTPClient) JSONPut(key Key, value Value) (Value, error) {
return c.json(c.ID, key, value)
}
// QuorumGet concurrently read values from majority nodes
func (c *HTTPClient) QuorumGet(key Key) ([]Value, []map[string]string) {
return c.MultiGet(c.N/2+1, key)
}
// MultiGet concurrently read values from n nodes
func (c *HTTPClient) MultiGet(n int, key Key) ([]Value, []map[string]string) {
valueC := make(chan Value)
metaC := make(chan map[string]string)
i := 0
for id := range c.HTTP {
go func(id ID) {
v, meta, err := c.rest(id, key, nil)
if err != nil {
log.Error(err)
return
}
valueC <- v
metaC <- meta
}(id)
i++
if i >= n {
break
}
}
values := make([]Value, 0)
metas := make([]map[string]string, 0)
for ; i > 0; i-- {
values = append(values, <-valueC)
metas = append(metas, <-metaC)
}
return values, metas
}
func (c *HTTPClient) LocalQuorumGet(key Key) ([]Value, []map[string]string) {
valueC := make(chan Value)
metaC := make(chan map[string]string)
i := 0
for id := range c.HTTP {
if c.ID.Zone() != id.Zone() {
continue
}
i++
if i > c.LocalN/2 {
break
}
go func(id ID) {
v, meta, err := c.rest(id, key, nil)
if err != nil {
log.Error(err)
return
}
valueC <- v
metaC <- meta
}(id)
}
values := make([]Value, 0)
metas := make([]map[string]string, 0)
for ; i >= 0; i-- {
values = append(values, <-valueC)
metas = append(metas, <-metaC)
}
return values, metas
}
// QuorumPut concurrently write values to majority of nodes
// TODO get headers
func (c *HTTPClient) QuorumPut(key Key, value Value) {
var wait sync.WaitGroup
i := 0
for id := range c.HTTP {
i++
if i > c.N/2 {
break
}
wait.Add(1)
go func(id ID) {
c.rest(id, key, value)
wait.Done()
}(id)
}
wait.Wait()
}
// Consensus collects /history/key from every node and compare their values
func (c *HTTPClient) Consensus(k Key) bool {
h := make(map[ID][]Value)
for id, url := range c.HTTP {
h[id] = make([]Value, 0)
r, err := c.Client.Get(url + "/history?key=" + strconv.Itoa(int(k)))
if err != nil {
log.Error(err)
continue
}
b, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Error(err)
continue
}
holder := h[id]
err = json.Unmarshal(b, &holder)
if err != nil {
log.Error(err)
continue
}
h[id] = holder
log.Debugf("node=%v key=%v h=%v", id, k, holder)
}
n := 0
for _, v := range h {
if len(v) > n {
n = len(v)
}
}
for i := 0; i < n; i++ {
set := make(map[string]struct{})
for id := range c.HTTP {
if len(h[id]) > i {
set[string(h[id][i])] = struct{}{}
}
}
if len(set) > 1 {
return false
}
}
return true
}
// Crash stops the node for t seconds then recover
// node crash forever if t < 0
func (c *HTTPClient) Crash(id ID, t int) {
url := c.HTTP[id] + "/crash?t=" + strconv.Itoa(t)
r, err := c.Client.Get(url)
if err != nil {
log.Error(err)
return
}
r.Body.Close()
}
// Drop drops every message send for t seconds
func (c *HTTPClient) Drop(from, to ID, t int) {
url := c.HTTP[from] + "/drop?id=" + string(to) + "&t=" + strconv.Itoa(t)
r, err := c.Client.Get(url)
if err != nil {
log.Error(err)
return
}
r.Body.Close()
}
// Partition cuts the network between nodes for t seconds
func (c *HTTPClient) Partition(t int, nodes ...ID) {
s := lib.NewSet()
for _, id := range nodes {
s.Add(id)
}
for from := range c.Addrs {
if !s.Has(from) {
for _, to := range nodes {
c.Drop(from, to, t)
}
}
}
}