client.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package etcdhttp
  15. import (
  16. "encoding/json"
  17. "errors"
  18. "expvar"
  19. "fmt"
  20. "io/ioutil"
  21. "net/http"
  22. "net/url"
  23. "path"
  24. "strconv"
  25. "strings"
  26. "time"
  27. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/jonboulle/clockwork"
  28. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus"
  29. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  30. etcdErr "github.com/coreos/etcd/error"
  31. "github.com/coreos/etcd/etcdserver"
  32. "github.com/coreos/etcd/etcdserver/auth"
  33. "github.com/coreos/etcd/etcdserver/etcdhttp/httptypes"
  34. "github.com/coreos/etcd/etcdserver/etcdserverpb"
  35. "github.com/coreos/etcd/etcdserver/stats"
  36. "github.com/coreos/etcd/pkg/types"
  37. "github.com/coreos/etcd/raft"
  38. "github.com/coreos/etcd/store"
  39. "github.com/coreos/etcd/version"
  40. )
  41. const (
  42. authPrefix = "/v2/auth"
  43. keysPrefix = "/v2/keys"
  44. deprecatedMachinesPrefix = "/v2/machines"
  45. membersPrefix = "/v2/members"
  46. statsPrefix = "/v2/stats"
  47. varsPath = "/debug/vars"
  48. metricsPath = "/metrics"
  49. healthPath = "/health"
  50. versionPath = "/version"
  51. )
  52. // NewClientHandler generates a muxed http.Handler with the given parameters to serve etcd client requests.
  53. func NewClientHandler(server *etcdserver.EtcdServer) http.Handler {
  54. go capabilityLoop(server)
  55. sec := auth.NewStore(server, defaultServerTimeout)
  56. kh := &keysHandler{
  57. sec: sec,
  58. server: server,
  59. cluster: server.Cluster(),
  60. timer: server,
  61. timeout: defaultServerTimeout,
  62. }
  63. sh := &statsHandler{
  64. stats: server,
  65. }
  66. mh := &membersHandler{
  67. sec: sec,
  68. server: server,
  69. cluster: server.Cluster(),
  70. clock: clockwork.NewRealClock(),
  71. }
  72. dmh := &deprecatedMachinesHandler{
  73. cluster: server.Cluster(),
  74. }
  75. sech := &authHandler{
  76. sec: sec,
  77. cluster: server.Cluster(),
  78. }
  79. mux := http.NewServeMux()
  80. mux.HandleFunc("/", http.NotFound)
  81. mux.Handle(healthPath, healthHandler(server))
  82. mux.HandleFunc(versionPath, versionHandler(server.Cluster(), serveVersion))
  83. mux.Handle(keysPrefix, kh)
  84. mux.Handle(keysPrefix+"/", kh)
  85. mux.HandleFunc(statsPrefix+"/store", sh.serveStore)
  86. mux.HandleFunc(statsPrefix+"/self", sh.serveSelf)
  87. mux.HandleFunc(statsPrefix+"/leader", sh.serveLeader)
  88. mux.HandleFunc(varsPath, serveVars)
  89. mux.Handle(metricsPath, prometheus.Handler())
  90. mux.Handle(membersPrefix, mh)
  91. mux.Handle(membersPrefix+"/", mh)
  92. mux.Handle(deprecatedMachinesPrefix, dmh)
  93. handleAuth(mux, sech)
  94. return requestLogger(mux)
  95. }
  96. type keysHandler struct {
  97. sec *auth.Store
  98. server etcdserver.Server
  99. cluster etcdserver.Cluster
  100. timer etcdserver.RaftTimer
  101. timeout time.Duration
  102. }
  103. func (h *keysHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  104. if !allowMethod(w, r.Method, "HEAD", "GET", "PUT", "POST", "DELETE") {
  105. return
  106. }
  107. w.Header().Set("X-Etcd-Cluster-ID", h.cluster.ID().String())
  108. ctx, cancel := context.WithTimeout(context.Background(), h.timeout)
  109. defer cancel()
  110. rr, err := parseKeyRequest(r, clockwork.NewRealClock())
  111. if err != nil {
  112. writeKeyError(w, err)
  113. return
  114. }
  115. // The path must be valid at this point (we've parsed the request successfully).
  116. if !hasKeyPrefixAccess(h.sec, r, r.URL.Path[len(keysPrefix):], rr.Recursive) {
  117. writeKeyNoAuth(w)
  118. return
  119. }
  120. resp, err := h.server.Do(ctx, rr)
  121. if err != nil {
  122. err = trimErrorPrefix(err, etcdserver.StoreKeysPrefix)
  123. writeKeyError(w, err)
  124. return
  125. }
  126. switch {
  127. case resp.Event != nil:
  128. if err := writeKeyEvent(w, resp.Event, h.timer); err != nil {
  129. // Should never be reached
  130. plog.Errorf("error writing event (%v)", err)
  131. }
  132. case resp.Watcher != nil:
  133. ctx, cancel := context.WithTimeout(context.Background(), defaultWatchTimeout)
  134. defer cancel()
  135. handleKeyWatch(ctx, w, resp.Watcher, rr.Stream, h.timer)
  136. default:
  137. writeKeyError(w, errors.New("received response with no Event/Watcher!"))
  138. }
  139. }
  140. type deprecatedMachinesHandler struct {
  141. cluster etcdserver.Cluster
  142. }
  143. func (h *deprecatedMachinesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  144. if !allowMethod(w, r.Method, "GET", "HEAD") {
  145. return
  146. }
  147. endpoints := h.cluster.ClientURLs()
  148. w.Write([]byte(strings.Join(endpoints, ", ")))
  149. }
  150. type membersHandler struct {
  151. sec *auth.Store
  152. server etcdserver.Server
  153. cluster etcdserver.Cluster
  154. clock clockwork.Clock
  155. }
  156. func (h *membersHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  157. if !allowMethod(w, r.Method, "GET", "POST", "DELETE", "PUT") {
  158. return
  159. }
  160. if !hasWriteRootAccess(h.sec, r) {
  161. writeNoAuth(w)
  162. return
  163. }
  164. w.Header().Set("X-Etcd-Cluster-ID", h.cluster.ID().String())
  165. ctx, cancel := context.WithTimeout(context.Background(), defaultServerTimeout)
  166. defer cancel()
  167. switch r.Method {
  168. case "GET":
  169. switch trimPrefix(r.URL.Path, membersPrefix) {
  170. case "":
  171. mc := newMemberCollection(h.cluster.Members())
  172. w.Header().Set("Content-Type", "application/json")
  173. if err := json.NewEncoder(w).Encode(mc); err != nil {
  174. plog.Warningf("failed to encode members response (%v)", err)
  175. }
  176. case "leader":
  177. id := h.server.Leader()
  178. if id == 0 {
  179. writeError(w, httptypes.NewHTTPError(http.StatusServiceUnavailable, "During election"))
  180. return
  181. }
  182. m := newMember(h.cluster.Member(id))
  183. w.Header().Set("Content-Type", "application/json")
  184. if err := json.NewEncoder(w).Encode(m); err != nil {
  185. plog.Warningf("failed to encode members response (%v)", err)
  186. }
  187. default:
  188. writeError(w, httptypes.NewHTTPError(http.StatusNotFound, "Not found"))
  189. }
  190. case "POST":
  191. req := httptypes.MemberCreateRequest{}
  192. if ok := unmarshalRequest(r, &req, w); !ok {
  193. return
  194. }
  195. now := h.clock.Now()
  196. m := etcdserver.NewMember("", req.PeerURLs, "", &now)
  197. err := h.server.AddMember(ctx, *m)
  198. switch {
  199. case err == etcdserver.ErrIDExists || err == etcdserver.ErrPeerURLexists:
  200. writeError(w, httptypes.NewHTTPError(http.StatusConflict, err.Error()))
  201. return
  202. case err != nil:
  203. plog.Errorf("error adding member %s (%v)", m.ID, err)
  204. writeError(w, err)
  205. return
  206. }
  207. res := newMember(m)
  208. w.Header().Set("Content-Type", "application/json")
  209. w.WriteHeader(http.StatusCreated)
  210. if err := json.NewEncoder(w).Encode(res); err != nil {
  211. plog.Warningf("failed to encode members response (%v)", err)
  212. }
  213. case "DELETE":
  214. id, ok := getID(r.URL.Path, w)
  215. if !ok {
  216. return
  217. }
  218. err := h.server.RemoveMember(ctx, uint64(id))
  219. switch {
  220. case err == etcdserver.ErrIDRemoved:
  221. writeError(w, httptypes.NewHTTPError(http.StatusGone, fmt.Sprintf("Member permanently removed: %s", id)))
  222. case err == etcdserver.ErrIDNotFound:
  223. writeError(w, httptypes.NewHTTPError(http.StatusNotFound, fmt.Sprintf("No such member: %s", id)))
  224. case err != nil:
  225. plog.Errorf("error removing member %s (%v)", id, err)
  226. writeError(w, err)
  227. default:
  228. w.WriteHeader(http.StatusNoContent)
  229. }
  230. case "PUT":
  231. id, ok := getID(r.URL.Path, w)
  232. if !ok {
  233. return
  234. }
  235. req := httptypes.MemberUpdateRequest{}
  236. if ok := unmarshalRequest(r, &req, w); !ok {
  237. return
  238. }
  239. m := etcdserver.Member{
  240. ID: id,
  241. RaftAttributes: etcdserver.RaftAttributes{PeerURLs: req.PeerURLs.StringSlice()},
  242. }
  243. err := h.server.UpdateMember(ctx, m)
  244. switch {
  245. case err == etcdserver.ErrPeerURLexists:
  246. writeError(w, httptypes.NewHTTPError(http.StatusConflict, err.Error()))
  247. case err == etcdserver.ErrIDNotFound:
  248. writeError(w, httptypes.NewHTTPError(http.StatusNotFound, fmt.Sprintf("No such member: %s", id)))
  249. case err != nil:
  250. plog.Errorf("error updating member %s (%v)", m.ID, err)
  251. writeError(w, err)
  252. default:
  253. w.WriteHeader(http.StatusNoContent)
  254. }
  255. }
  256. }
  257. type statsHandler struct {
  258. stats stats.Stats
  259. }
  260. func (h *statsHandler) serveStore(w http.ResponseWriter, r *http.Request) {
  261. if !allowMethod(w, r.Method, "GET") {
  262. return
  263. }
  264. w.Header().Set("Content-Type", "application/json")
  265. w.Write(h.stats.StoreStats())
  266. }
  267. func (h *statsHandler) serveSelf(w http.ResponseWriter, r *http.Request) {
  268. if !allowMethod(w, r.Method, "GET") {
  269. return
  270. }
  271. w.Header().Set("Content-Type", "application/json")
  272. w.Write(h.stats.SelfStats())
  273. }
  274. func (h *statsHandler) serveLeader(w http.ResponseWriter, r *http.Request) {
  275. if !allowMethod(w, r.Method, "GET") {
  276. return
  277. }
  278. stats := h.stats.LeaderStats()
  279. if stats == nil {
  280. writeError(w, httptypes.NewHTTPError(http.StatusForbidden, "not current leader"))
  281. return
  282. }
  283. w.Header().Set("Content-Type", "application/json")
  284. w.Write(stats)
  285. }
  286. func serveVars(w http.ResponseWriter, r *http.Request) {
  287. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  288. fmt.Fprintf(w, "{\n")
  289. first := true
  290. expvar.Do(func(kv expvar.KeyValue) {
  291. if !first {
  292. fmt.Fprintf(w, ",\n")
  293. }
  294. first = false
  295. fmt.Fprintf(w, "%q: %s", kv.Key, kv.Value)
  296. })
  297. fmt.Fprintf(w, "\n}\n")
  298. }
  299. // TODO: change etcdserver to raft interface when we have it.
  300. // add test for healthHeadler when we have the interface ready.
  301. func healthHandler(server *etcdserver.EtcdServer) http.HandlerFunc {
  302. return func(w http.ResponseWriter, r *http.Request) {
  303. if !allowMethod(w, r.Method, "GET") {
  304. return
  305. }
  306. if uint64(server.Leader()) == raft.None {
  307. http.Error(w, `{"health": "false"}`, http.StatusServiceUnavailable)
  308. return
  309. }
  310. // wait for raft's progress
  311. index := server.Index()
  312. for i := 0; i < 3; i++ {
  313. time.Sleep(250 * time.Millisecond)
  314. if server.Index() > index {
  315. w.WriteHeader(http.StatusOK)
  316. w.Write([]byte(`{"health": "true"}`))
  317. return
  318. }
  319. }
  320. http.Error(w, `{"health": "false"}`, http.StatusServiceUnavailable)
  321. return
  322. }
  323. }
  324. func versionHandler(c etcdserver.Cluster, fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
  325. return func(w http.ResponseWriter, r *http.Request) {
  326. v := c.Version()
  327. if v != nil {
  328. fn(w, r, v.String())
  329. } else {
  330. fn(w, r, "not_decided")
  331. }
  332. }
  333. }
  334. func serveVersion(w http.ResponseWriter, r *http.Request, clusterV string) {
  335. if !allowMethod(w, r.Method, "GET") {
  336. return
  337. }
  338. vs := version.Versions{
  339. Server: version.Version,
  340. Cluster: clusterV,
  341. }
  342. b, err := json.Marshal(&vs)
  343. if err != nil {
  344. plog.Panicf("cannot marshal versions to json (%v)", err)
  345. }
  346. w.Write(b)
  347. }
  348. // parseKeyRequest converts a received http.Request on keysPrefix to
  349. // a server Request, performing validation of supplied fields as appropriate.
  350. // If any validation fails, an empty Request and non-nil error is returned.
  351. func parseKeyRequest(r *http.Request, clock clockwork.Clock) (etcdserverpb.Request, error) {
  352. emptyReq := etcdserverpb.Request{}
  353. err := r.ParseForm()
  354. if err != nil {
  355. return emptyReq, etcdErr.NewRequestError(
  356. etcdErr.EcodeInvalidForm,
  357. err.Error(),
  358. )
  359. }
  360. if !strings.HasPrefix(r.URL.Path, keysPrefix) {
  361. return emptyReq, etcdErr.NewRequestError(
  362. etcdErr.EcodeInvalidForm,
  363. "incorrect key prefix",
  364. )
  365. }
  366. p := path.Join(etcdserver.StoreKeysPrefix, r.URL.Path[len(keysPrefix):])
  367. var pIdx, wIdx uint64
  368. if pIdx, err = getUint64(r.Form, "prevIndex"); err != nil {
  369. return emptyReq, etcdErr.NewRequestError(
  370. etcdErr.EcodeIndexNaN,
  371. `invalid value for "prevIndex"`,
  372. )
  373. }
  374. if wIdx, err = getUint64(r.Form, "waitIndex"); err != nil {
  375. return emptyReq, etcdErr.NewRequestError(
  376. etcdErr.EcodeIndexNaN,
  377. `invalid value for "waitIndex"`,
  378. )
  379. }
  380. var rec, sort, wait, dir, quorum, stream bool
  381. if rec, err = getBool(r.Form, "recursive"); err != nil {
  382. return emptyReq, etcdErr.NewRequestError(
  383. etcdErr.EcodeInvalidField,
  384. `invalid value for "recursive"`,
  385. )
  386. }
  387. if sort, err = getBool(r.Form, "sorted"); err != nil {
  388. return emptyReq, etcdErr.NewRequestError(
  389. etcdErr.EcodeInvalidField,
  390. `invalid value for "sorted"`,
  391. )
  392. }
  393. if wait, err = getBool(r.Form, "wait"); err != nil {
  394. return emptyReq, etcdErr.NewRequestError(
  395. etcdErr.EcodeInvalidField,
  396. `invalid value for "wait"`,
  397. )
  398. }
  399. // TODO(jonboulle): define what parameters dir is/isn't compatible with?
  400. if dir, err = getBool(r.Form, "dir"); err != nil {
  401. return emptyReq, etcdErr.NewRequestError(
  402. etcdErr.EcodeInvalidField,
  403. `invalid value for "dir"`,
  404. )
  405. }
  406. if quorum, err = getBool(r.Form, "quorum"); err != nil {
  407. return emptyReq, etcdErr.NewRequestError(
  408. etcdErr.EcodeInvalidField,
  409. `invalid value for "quorum"`,
  410. )
  411. }
  412. if stream, err = getBool(r.Form, "stream"); err != nil {
  413. return emptyReq, etcdErr.NewRequestError(
  414. etcdErr.EcodeInvalidField,
  415. `invalid value for "stream"`,
  416. )
  417. }
  418. if wait && r.Method != "GET" {
  419. return emptyReq, etcdErr.NewRequestError(
  420. etcdErr.EcodeInvalidField,
  421. `"wait" can only be used with GET requests`,
  422. )
  423. }
  424. pV := r.FormValue("prevValue")
  425. if _, ok := r.Form["prevValue"]; ok && pV == "" {
  426. return emptyReq, etcdErr.NewRequestError(
  427. etcdErr.EcodePrevValueRequired,
  428. `"prevValue" cannot be empty`,
  429. )
  430. }
  431. // TTL is nullable, so leave it null if not specified
  432. // or an empty string
  433. var ttl *uint64
  434. if len(r.FormValue("ttl")) > 0 {
  435. i, err := getUint64(r.Form, "ttl")
  436. if err != nil {
  437. return emptyReq, etcdErr.NewRequestError(
  438. etcdErr.EcodeTTLNaN,
  439. `invalid value for "ttl"`,
  440. )
  441. }
  442. ttl = &i
  443. }
  444. // prevExist is nullable, so leave it null if not specified
  445. var pe *bool
  446. if _, ok := r.Form["prevExist"]; ok {
  447. bv, err := getBool(r.Form, "prevExist")
  448. if err != nil {
  449. return emptyReq, etcdErr.NewRequestError(
  450. etcdErr.EcodeInvalidField,
  451. "invalid value for prevExist",
  452. )
  453. }
  454. pe = &bv
  455. }
  456. rr := etcdserverpb.Request{
  457. Method: r.Method,
  458. Path: p,
  459. Val: r.FormValue("value"),
  460. Dir: dir,
  461. PrevValue: pV,
  462. PrevIndex: pIdx,
  463. PrevExist: pe,
  464. Wait: wait,
  465. Since: wIdx,
  466. Recursive: rec,
  467. Sorted: sort,
  468. Quorum: quorum,
  469. Stream: stream,
  470. }
  471. if pe != nil {
  472. rr.PrevExist = pe
  473. }
  474. // Null TTL is equivalent to unset Expiration
  475. if ttl != nil {
  476. expr := time.Duration(*ttl) * time.Second
  477. rr.Expiration = clock.Now().Add(expr).UnixNano()
  478. }
  479. return rr, nil
  480. }
  481. // writeKeyEvent trims the prefix of key path in a single Event under
  482. // StoreKeysPrefix, serializes it and writes the resulting JSON to the given
  483. // ResponseWriter, along with the appropriate headers.
  484. func writeKeyEvent(w http.ResponseWriter, ev *store.Event, rt etcdserver.RaftTimer) error {
  485. if ev == nil {
  486. return errors.New("cannot write empty Event!")
  487. }
  488. w.Header().Set("Content-Type", "application/json")
  489. w.Header().Set("X-Etcd-Index", fmt.Sprint(ev.EtcdIndex))
  490. w.Header().Set("X-Raft-Index", fmt.Sprint(rt.Index()))
  491. w.Header().Set("X-Raft-Term", fmt.Sprint(rt.Term()))
  492. if ev.IsCreated() {
  493. w.WriteHeader(http.StatusCreated)
  494. }
  495. ev = trimEventPrefix(ev, etcdserver.StoreKeysPrefix)
  496. return json.NewEncoder(w).Encode(ev)
  497. }
  498. func writeKeyNoAuth(w http.ResponseWriter) {
  499. e := etcdErr.NewError(etcdErr.EcodeUnauthorized, "Insufficient credentials", 0)
  500. e.WriteTo(w)
  501. }
  502. // writeKeyError logs and writes the given Error to the ResponseWriter.
  503. // If Error is not an etcdErr, the error will be converted to an etcd error.
  504. func writeKeyError(w http.ResponseWriter, err error) {
  505. if err == nil {
  506. return
  507. }
  508. switch e := err.(type) {
  509. case *etcdErr.Error:
  510. e.WriteTo(w)
  511. default:
  512. if err == etcdserver.ErrTimeoutDueToLeaderFail {
  513. plog.Error(err)
  514. } else {
  515. plog.Errorf("got unexpected response error (%v)", err)
  516. }
  517. ee := etcdErr.NewError(etcdErr.EcodeRaftInternal, err.Error(), 0)
  518. ee.WriteTo(w)
  519. }
  520. }
  521. func handleKeyWatch(ctx context.Context, w http.ResponseWriter, wa store.Watcher, stream bool, rt etcdserver.RaftTimer) {
  522. defer wa.Remove()
  523. ech := wa.EventChan()
  524. var nch <-chan bool
  525. if x, ok := w.(http.CloseNotifier); ok {
  526. nch = x.CloseNotify()
  527. }
  528. w.Header().Set("Content-Type", "application/json")
  529. w.Header().Set("X-Etcd-Index", fmt.Sprint(wa.StartIndex()))
  530. w.Header().Set("X-Raft-Index", fmt.Sprint(rt.Index()))
  531. w.Header().Set("X-Raft-Term", fmt.Sprint(rt.Term()))
  532. w.WriteHeader(http.StatusOK)
  533. // Ensure headers are flushed early, in case of long polling
  534. w.(http.Flusher).Flush()
  535. for {
  536. select {
  537. case <-nch:
  538. // Client closed connection. Nothing to do.
  539. return
  540. case <-ctx.Done():
  541. // Timed out. net/http will close the connection for us, so nothing to do.
  542. return
  543. case ev, ok := <-ech:
  544. if !ok {
  545. // If the channel is closed this may be an indication of
  546. // that notifications are much more than we are able to
  547. // send to the client in time. Then we simply end streaming.
  548. return
  549. }
  550. ev = trimEventPrefix(ev, etcdserver.StoreKeysPrefix)
  551. if err := json.NewEncoder(w).Encode(ev); err != nil {
  552. // Should never be reached
  553. plog.Warningf("error writing event (%v)", err)
  554. return
  555. }
  556. if !stream {
  557. return
  558. }
  559. w.(http.Flusher).Flush()
  560. }
  561. }
  562. }
  563. func trimEventPrefix(ev *store.Event, prefix string) *store.Event {
  564. if ev == nil {
  565. return nil
  566. }
  567. // Since the *Event may reference one in the store history
  568. // history, we must copy it before modifying
  569. e := ev.Clone()
  570. e.Node = trimNodeExternPrefix(e.Node, prefix)
  571. e.PrevNode = trimNodeExternPrefix(e.PrevNode, prefix)
  572. return e
  573. }
  574. func trimNodeExternPrefix(n *store.NodeExtern, prefix string) *store.NodeExtern {
  575. if n == nil {
  576. return nil
  577. }
  578. n.Key = strings.TrimPrefix(n.Key, prefix)
  579. for _, nn := range n.Nodes {
  580. nn = trimNodeExternPrefix(nn, prefix)
  581. }
  582. return n
  583. }
  584. func trimErrorPrefix(err error, prefix string) error {
  585. if e, ok := err.(*etcdErr.Error); ok {
  586. e.Cause = strings.TrimPrefix(e.Cause, prefix)
  587. }
  588. return err
  589. }
  590. func unmarshalRequest(r *http.Request, req json.Unmarshaler, w http.ResponseWriter) bool {
  591. ctype := r.Header.Get("Content-Type")
  592. if ctype != "application/json" {
  593. writeError(w, httptypes.NewHTTPError(http.StatusUnsupportedMediaType, fmt.Sprintf("Bad Content-Type %s, accept application/json", ctype)))
  594. return false
  595. }
  596. b, err := ioutil.ReadAll(r.Body)
  597. if err != nil {
  598. writeError(w, httptypes.NewHTTPError(http.StatusBadRequest, err.Error()))
  599. return false
  600. }
  601. if err := req.UnmarshalJSON(b); err != nil {
  602. writeError(w, httptypes.NewHTTPError(http.StatusBadRequest, err.Error()))
  603. return false
  604. }
  605. return true
  606. }
  607. func getID(p string, w http.ResponseWriter) (types.ID, bool) {
  608. idStr := trimPrefix(p, membersPrefix)
  609. if idStr == "" {
  610. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  611. return 0, false
  612. }
  613. id, err := types.IDFromString(idStr)
  614. if err != nil {
  615. writeError(w, httptypes.NewHTTPError(http.StatusNotFound, fmt.Sprintf("No such member: %s", idStr)))
  616. return 0, false
  617. }
  618. return id, true
  619. }
  620. // getUint64 extracts a uint64 by the given key from a Form. If the key does
  621. // not exist in the form, 0 is returned. If the key exists but the value is
  622. // badly formed, an error is returned. If multiple values are present only the
  623. // first is considered.
  624. func getUint64(form url.Values, key string) (i uint64, err error) {
  625. if vals, ok := form[key]; ok {
  626. i, err = strconv.ParseUint(vals[0], 10, 64)
  627. }
  628. return
  629. }
  630. // getBool extracts a bool by the given key from a Form. If the key does not
  631. // exist in the form, false is returned. If the key exists but the value is
  632. // badly formed, an error is returned. If multiple values are present only the
  633. // first is considered.
  634. func getBool(form url.Values, key string) (b bool, err error) {
  635. if vals, ok := form[key]; ok {
  636. b, err = strconv.ParseBool(vals[0])
  637. }
  638. return
  639. }
  640. // trimPrefix removes a given prefix and any slash following the prefix
  641. // e.g.: trimPrefix("foo", "foo") == trimPrefix("foo/", "foo") == ""
  642. func trimPrefix(p, prefix string) (s string) {
  643. s = strings.TrimPrefix(p, prefix)
  644. s = strings.TrimPrefix(s, "/")
  645. return
  646. }
  647. func newMemberCollection(ms []*etcdserver.Member) *httptypes.MemberCollection {
  648. c := httptypes.MemberCollection(make([]httptypes.Member, len(ms)))
  649. for i, m := range ms {
  650. c[i] = newMember(m)
  651. }
  652. return &c
  653. }
  654. func newMember(m *etcdserver.Member) httptypes.Member {
  655. tm := httptypes.Member{
  656. ID: m.ID.String(),
  657. Name: m.Name,
  658. PeerURLs: make([]string, len(m.PeerURLs)),
  659. ClientURLs: make([]string, len(m.ClientURLs)),
  660. }
  661. copy(tm.PeerURLs, m.PeerURLs)
  662. copy(tm.ClientURLs, m.ClientURLs)
  663. return tm
  664. }