http.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package etcdhttp
  14. import (
  15. "encoding/json"
  16. "errors"
  17. "fmt"
  18. "io/ioutil"
  19. "log"
  20. "net/http"
  21. "net/url"
  22. "path"
  23. "strconv"
  24. "strings"
  25. "time"
  26. "github.com/coreos/etcd/Godeps/_workspace/src/code.google.com/p/go.net/context"
  27. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/jonboulle/clockwork"
  28. etcdErr "github.com/coreos/etcd/error"
  29. "github.com/coreos/etcd/etcdserver"
  30. "github.com/coreos/etcd/etcdserver/etcdserverpb"
  31. "github.com/coreos/etcd/raft/raftpb"
  32. "github.com/coreos/etcd/store"
  33. )
  34. const (
  35. keysPrefix = "/v2/keys"
  36. deprecatedMachinesPrefix = "/v2/machines"
  37. adminMembersPrefix = "/v2/admin/members/"
  38. raftPrefix = "/raft"
  39. statsPrefix = "/v2/stats"
  40. // time to wait for response from EtcdServer requests
  41. defaultServerTimeout = 500 * time.Millisecond
  42. // time to wait for a Watch request
  43. defaultWatchTimeout = 5 * time.Minute
  44. )
  45. var errClosed = errors.New("etcdhttp: client closed connection")
  46. // NewClientHandler generates a muxed http.Handler with the given parameters to serve etcd client requests.
  47. func NewClientHandler(server *etcdserver.EtcdServer) http.Handler {
  48. sh := &serverHandler{
  49. server: server,
  50. clusterStore: server.ClusterStore,
  51. stats: server,
  52. timer: server,
  53. timeout: defaultServerTimeout,
  54. }
  55. mux := http.NewServeMux()
  56. mux.HandleFunc(keysPrefix, sh.serveKeys)
  57. mux.HandleFunc(keysPrefix+"/", sh.serveKeys)
  58. mux.HandleFunc(statsPrefix+"/store", sh.serveStoreStats)
  59. mux.HandleFunc(statsPrefix+"/self", sh.serveSelfStats)
  60. mux.HandleFunc(statsPrefix+"/leader", sh.serveLeaderStats)
  61. // TODO: dynamic configuration may make this outdated. take care of it.
  62. // TODO: dynamic configuration may introduce race also.
  63. // TODO: add serveMembers
  64. mux.HandleFunc(deprecatedMachinesPrefix, sh.serveMachines)
  65. mux.HandleFunc(adminMembersPrefix, sh.serveAdminMembers)
  66. mux.HandleFunc("/", http.NotFound)
  67. return mux
  68. }
  69. // NewPeerHandler generates an http.Handler to handle etcd peer (raft) requests.
  70. func NewPeerHandler(server *etcdserver.EtcdServer) http.Handler {
  71. sh := &serverHandler{
  72. server: server,
  73. stats: server,
  74. clusterStore: server.ClusterStore,
  75. }
  76. mux := http.NewServeMux()
  77. mux.HandleFunc(raftPrefix, sh.serveRaft)
  78. mux.HandleFunc("/", http.NotFound)
  79. return mux
  80. }
  81. // serverHandler provides http.Handlers for etcd client and raft communication.
  82. type serverHandler struct {
  83. timeout time.Duration
  84. server etcdserver.Server
  85. stats etcdserver.Stats
  86. timer etcdserver.RaftTimer
  87. clusterStore etcdserver.ClusterStore
  88. }
  89. func (h serverHandler) serveKeys(w http.ResponseWriter, r *http.Request) {
  90. if !allowMethod(w, r.Method, "GET", "PUT", "POST", "DELETE") {
  91. return
  92. }
  93. ctx, cancel := context.WithTimeout(context.Background(), h.timeout)
  94. defer cancel()
  95. rr, err := parseKeyRequest(r, etcdserver.GenID(), clockwork.NewRealClock())
  96. if err != nil {
  97. writeError(w, err)
  98. return
  99. }
  100. resp, err := h.server.Do(ctx, rr)
  101. if err != nil {
  102. writeError(w, err)
  103. return
  104. }
  105. switch {
  106. case resp.Event != nil:
  107. if err := writeKeyEvent(w, resp.Event, h.timer); err != nil {
  108. // Should never be reached
  109. log.Printf("error writing event: %v", err)
  110. }
  111. case resp.Watcher != nil:
  112. ctx, cancel := context.WithTimeout(context.Background(), defaultWatchTimeout)
  113. defer cancel()
  114. handleKeyWatch(ctx, w, resp.Watcher, rr.Stream, h.timer)
  115. default:
  116. writeError(w, errors.New("received response with no Event/Watcher!"))
  117. }
  118. }
  119. // serveMachines responds address list in the format '0.0.0.0, 1.1.1.1'.
  120. func (h serverHandler) serveMachines(w http.ResponseWriter, r *http.Request) {
  121. if !allowMethod(w, r.Method, "GET", "HEAD") {
  122. return
  123. }
  124. endpoints := h.clusterStore.Get().ClientURLs()
  125. w.Write([]byte(strings.Join(endpoints, ", ")))
  126. }
  127. func (h serverHandler) serveAdminMembers(w http.ResponseWriter, r *http.Request) {
  128. if !allowMethod(w, r.Method, "PUT", "DELETE") {
  129. return
  130. }
  131. ctx, cancel := context.WithTimeout(context.Background(), defaultServerTimeout)
  132. defer cancel()
  133. idStr := strings.TrimPrefix(r.URL.Path, adminMembersPrefix)
  134. id, err := strconv.ParseUint(idStr, 16, 64)
  135. if err != nil {
  136. http.Error(w, err.Error(), http.StatusBadRequest)
  137. return
  138. }
  139. switch r.Method {
  140. case "PUT":
  141. if err := r.ParseForm(); err != nil {
  142. http.Error(w, err.Error(), http.StatusBadRequest)
  143. return
  144. }
  145. peerURLs := r.PostForm["PeerURLs"]
  146. log.Printf("etcdhttp: add node %x with peer urls %v", id, peerURLs)
  147. m := etcdserver.Member{
  148. ID: id,
  149. RaftAttributes: etcdserver.RaftAttributes{
  150. PeerURLs: peerURLs,
  151. },
  152. }
  153. if err := h.server.AddMember(ctx, m); err != nil {
  154. log.Printf("etcdhttp: error adding node %x: %v", id, err)
  155. writeError(w, err)
  156. return
  157. }
  158. w.WriteHeader(http.StatusCreated)
  159. case "DELETE":
  160. log.Printf("etcdhttp: remove node %x", id)
  161. if err := h.server.RemoveMember(ctx, id); err != nil {
  162. log.Printf("etcdhttp: error removing node %x: %v", id, err)
  163. writeError(w, err)
  164. return
  165. }
  166. w.WriteHeader(http.StatusNoContent)
  167. }
  168. }
  169. func (h serverHandler) serveStoreStats(w http.ResponseWriter, r *http.Request) {
  170. if !allowMethod(w, r.Method, "GET") {
  171. return
  172. }
  173. w.Header().Set("Content-Type", "application/json")
  174. w.Write(h.stats.StoreStats())
  175. }
  176. func (h serverHandler) serveSelfStats(w http.ResponseWriter, r *http.Request) {
  177. if !allowMethod(w, r.Method, "GET") {
  178. return
  179. }
  180. w.Header().Set("Content-Type", "application/json")
  181. w.Write(h.stats.SelfStats())
  182. }
  183. func (h serverHandler) serveLeaderStats(w http.ResponseWriter, r *http.Request) {
  184. if !allowMethod(w, r.Method, "GET") {
  185. return
  186. }
  187. w.Header().Set("Content-Type", "application/json")
  188. w.Write(h.stats.LeaderStats())
  189. }
  190. func (h serverHandler) serveRaft(w http.ResponseWriter, r *http.Request) {
  191. if !allowMethod(w, r.Method, "POST") {
  192. return
  193. }
  194. gcid := r.Header.Get("X-Etcd-Cluster-ID")
  195. wcid := strconv.FormatUint(h.clusterStore.Get().ID(), 16)
  196. if gcid != wcid {
  197. log.Printf("etcdhttp: request ignored: clusterID mismatch got %s want %x", gcid, wcid)
  198. http.Error(w, "clusterID mismatch", http.StatusPreconditionFailed)
  199. return
  200. }
  201. b, err := ioutil.ReadAll(r.Body)
  202. if err != nil {
  203. log.Println("etcdhttp: error reading raft message:", err)
  204. http.Error(w, "error reading raft message", http.StatusBadRequest)
  205. return
  206. }
  207. var m raftpb.Message
  208. if err := m.Unmarshal(b); err != nil {
  209. log.Println("etcdhttp: error unmarshaling raft message:", err)
  210. http.Error(w, "error unmarshaling raft message", http.StatusBadRequest)
  211. return
  212. }
  213. log.Printf("etcdhttp: raft recv message from %#x: %+v", m.From, m)
  214. if m.Type == raftpb.MsgApp {
  215. h.stats.UpdateRecvApp(m.From, r.ContentLength)
  216. }
  217. if err := h.server.Process(context.TODO(), m); err != nil {
  218. log.Println("etcdhttp: error processing raft message:", err)
  219. writeError(w, err)
  220. return
  221. }
  222. w.WriteHeader(http.StatusNoContent)
  223. }
  224. // parseKeyRequest converts a received http.Request on keysPrefix to
  225. // a server Request, performing validation of supplied fields as appropriate.
  226. // If any validation fails, an empty Request and non-nil error is returned.
  227. func parseKeyRequest(r *http.Request, id uint64, clock clockwork.Clock) (etcdserverpb.Request, error) {
  228. emptyReq := etcdserverpb.Request{}
  229. err := r.ParseForm()
  230. if err != nil {
  231. return emptyReq, etcdErr.NewRequestError(
  232. etcdErr.EcodeInvalidForm,
  233. err.Error(),
  234. )
  235. }
  236. if !strings.HasPrefix(r.URL.Path, keysPrefix) {
  237. return emptyReq, etcdErr.NewRequestError(
  238. etcdErr.EcodeInvalidForm,
  239. "incorrect key prefix",
  240. )
  241. }
  242. p := path.Join(etcdserver.StoreKeysPrefix, r.URL.Path[len(keysPrefix):])
  243. var pIdx, wIdx uint64
  244. if pIdx, err = getUint64(r.Form, "prevIndex"); err != nil {
  245. return emptyReq, etcdErr.NewRequestError(
  246. etcdErr.EcodeIndexNaN,
  247. `invalid value for "prevIndex"`,
  248. )
  249. }
  250. if wIdx, err = getUint64(r.Form, "waitIndex"); err != nil {
  251. return emptyReq, etcdErr.NewRequestError(
  252. etcdErr.EcodeIndexNaN,
  253. `invalid value for "waitIndex"`,
  254. )
  255. }
  256. var rec, sort, wait, dir, stream bool
  257. if rec, err = getBool(r.Form, "recursive"); err != nil {
  258. return emptyReq, etcdErr.NewRequestError(
  259. etcdErr.EcodeInvalidField,
  260. `invalid value for "recursive"`,
  261. )
  262. }
  263. if sort, err = getBool(r.Form, "sorted"); err != nil {
  264. return emptyReq, etcdErr.NewRequestError(
  265. etcdErr.EcodeInvalidField,
  266. `invalid value for "sorted"`,
  267. )
  268. }
  269. if wait, err = getBool(r.Form, "wait"); err != nil {
  270. return emptyReq, etcdErr.NewRequestError(
  271. etcdErr.EcodeInvalidField,
  272. `invalid value for "wait"`,
  273. )
  274. }
  275. // TODO(jonboulle): define what parameters dir is/isn't compatible with?
  276. if dir, err = getBool(r.Form, "dir"); err != nil {
  277. return emptyReq, etcdErr.NewRequestError(
  278. etcdErr.EcodeInvalidField,
  279. `invalid value for "dir"`,
  280. )
  281. }
  282. if stream, err = getBool(r.Form, "stream"); err != nil {
  283. return emptyReq, etcdErr.NewRequestError(
  284. etcdErr.EcodeInvalidField,
  285. `invalid value for "stream"`,
  286. )
  287. }
  288. if wait && r.Method != "GET" {
  289. return emptyReq, etcdErr.NewRequestError(
  290. etcdErr.EcodeInvalidField,
  291. `"wait" can only be used with GET requests`,
  292. )
  293. }
  294. pV := r.FormValue("prevValue")
  295. if _, ok := r.Form["prevValue"]; ok && pV == "" {
  296. return emptyReq, etcdErr.NewRequestError(
  297. etcdErr.EcodeInvalidField,
  298. `"prevValue" cannot be empty`,
  299. )
  300. }
  301. // TTL is nullable, so leave it null if not specified
  302. // or an empty string
  303. var ttl *uint64
  304. if len(r.FormValue("ttl")) > 0 {
  305. i, err := getUint64(r.Form, "ttl")
  306. if err != nil {
  307. return emptyReq, etcdErr.NewRequestError(
  308. etcdErr.EcodeTTLNaN,
  309. `invalid value for "ttl"`,
  310. )
  311. }
  312. ttl = &i
  313. }
  314. // prevExist is nullable, so leave it null if not specified
  315. var pe *bool
  316. if _, ok := r.Form["prevExist"]; ok {
  317. bv, err := getBool(r.Form, "prevExist")
  318. if err != nil {
  319. return emptyReq, etcdErr.NewRequestError(
  320. etcdErr.EcodeInvalidField,
  321. "invalid value for prevExist",
  322. )
  323. }
  324. pe = &bv
  325. }
  326. rr := etcdserverpb.Request{
  327. ID: id,
  328. Method: r.Method,
  329. Path: p,
  330. Val: r.FormValue("value"),
  331. Dir: dir,
  332. PrevValue: pV,
  333. PrevIndex: pIdx,
  334. PrevExist: pe,
  335. Recursive: rec,
  336. Since: wIdx,
  337. Sorted: sort,
  338. Stream: stream,
  339. Wait: wait,
  340. }
  341. if pe != nil {
  342. rr.PrevExist = pe
  343. }
  344. // Null TTL is equivalent to unset Expiration
  345. if ttl != nil {
  346. expr := time.Duration(*ttl) * time.Second
  347. rr.Expiration = clock.Now().Add(expr).UnixNano()
  348. }
  349. return rr, nil
  350. }
  351. // getUint64 extracts a uint64 by the given key from a Form. If the key does
  352. // not exist in the form, 0 is returned. If the key exists but the value is
  353. // badly formed, an error is returned. If multiple values are present only the
  354. // first is considered.
  355. func getUint64(form url.Values, key string) (i uint64, err error) {
  356. if vals, ok := form[key]; ok {
  357. i, err = strconv.ParseUint(vals[0], 10, 64)
  358. }
  359. return
  360. }
  361. // getBool extracts a bool by the given key from a Form. If the key does not
  362. // exist in the form, false is returned. If the key exists but the value is
  363. // badly formed, an error is returned. If multiple values are present only the
  364. // first is considered.
  365. func getBool(form url.Values, key string) (b bool, err error) {
  366. if vals, ok := form[key]; ok {
  367. b, err = strconv.ParseBool(vals[0])
  368. }
  369. return
  370. }
  371. // writeError logs and writes the given Error to the ResponseWriter
  372. // If Error is an etcdErr, it is rendered to the ResponseWriter
  373. // Otherwise, it is assumed to be an InternalServerError
  374. func writeError(w http.ResponseWriter, err error) {
  375. if err == nil {
  376. return
  377. }
  378. log.Println(err)
  379. if e, ok := err.(*etcdErr.Error); ok {
  380. e.Write(w)
  381. } else {
  382. http.Error(w, "Internal Server Error", http.StatusInternalServerError)
  383. }
  384. }
  385. // writeKeyEvent trims the prefix of key path in a single Event under
  386. // StoreKeysPrefix, serializes it and writes the resulting JSON to the given
  387. // ResponseWriter, along with the appropriate headers.
  388. func writeKeyEvent(w http.ResponseWriter, ev *store.Event, rt etcdserver.RaftTimer) error {
  389. if ev == nil {
  390. return errors.New("cannot write empty Event!")
  391. }
  392. w.Header().Set("Content-Type", "application/json")
  393. w.Header().Set("X-Etcd-Index", fmt.Sprint(ev.EtcdIndex))
  394. w.Header().Set("X-Raft-Index", fmt.Sprint(rt.Index()))
  395. w.Header().Set("X-Raft-Term", fmt.Sprint(rt.Term()))
  396. if ev.IsCreated() {
  397. w.WriteHeader(http.StatusCreated)
  398. }
  399. ev = trimEventPrefix(ev, etcdserver.StoreKeysPrefix)
  400. return json.NewEncoder(w).Encode(ev)
  401. }
  402. func handleKeyWatch(ctx context.Context, w http.ResponseWriter, wa store.Watcher, stream bool, rt etcdserver.RaftTimer) {
  403. defer wa.Remove()
  404. ech := wa.EventChan()
  405. var nch <-chan bool
  406. if x, ok := w.(http.CloseNotifier); ok {
  407. nch = x.CloseNotify()
  408. }
  409. w.Header().Set("Content-Type", "application/json")
  410. w.Header().Set("X-Etcd-Index", fmt.Sprint(wa.StartIndex()))
  411. w.Header().Set("X-Raft-Index", fmt.Sprint(rt.Index()))
  412. w.Header().Set("X-Raft-Term", fmt.Sprint(rt.Term()))
  413. w.WriteHeader(http.StatusOK)
  414. // Ensure headers are flushed early, in case of long polling
  415. w.(http.Flusher).Flush()
  416. for {
  417. select {
  418. case <-nch:
  419. // Client closed connection. Nothing to do.
  420. return
  421. case <-ctx.Done():
  422. // Timed out. net/http will close the connection for us, so nothing to do.
  423. return
  424. case ev, ok := <-ech:
  425. if !ok {
  426. // If the channel is closed this may be an indication of
  427. // that notifications are much more than we are able to
  428. // send to the client in time. Then we simply end streaming.
  429. return
  430. }
  431. ev = trimEventPrefix(ev, etcdserver.StoreKeysPrefix)
  432. if err := json.NewEncoder(w).Encode(ev); err != nil {
  433. // Should never be reached
  434. log.Printf("error writing event: %v\n", err)
  435. return
  436. }
  437. if !stream {
  438. return
  439. }
  440. w.(http.Flusher).Flush()
  441. }
  442. }
  443. }
  444. // allowMethod verifies that the given method is one of the allowed methods,
  445. // and if not, it writes an error to w. A boolean is returned indicating
  446. // whether or not the method is allowed.
  447. func allowMethod(w http.ResponseWriter, m string, ms ...string) bool {
  448. for _, meth := range ms {
  449. if m == meth {
  450. return true
  451. }
  452. }
  453. w.Header().Set("Allow", strings.Join(ms, ","))
  454. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  455. return false
  456. }
  457. func trimEventPrefix(ev *store.Event, prefix string) *store.Event {
  458. if ev == nil {
  459. return nil
  460. }
  461. ev.Node = trimNodeExternPrefix(ev.Node, prefix)
  462. ev.PrevNode = trimNodeExternPrefix(ev.PrevNode, prefix)
  463. return ev
  464. }
  465. func trimNodeExternPrefix(n *store.NodeExtern, prefix string) *store.NodeExtern {
  466. if n == nil {
  467. return nil
  468. }
  469. n.Key = strings.TrimPrefix(n.Key, prefix)
  470. for _, nn := range n.Nodes {
  471. nn = trimNodeExternPrefix(nn, prefix)
  472. }
  473. return n
  474. }