http.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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, "POST", "DELETE") {
  133. return
  134. }
  135. ctx, cancel := context.WithTimeout(context.Background(), defaultServerTimeout)
  136. defer cancel()
  137. switch r.Method {
  138. case "POST":
  139. if err := r.ParseForm(); err != nil {
  140. http.Error(w, err.Error(), http.StatusBadRequest)
  141. return
  142. }
  143. peerURLs := r.PostForm["PeerURLs"]
  144. validURLs, err := types.NewURLs(peerURLs)
  145. if err != nil {
  146. http.Error(w, "bad peer urls", http.StatusBadRequest)
  147. return
  148. }
  149. now := h.clock.Now()
  150. m := etcdserver.NewMember("", validURLs, "", &now)
  151. if err := h.server.AddMember(ctx, *m); err != nil {
  152. log.Printf("etcdhttp: error adding node %x: %v", m.ID, err)
  153. writeError(w, err)
  154. return
  155. }
  156. log.Printf("etcdhttp: added node %x with peer urls %v", m.ID, peerURLs)
  157. w.WriteHeader(http.StatusCreated)
  158. case "DELETE":
  159. idStr := strings.TrimPrefix(r.URL.Path, adminMembersPrefix)
  160. id, err := strconv.ParseUint(idStr, 16, 64)
  161. if err != nil {
  162. http.Error(w, err.Error(), http.StatusBadRequest)
  163. return
  164. }
  165. log.Printf("etcdhttp: remove node %x", id)
  166. if err := h.server.RemoveMember(ctx, id); err != nil {
  167. log.Printf("etcdhttp: error removing node %x: %v", id, err)
  168. writeError(w, err)
  169. return
  170. }
  171. w.WriteHeader(http.StatusNoContent)
  172. }
  173. }
  174. func (h serverHandler) serveStoreStats(w http.ResponseWriter, r *http.Request) {
  175. if !allowMethod(w, r.Method, "GET") {
  176. return
  177. }
  178. w.Header().Set("Content-Type", "application/json")
  179. w.Write(h.stats.StoreStats())
  180. }
  181. func (h serverHandler) serveSelfStats(w http.ResponseWriter, r *http.Request) {
  182. if !allowMethod(w, r.Method, "GET") {
  183. return
  184. }
  185. w.Header().Set("Content-Type", "application/json")
  186. w.Write(h.stats.SelfStats())
  187. }
  188. func (h serverHandler) serveLeaderStats(w http.ResponseWriter, r *http.Request) {
  189. if !allowMethod(w, r.Method, "GET") {
  190. return
  191. }
  192. w.Header().Set("Content-Type", "application/json")
  193. w.Write(h.stats.LeaderStats())
  194. }
  195. func (h serverHandler) serveRaft(w http.ResponseWriter, r *http.Request) {
  196. if !allowMethod(w, r.Method, "POST") {
  197. return
  198. }
  199. wcid := strconv.FormatUint(h.clusterStore.Get().ID(), 16)
  200. w.Header().Set("X-Etcd-Cluster-ID", wcid)
  201. gcid := r.Header.Get("X-Etcd-Cluster-ID")
  202. if gcid != wcid {
  203. log.Printf("etcdhttp: request ignored due to cluster ID mismatch got %s want %s", gcid, wcid)
  204. http.Error(w, "clusterID mismatch", http.StatusPreconditionFailed)
  205. return
  206. }
  207. b, err := ioutil.ReadAll(r.Body)
  208. if err != nil {
  209. log.Println("etcdhttp: error reading raft message:", err)
  210. http.Error(w, "error reading raft message", http.StatusBadRequest)
  211. return
  212. }
  213. var m raftpb.Message
  214. if err := m.Unmarshal(b); err != nil {
  215. log.Println("etcdhttp: error unmarshaling raft message:", err)
  216. http.Error(w, "error unmarshaling raft message", http.StatusBadRequest)
  217. return
  218. }
  219. log.Printf("etcdhttp: raft recv message from %#x: %+v", m.From, m)
  220. if err := h.server.Process(context.TODO(), m); err != nil {
  221. log.Println("etcdhttp: error processing raft message:", err)
  222. switch err {
  223. case etcdserver.ErrRemoved:
  224. http.Error(w, "cannot process message from removed node", http.StatusForbidden)
  225. default:
  226. writeError(w, err)
  227. }
  228. return
  229. }
  230. if m.Type == raftpb.MsgApp {
  231. h.stats.UpdateRecvApp(m.From, r.ContentLength)
  232. }
  233. w.WriteHeader(http.StatusNoContent)
  234. }
  235. // parseKeyRequest converts a received http.Request on keysPrefix to
  236. // a server Request, performing validation of supplied fields as appropriate.
  237. // If any validation fails, an empty Request and non-nil error is returned.
  238. func parseKeyRequest(r *http.Request, id uint64, clock clockwork.Clock) (etcdserverpb.Request, error) {
  239. emptyReq := etcdserverpb.Request{}
  240. err := r.ParseForm()
  241. if err != nil {
  242. return emptyReq, etcdErr.NewRequestError(
  243. etcdErr.EcodeInvalidForm,
  244. err.Error(),
  245. )
  246. }
  247. if !strings.HasPrefix(r.URL.Path, keysPrefix) {
  248. return emptyReq, etcdErr.NewRequestError(
  249. etcdErr.EcodeInvalidForm,
  250. "incorrect key prefix",
  251. )
  252. }
  253. p := path.Join(etcdserver.StoreKeysPrefix, r.URL.Path[len(keysPrefix):])
  254. var pIdx, wIdx uint64
  255. if pIdx, err = getUint64(r.Form, "prevIndex"); err != nil {
  256. return emptyReq, etcdErr.NewRequestError(
  257. etcdErr.EcodeIndexNaN,
  258. `invalid value for "prevIndex"`,
  259. )
  260. }
  261. if wIdx, err = getUint64(r.Form, "waitIndex"); err != nil {
  262. return emptyReq, etcdErr.NewRequestError(
  263. etcdErr.EcodeIndexNaN,
  264. `invalid value for "waitIndex"`,
  265. )
  266. }
  267. var rec, sort, wait, dir, stream bool
  268. if rec, err = getBool(r.Form, "recursive"); err != nil {
  269. return emptyReq, etcdErr.NewRequestError(
  270. etcdErr.EcodeInvalidField,
  271. `invalid value for "recursive"`,
  272. )
  273. }
  274. if sort, err = getBool(r.Form, "sorted"); err != nil {
  275. return emptyReq, etcdErr.NewRequestError(
  276. etcdErr.EcodeInvalidField,
  277. `invalid value for "sorted"`,
  278. )
  279. }
  280. if wait, err = getBool(r.Form, "wait"); err != nil {
  281. return emptyReq, etcdErr.NewRequestError(
  282. etcdErr.EcodeInvalidField,
  283. `invalid value for "wait"`,
  284. )
  285. }
  286. // TODO(jonboulle): define what parameters dir is/isn't compatible with?
  287. if dir, err = getBool(r.Form, "dir"); err != nil {
  288. return emptyReq, etcdErr.NewRequestError(
  289. etcdErr.EcodeInvalidField,
  290. `invalid value for "dir"`,
  291. )
  292. }
  293. if stream, err = getBool(r.Form, "stream"); err != nil {
  294. return emptyReq, etcdErr.NewRequestError(
  295. etcdErr.EcodeInvalidField,
  296. `invalid value for "stream"`,
  297. )
  298. }
  299. if wait && r.Method != "GET" {
  300. return emptyReq, etcdErr.NewRequestError(
  301. etcdErr.EcodeInvalidField,
  302. `"wait" can only be used with GET requests`,
  303. )
  304. }
  305. pV := r.FormValue("prevValue")
  306. if _, ok := r.Form["prevValue"]; ok && pV == "" {
  307. return emptyReq, etcdErr.NewRequestError(
  308. etcdErr.EcodeInvalidField,
  309. `"prevValue" cannot be empty`,
  310. )
  311. }
  312. // TTL is nullable, so leave it null if not specified
  313. // or an empty string
  314. var ttl *uint64
  315. if len(r.FormValue("ttl")) > 0 {
  316. i, err := getUint64(r.Form, "ttl")
  317. if err != nil {
  318. return emptyReq, etcdErr.NewRequestError(
  319. etcdErr.EcodeTTLNaN,
  320. `invalid value for "ttl"`,
  321. )
  322. }
  323. ttl = &i
  324. }
  325. // prevExist is nullable, so leave it null if not specified
  326. var pe *bool
  327. if _, ok := r.Form["prevExist"]; ok {
  328. bv, err := getBool(r.Form, "prevExist")
  329. if err != nil {
  330. return emptyReq, etcdErr.NewRequestError(
  331. etcdErr.EcodeInvalidField,
  332. "invalid value for prevExist",
  333. )
  334. }
  335. pe = &bv
  336. }
  337. rr := etcdserverpb.Request{
  338. ID: id,
  339. Method: r.Method,
  340. Path: p,
  341. Val: r.FormValue("value"),
  342. Dir: dir,
  343. PrevValue: pV,
  344. PrevIndex: pIdx,
  345. PrevExist: pe,
  346. Recursive: rec,
  347. Since: wIdx,
  348. Sorted: sort,
  349. Stream: stream,
  350. Wait: wait,
  351. }
  352. if pe != nil {
  353. rr.PrevExist = pe
  354. }
  355. // Null TTL is equivalent to unset Expiration
  356. if ttl != nil {
  357. expr := time.Duration(*ttl) * time.Second
  358. rr.Expiration = clock.Now().Add(expr).UnixNano()
  359. }
  360. return rr, nil
  361. }
  362. // getUint64 extracts a uint64 by the given key from a Form. If the key does
  363. // not exist in the form, 0 is returned. If the key exists but the value is
  364. // badly formed, an error is returned. If multiple values are present only the
  365. // first is considered.
  366. func getUint64(form url.Values, key string) (i uint64, err error) {
  367. if vals, ok := form[key]; ok {
  368. i, err = strconv.ParseUint(vals[0], 10, 64)
  369. }
  370. return
  371. }
  372. // getBool extracts a bool by the given key from a Form. If the key does not
  373. // exist in the form, false is returned. If the key exists but the value is
  374. // badly formed, an error is returned. If multiple values are present only the
  375. // first is considered.
  376. func getBool(form url.Values, key string) (b bool, err error) {
  377. if vals, ok := form[key]; ok {
  378. b, err = strconv.ParseBool(vals[0])
  379. }
  380. return
  381. }
  382. // writeError logs and writes the given Error to the ResponseWriter
  383. // If Error is an etcdErr, it is rendered to the ResponseWriter
  384. // Otherwise, it is assumed to be an InternalServerError
  385. func writeError(w http.ResponseWriter, err error) {
  386. if err == nil {
  387. return
  388. }
  389. log.Println(err)
  390. if e, ok := err.(*etcdErr.Error); ok {
  391. e.Write(w)
  392. } else {
  393. http.Error(w, "Internal Server Error", http.StatusInternalServerError)
  394. }
  395. }
  396. // writeKeyEvent trims the prefix of key path in a single Event under
  397. // StoreKeysPrefix, serializes it and writes the resulting JSON to the given
  398. // ResponseWriter, along with the appropriate headers.
  399. func writeKeyEvent(w http.ResponseWriter, ev *store.Event, rt etcdserver.RaftTimer) error {
  400. if ev == nil {
  401. return errors.New("cannot write empty Event!")
  402. }
  403. w.Header().Set("Content-Type", "application/json")
  404. w.Header().Set("X-Etcd-Index", fmt.Sprint(ev.EtcdIndex))
  405. w.Header().Set("X-Raft-Index", fmt.Sprint(rt.Index()))
  406. w.Header().Set("X-Raft-Term", fmt.Sprint(rt.Term()))
  407. if ev.IsCreated() {
  408. w.WriteHeader(http.StatusCreated)
  409. }
  410. ev = trimEventPrefix(ev, etcdserver.StoreKeysPrefix)
  411. return json.NewEncoder(w).Encode(ev)
  412. }
  413. func handleKeyWatch(ctx context.Context, w http.ResponseWriter, wa store.Watcher, stream bool, rt etcdserver.RaftTimer) {
  414. defer wa.Remove()
  415. ech := wa.EventChan()
  416. var nch <-chan bool
  417. if x, ok := w.(http.CloseNotifier); ok {
  418. nch = x.CloseNotify()
  419. }
  420. w.Header().Set("Content-Type", "application/json")
  421. w.Header().Set("X-Etcd-Index", fmt.Sprint(wa.StartIndex()))
  422. w.Header().Set("X-Raft-Index", fmt.Sprint(rt.Index()))
  423. w.Header().Set("X-Raft-Term", fmt.Sprint(rt.Term()))
  424. w.WriteHeader(http.StatusOK)
  425. // Ensure headers are flushed early, in case of long polling
  426. w.(http.Flusher).Flush()
  427. for {
  428. select {
  429. case <-nch:
  430. // Client closed connection. Nothing to do.
  431. return
  432. case <-ctx.Done():
  433. // Timed out. net/http will close the connection for us, so nothing to do.
  434. return
  435. case ev, ok := <-ech:
  436. if !ok {
  437. // If the channel is closed this may be an indication of
  438. // that notifications are much more than we are able to
  439. // send to the client in time. Then we simply end streaming.
  440. return
  441. }
  442. ev = trimEventPrefix(ev, etcdserver.StoreKeysPrefix)
  443. if err := json.NewEncoder(w).Encode(ev); err != nil {
  444. // Should never be reached
  445. log.Printf("error writing event: %v\n", err)
  446. return
  447. }
  448. if !stream {
  449. return
  450. }
  451. w.(http.Flusher).Flush()
  452. }
  453. }
  454. }
  455. // allowMethod verifies that the given method is one of the allowed methods,
  456. // and if not, it writes an error to w. A boolean is returned indicating
  457. // whether or not the method is allowed.
  458. func allowMethod(w http.ResponseWriter, m string, ms ...string) bool {
  459. for _, meth := range ms {
  460. if m == meth {
  461. return true
  462. }
  463. }
  464. w.Header().Set("Allow", strings.Join(ms, ","))
  465. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  466. return false
  467. }
  468. func trimEventPrefix(ev *store.Event, prefix string) *store.Event {
  469. if ev == nil {
  470. return nil
  471. }
  472. ev.Node = trimNodeExternPrefix(ev.Node, prefix)
  473. ev.PrevNode = trimNodeExternPrefix(ev.PrevNode, prefix)
  474. return ev
  475. }
  476. func trimNodeExternPrefix(n *store.NodeExtern, prefix string) *store.NodeExtern {
  477. if n == nil {
  478. return nil
  479. }
  480. n.Key = strings.TrimPrefix(n.Key, prefix)
  481. for _, nn := range n.Nodes {
  482. nn = trimNodeExternPrefix(nn, prefix)
  483. }
  484. return n
  485. }