client.go 20 KB

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