http.go 16 KB

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