http.go 17 KB

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