forked from etcd-io/etcd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_handlers.go
304 lines (237 loc) · 6.78 KB
/
client_handlers.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
package main
import (
"github.com/coreos/etcd/store"
"net/http"
"strconv"
"time"
)
//-------------------------------------------------------------------
// Handlers to handle etcd-store related request via raft client port
//-------------------------------------------------------------------
// Multiplex GET/POST/DELETE request to corresponding handlers
func Multiplexer(w http.ResponseWriter, req *http.Request) {
if req.Method == "GET" {
GetHttpHandler(&w, req)
} else if req.Method == "POST" {
SetHttpHandler(&w, req)
} else if req.Method == "DELETE" {
DeleteHttpHandler(&w, req)
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
}
//--------------------------------------
// State sensitive handlers
// Set/Delete will dispatch to leader
//--------------------------------------
// Set Command Handler
func SetHttpHandler(w *http.ResponseWriter, req *http.Request) {
key := req.URL.Path[len("/v1/keys/"):]
debug("[recv] POST http://%v/v1/keys/%s", raftServer.Name(), key)
value := req.FormValue("value")
if len(value) == 0 {
(*w).WriteHeader(http.StatusBadRequest)
(*w).Write(newJsonError(200, "Set"))
return
}
prevValue := req.FormValue("prevValue")
strDuration := req.FormValue("ttl")
expireTime, err := durationToExpireTime(strDuration)
if err != nil {
(*w).WriteHeader(http.StatusBadRequest)
(*w).Write(newJsonError(202, "Set"))
}
if len(prevValue) != 0 {
command := &TestAndSetCommand{}
command.Key = key
command.Value = value
command.PrevValue = prevValue
command.ExpireTime = expireTime
dispatch(command, w, req, true)
} else {
command := &SetCommand{}
command.Key = key
command.Value = value
command.ExpireTime = expireTime
dispatch(command, w, req, true)
}
}
// Delete Handler
func DeleteHttpHandler(w *http.ResponseWriter, req *http.Request) {
key := req.URL.Path[len("/v1/keys/"):]
debug("[recv] DELETE http://%v/v1/keys/%s", raftServer.Name(), key)
command := &DeleteCommand{}
command.Key = key
dispatch(command, w, req, true)
}
// Dispatch the command to leader
func dispatch(c Command, w *http.ResponseWriter, req *http.Request, client bool) {
if raftServer.State() == "leader" {
if body, err := raftServer.Do(c); err != nil {
if _, ok := err.(store.NotFoundError); ok {
http.NotFound((*w), req)
return
}
if _, ok := err.(store.TestFail); ok {
(*w).WriteHeader(http.StatusBadRequest)
(*w).Write(newJsonError(101, err.Error()))
return
}
if _, ok := err.(store.NotFile); ok {
(*w).WriteHeader(http.StatusBadRequest)
(*w).Write(newJsonError(102, err.Error()))
return
}
(*w).WriteHeader(http.StatusInternalServerError)
(*w).Write(newJsonError(300, err.Error()))
return
} else {
if body == nil {
http.NotFound((*w), req)
} else {
body, ok := body.([]byte)
// this should not happen
if !ok {
panic("wrong type")
}
(*w).WriteHeader(http.StatusOK)
(*w).Write(body)
}
return
}
} else {
// current no leader
if raftServer.Leader() == "" {
(*w).WriteHeader(http.StatusInternalServerError)
(*w).Write(newJsonError(300, ""))
return
}
// tell the client where is the leader
path := req.URL.Path
var scheme string
if scheme = req.URL.Scheme; scheme == "" {
scheme = "http://"
}
var url string
if client {
clientAddr, _ := getClientAddr(raftServer.Leader())
url = scheme + clientAddr + path
} else {
url = scheme + raftServer.Leader() + path
}
debug("Redirect to %s", url)
http.Redirect(*w, req, url, http.StatusTemporaryRedirect)
return
}
(*w).WriteHeader(http.StatusInternalServerError)
(*w).Write(newJsonError(300, ""))
return
}
//--------------------------------------
// State non-sensitive handlers
// will not dispatch to leader
// TODO: add sensitive version for these
// command?
//--------------------------------------
// Handler to return the current leader name
func LeaderHttpHandler(w http.ResponseWriter, req *http.Request) {
leader := raftServer.Leader()
if leader != "" {
w.WriteHeader(http.StatusOK)
w.Write([]byte(raftServer.Leader()))
} else {
// not likely, but it may happen
w.WriteHeader(http.StatusInternalServerError)
w.Write(newJsonError(301, ""))
}
}
// Handler to return all the known machines in the current cluster
func MachinesHttpHandler(w http.ResponseWriter, req *http.Request) {
peers := raftServer.Peers()
// Add itself to the machine list first
// Since peer map does not contain the server itself
machines, _ := getClientAddr(raftServer.Name())
// Add all peers to the list and separate by comma
// We do not use json here since we accept machines list
// in the command line separate by comma.
for peerName, _ := range peers {
if addr, ok := getClientAddr(peerName); ok {
machines = machines + "," + addr
}
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(machines))
}
// Get Handler
func GetHttpHandler(w *http.ResponseWriter, req *http.Request) {
key := req.URL.Path[len("/v1/keys/"):]
debug("[recv] GET http://%v/v1/keys/%s", raftServer.Name(), key)
command := &GetCommand{}
command.Key = key
if body, err := command.Apply(raftServer); err != nil {
if _, ok := err.(store.NotFoundError); ok {
http.NotFound((*w), req)
return
}
(*w).WriteHeader(http.StatusInternalServerError)
(*w).Write(newJsonError(300, ""))
return
} else {
body, ok := body.([]byte)
if !ok {
panic("wrong type")
}
(*w).WriteHeader(http.StatusOK)
(*w).Write(body)
return
}
}
// Watch handler
func WatchHttpHandler(w http.ResponseWriter, req *http.Request) {
key := req.URL.Path[len("/v1/watch/"):]
command := &WatchCommand{}
command.Key = key
if req.Method == "GET" {
debug("[recv] GET http://%v/watch/%s", raftServer.Name(), key)
command.SinceIndex = 0
} else if req.Method == "POST" {
// watch from a specific index
debug("[recv] POST http://%v/watch/%s", raftServer.Name(), key)
content := req.FormValue("index")
sinceIndex, err := strconv.ParseUint(string(content), 10, 64)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write(newJsonError(203, "Watch From Index"))
}
command.SinceIndex = sinceIndex
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if body, err := command.Apply(raftServer); err != nil {
warn("Unable to do watch command: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
} else {
w.WriteHeader(http.StatusOK)
body, ok := body.([]byte)
if !ok {
panic("wrong type")
}
w.Write(body)
return
}
}
// Convert string duration to time format
func durationToExpireTime(strDuration string) (time.Time, error) {
if strDuration != "" {
duration, err := strconv.Atoi(strDuration)
if err != nil {
return time.Unix(0, 0), err
}
return time.Now().Add(time.Second * (time.Duration)(duration)), nil
} else {
return time.Unix(0, 0), nil
}
}