http.go 15 KB

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