client.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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. "context"
  17. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "io/ioutil"
  21. "net/http"
  22. "net/url"
  23. "path"
  24. "strconv"
  25. "strings"
  26. "time"
  27. etcdErr "github.com/coreos/etcd/error"
  28. "github.com/coreos/etcd/etcdserver"
  29. "github.com/coreos/etcd/etcdserver/api"
  30. "github.com/coreos/etcd/etcdserver/api/etcdhttp"
  31. "github.com/coreos/etcd/etcdserver/api/v2http/httptypes"
  32. "github.com/coreos/etcd/etcdserver/auth"
  33. "github.com/coreos/etcd/etcdserver/etcdserverpb"
  34. "github.com/coreos/etcd/etcdserver/membership"
  35. "github.com/coreos/etcd/etcdserver/stats"
  36. "github.com/coreos/etcd/pkg/types"
  37. "github.com/coreos/etcd/store"
  38. "github.com/jonboulle/clockwork"
  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.ServerPeer, 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.ServerV2, timeout time.Duration) {
  55. sec := auth.NewStore(server, timeout)
  56. kh := &keysHandler{
  57. sec: sec,
  58. server: server,
  59. cluster: server.Cluster(),
  60. timeout: timeout,
  61. clientCertAuthEnabled: server.ClientCertAuthEnabled(),
  62. }
  63. sh := &statsHandler{
  64. stats: server,
  65. }
  66. mh := &membersHandler{
  67. sec: sec,
  68. server: server,
  69. cluster: server.Cluster(),
  70. timeout: timeout,
  71. clock: clockwork.NewRealClock(),
  72. clientCertAuthEnabled: server.ClientCertAuthEnabled(),
  73. }
  74. mah := &machinesHandler{cluster: server.Cluster()}
  75. sech := &authHandler{
  76. sec: sec,
  77. cluster: server.Cluster(),
  78. clientCertAuthEnabled: server.ClientCertAuthEnabled(),
  79. }
  80. mux.HandleFunc("/", http.NotFound)
  81. mux.Handle(keysPrefix, kh)
  82. mux.Handle(keysPrefix+"/", kh)
  83. mux.HandleFunc(statsPrefix+"/store", sh.serveStore)
  84. mux.HandleFunc(statsPrefix+"/self", sh.serveSelf)
  85. mux.HandleFunc(statsPrefix+"/leader", sh.serveLeader)
  86. mux.Handle(membersPrefix, mh)
  87. mux.Handle(membersPrefix+"/", mh)
  88. mux.Handle(machinesPrefix, mah)
  89. handleAuth(mux, sech)
  90. }
  91. type keysHandler struct {
  92. sec auth.Store
  93. server etcdserver.ServerV2
  94. cluster api.Cluster
  95. timeout time.Duration
  96. clientCertAuthEnabled bool
  97. }
  98. func (h *keysHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  99. if !allowMethod(w, r.Method, "HEAD", "GET", "PUT", "POST", "DELETE") {
  100. return
  101. }
  102. w.Header().Set("X-Etcd-Cluster-ID", h.cluster.ID().String())
  103. ctx, cancel := context.WithTimeout(context.Background(), h.timeout)
  104. defer cancel()
  105. clock := clockwork.NewRealClock()
  106. startTime := clock.Now()
  107. rr, noValueOnSuccess, err := parseKeyRequest(r, clock)
  108. if err != nil {
  109. writeKeyError(w, err)
  110. return
  111. }
  112. // The path must be valid at this point (we've parsed the request successfully).
  113. if !hasKeyPrefixAccess(h.sec, r, r.URL.Path[len(keysPrefix):], rr.Recursive, h.clientCertAuthEnabled) {
  114. writeKeyNoAuth(w)
  115. return
  116. }
  117. if !rr.Wait {
  118. reportRequestReceived(rr)
  119. }
  120. resp, err := h.server.Do(ctx, rr)
  121. if err != nil {
  122. err = trimErrorPrefix(err, etcdserver.StoreKeysPrefix)
  123. writeKeyError(w, err)
  124. reportRequestFailed(rr, err)
  125. return
  126. }
  127. switch {
  128. case resp.Event != nil:
  129. if err := writeKeyEvent(w, resp, noValueOnSuccess); err != nil {
  130. // Should never be reached
  131. plog.Errorf("error writing event (%v)", err)
  132. }
  133. reportRequestCompleted(rr, resp, startTime)
  134. case resp.Watcher != nil:
  135. ctx, cancel := context.WithTimeout(context.Background(), defaultWatchTimeout)
  136. defer cancel()
  137. handleKeyWatch(ctx, w, resp, rr.Stream)
  138. default:
  139. writeKeyError(w, errors.New("received response with no Event/Watcher!"))
  140. }
  141. }
  142. type machinesHandler struct {
  143. cluster api.Cluster
  144. }
  145. func (h *machinesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  146. if !allowMethod(w, r.Method, "GET", "HEAD") {
  147. return
  148. }
  149. endpoints := h.cluster.ClientURLs()
  150. w.Write([]byte(strings.Join(endpoints, ", ")))
  151. }
  152. type membersHandler struct {
  153. sec auth.Store
  154. server etcdserver.ServerV2
  155. cluster api.Cluster
  156. timeout time.Duration
  157. clock clockwork.Clock
  158. clientCertAuthEnabled bool
  159. }
  160. func (h *membersHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  161. if !allowMethod(w, r.Method, "GET", "POST", "DELETE", "PUT") {
  162. return
  163. }
  164. if !hasWriteRootAccess(h.sec, r, h.clientCertAuthEnabled) {
  165. writeNoAuth(w, r)
  166. return
  167. }
  168. w.Header().Set("X-Etcd-Cluster-ID", h.cluster.ID().String())
  169. ctx, cancel := context.WithTimeout(context.Background(), h.timeout)
  170. defer cancel()
  171. switch r.Method {
  172. case "GET":
  173. switch trimPrefix(r.URL.Path, membersPrefix) {
  174. case "":
  175. mc := newMemberCollection(h.cluster.Members())
  176. w.Header().Set("Content-Type", "application/json")
  177. if err := json.NewEncoder(w).Encode(mc); err != nil {
  178. plog.Warningf("failed to encode members response (%v)", err)
  179. }
  180. case "leader":
  181. id := h.server.Leader()
  182. if id == 0 {
  183. writeError(w, r, httptypes.NewHTTPError(http.StatusServiceUnavailable, "During election"))
  184. return
  185. }
  186. m := newMember(h.cluster.Member(id))
  187. w.Header().Set("Content-Type", "application/json")
  188. if err := json.NewEncoder(w).Encode(m); err != nil {
  189. plog.Warningf("failed to encode members response (%v)", err)
  190. }
  191. default:
  192. writeError(w, r, httptypes.NewHTTPError(http.StatusNotFound, "Not found"))
  193. }
  194. case "POST":
  195. req := httptypes.MemberCreateRequest{}
  196. if ok := unmarshalRequest(r, &req, w); !ok {
  197. return
  198. }
  199. now := h.clock.Now()
  200. m := membership.NewMember("", req.PeerURLs, "", &now)
  201. _, err := h.server.AddMember(ctx, *m)
  202. switch {
  203. case err == membership.ErrIDExists || err == membership.ErrPeerURLexists:
  204. writeError(w, r, httptypes.NewHTTPError(http.StatusConflict, err.Error()))
  205. return
  206. case err != nil:
  207. plog.Errorf("error adding member %s (%v)", m.ID, err)
  208. writeError(w, r, err)
  209. return
  210. }
  211. res := newMember(m)
  212. w.Header().Set("Content-Type", "application/json")
  213. w.WriteHeader(http.StatusCreated)
  214. if err := json.NewEncoder(w).Encode(res); err != nil {
  215. plog.Warningf("failed to encode members response (%v)", err)
  216. }
  217. case "DELETE":
  218. id, ok := getID(r.URL.Path, w)
  219. if !ok {
  220. return
  221. }
  222. _, err := h.server.RemoveMember(ctx, uint64(id))
  223. switch {
  224. case err == membership.ErrIDRemoved:
  225. writeError(w, r, httptypes.NewHTTPError(http.StatusGone, fmt.Sprintf("Member permanently removed: %s", id)))
  226. case err == membership.ErrIDNotFound:
  227. writeError(w, r, httptypes.NewHTTPError(http.StatusNotFound, fmt.Sprintf("No such member: %s", id)))
  228. case err != nil:
  229. plog.Errorf("error removing member %s (%v)", id, err)
  230. writeError(w, r, err)
  231. default:
  232. w.WriteHeader(http.StatusNoContent)
  233. }
  234. case "PUT":
  235. id, ok := getID(r.URL.Path, w)
  236. if !ok {
  237. return
  238. }
  239. req := httptypes.MemberUpdateRequest{}
  240. if ok := unmarshalRequest(r, &req, w); !ok {
  241. return
  242. }
  243. m := membership.Member{
  244. ID: id,
  245. RaftAttributes: membership.RaftAttributes{PeerURLs: req.PeerURLs.StringSlice()},
  246. }
  247. _, err := h.server.UpdateMember(ctx, m)
  248. switch {
  249. case err == membership.ErrPeerURLexists:
  250. writeError(w, r, httptypes.NewHTTPError(http.StatusConflict, err.Error()))
  251. case err == membership.ErrIDNotFound:
  252. writeError(w, r, httptypes.NewHTTPError(http.StatusNotFound, fmt.Sprintf("No such member: %s", id)))
  253. case err != nil:
  254. plog.Errorf("error updating member %s (%v)", m.ID, err)
  255. writeError(w, r, err)
  256. default:
  257. w.WriteHeader(http.StatusNoContent)
  258. }
  259. }
  260. }
  261. type statsHandler struct {
  262. stats stats.Stats
  263. }
  264. func (h *statsHandler) serveStore(w http.ResponseWriter, r *http.Request) {
  265. if !allowMethod(w, r.Method, "GET") {
  266. return
  267. }
  268. w.Header().Set("Content-Type", "application/json")
  269. w.Write(h.stats.StoreStats())
  270. }
  271. func (h *statsHandler) serveSelf(w http.ResponseWriter, r *http.Request) {
  272. if !allowMethod(w, r.Method, "GET") {
  273. return
  274. }
  275. w.Header().Set("Content-Type", "application/json")
  276. w.Write(h.stats.SelfStats())
  277. }
  278. func (h *statsHandler) serveLeader(w http.ResponseWriter, r *http.Request) {
  279. if !allowMethod(w, r.Method, "GET") {
  280. return
  281. }
  282. stats := h.stats.LeaderStats()
  283. if stats == nil {
  284. etcdhttp.WriteError(w, r, httptypes.NewHTTPError(http.StatusForbidden, "not current leader"))
  285. return
  286. }
  287. w.Header().Set("Content-Type", "application/json")
  288. w.Write(stats)
  289. }
  290. // parseKeyRequest converts a received http.Request on keysPrefix to
  291. // a server Request, performing validation of supplied fields as appropriate.
  292. // If any validation fails, an empty Request and non-nil error is returned.
  293. func parseKeyRequest(r *http.Request, clock clockwork.Clock) (etcdserverpb.Request, bool, error) {
  294. var noValueOnSuccess bool
  295. emptyReq := etcdserverpb.Request{}
  296. err := r.ParseForm()
  297. if err != nil {
  298. return emptyReq, false, etcdErr.NewRequestError(
  299. etcdErr.EcodeInvalidForm,
  300. err.Error(),
  301. )
  302. }
  303. if !strings.HasPrefix(r.URL.Path, keysPrefix) {
  304. return emptyReq, false, etcdErr.NewRequestError(
  305. etcdErr.EcodeInvalidForm,
  306. "incorrect key prefix",
  307. )
  308. }
  309. p := path.Join(etcdserver.StoreKeysPrefix, r.URL.Path[len(keysPrefix):])
  310. var pIdx, wIdx uint64
  311. if pIdx, err = getUint64(r.Form, "prevIndex"); err != nil {
  312. return emptyReq, false, etcdErr.NewRequestError(
  313. etcdErr.EcodeIndexNaN,
  314. `invalid value for "prevIndex"`,
  315. )
  316. }
  317. if wIdx, err = getUint64(r.Form, "waitIndex"); err != nil {
  318. return emptyReq, false, etcdErr.NewRequestError(
  319. etcdErr.EcodeIndexNaN,
  320. `invalid value for "waitIndex"`,
  321. )
  322. }
  323. var rec, sort, wait, dir, quorum, stream bool
  324. if rec, err = getBool(r.Form, "recursive"); err != nil {
  325. return emptyReq, false, etcdErr.NewRequestError(
  326. etcdErr.EcodeInvalidField,
  327. `invalid value for "recursive"`,
  328. )
  329. }
  330. if sort, err = getBool(r.Form, "sorted"); err != nil {
  331. return emptyReq, false, etcdErr.NewRequestError(
  332. etcdErr.EcodeInvalidField,
  333. `invalid value for "sorted"`,
  334. )
  335. }
  336. if wait, err = getBool(r.Form, "wait"); err != nil {
  337. return emptyReq, false, etcdErr.NewRequestError(
  338. etcdErr.EcodeInvalidField,
  339. `invalid value for "wait"`,
  340. )
  341. }
  342. // TODO(jonboulle): define what parameters dir is/isn't compatible with?
  343. if dir, err = getBool(r.Form, "dir"); err != nil {
  344. return emptyReq, false, etcdErr.NewRequestError(
  345. etcdErr.EcodeInvalidField,
  346. `invalid value for "dir"`,
  347. )
  348. }
  349. if quorum, err = getBool(r.Form, "quorum"); err != nil {
  350. return emptyReq, false, etcdErr.NewRequestError(
  351. etcdErr.EcodeInvalidField,
  352. `invalid value for "quorum"`,
  353. )
  354. }
  355. if stream, err = getBool(r.Form, "stream"); err != nil {
  356. return emptyReq, false, etcdErr.NewRequestError(
  357. etcdErr.EcodeInvalidField,
  358. `invalid value for "stream"`,
  359. )
  360. }
  361. if wait && r.Method != "GET" {
  362. return emptyReq, false, etcdErr.NewRequestError(
  363. etcdErr.EcodeInvalidField,
  364. `"wait" can only be used with GET requests`,
  365. )
  366. }
  367. pV := r.FormValue("prevValue")
  368. if _, ok := r.Form["prevValue"]; ok && pV == "" {
  369. return emptyReq, false, etcdErr.NewRequestError(
  370. etcdErr.EcodePrevValueRequired,
  371. `"prevValue" cannot be empty`,
  372. )
  373. }
  374. if noValueOnSuccess, err = getBool(r.Form, "noValueOnSuccess"); err != nil {
  375. return emptyReq, false, etcdErr.NewRequestError(
  376. etcdErr.EcodeInvalidField,
  377. `invalid value for "noValueOnSuccess"`,
  378. )
  379. }
  380. // TTL is nullable, so leave it null if not specified
  381. // or an empty string
  382. var ttl *uint64
  383. if len(r.FormValue("ttl")) > 0 {
  384. i, err := getUint64(r.Form, "ttl")
  385. if err != nil {
  386. return emptyReq, false, etcdErr.NewRequestError(
  387. etcdErr.EcodeTTLNaN,
  388. `invalid value for "ttl"`,
  389. )
  390. }
  391. ttl = &i
  392. }
  393. // prevExist is nullable, so leave it null if not specified
  394. var pe *bool
  395. if _, ok := r.Form["prevExist"]; ok {
  396. bv, err := getBool(r.Form, "prevExist")
  397. if err != nil {
  398. return emptyReq, false, etcdErr.NewRequestError(
  399. etcdErr.EcodeInvalidField,
  400. "invalid value for prevExist",
  401. )
  402. }
  403. pe = &bv
  404. }
  405. // refresh is nullable, so leave it null if not specified
  406. var refresh *bool
  407. if _, ok := r.Form["refresh"]; ok {
  408. bv, err := getBool(r.Form, "refresh")
  409. if err != nil {
  410. return emptyReq, false, etcdErr.NewRequestError(
  411. etcdErr.EcodeInvalidField,
  412. "invalid value for refresh",
  413. )
  414. }
  415. refresh = &bv
  416. if refresh != nil && *refresh {
  417. val := r.FormValue("value")
  418. if _, ok := r.Form["value"]; ok && val != "" {
  419. return emptyReq, false, etcdErr.NewRequestError(
  420. etcdErr.EcodeRefreshValue,
  421. `A value was provided on a refresh`,
  422. )
  423. }
  424. if ttl == nil {
  425. return emptyReq, false, etcdErr.NewRequestError(
  426. etcdErr.EcodeRefreshTTLRequired,
  427. `No TTL value set`,
  428. )
  429. }
  430. }
  431. }
  432. rr := etcdserverpb.Request{
  433. Method: r.Method,
  434. Path: p,
  435. Val: r.FormValue("value"),
  436. Dir: dir,
  437. PrevValue: pV,
  438. PrevIndex: pIdx,
  439. PrevExist: pe,
  440. Wait: wait,
  441. Since: wIdx,
  442. Recursive: rec,
  443. Sorted: sort,
  444. Quorum: quorum,
  445. Stream: stream,
  446. }
  447. if pe != nil {
  448. rr.PrevExist = pe
  449. }
  450. if refresh != nil {
  451. rr.Refresh = refresh
  452. }
  453. // Null TTL is equivalent to unset Expiration
  454. if ttl != nil {
  455. expr := time.Duration(*ttl) * time.Second
  456. rr.Expiration = clock.Now().Add(expr).UnixNano()
  457. }
  458. return rr, noValueOnSuccess, nil
  459. }
  460. // writeKeyEvent trims the prefix of key path in a single Event under
  461. // StoreKeysPrefix, serializes it and writes the resulting JSON to the given
  462. // ResponseWriter, along with the appropriate headers.
  463. func writeKeyEvent(w http.ResponseWriter, resp etcdserver.Response, noValueOnSuccess bool) error {
  464. ev := resp.Event
  465. if ev == nil {
  466. return errors.New("cannot write empty Event!")
  467. }
  468. w.Header().Set("Content-Type", "application/json")
  469. w.Header().Set("X-Etcd-Index", fmt.Sprint(ev.EtcdIndex))
  470. w.Header().Set("X-Raft-Index", fmt.Sprint(resp.Index))
  471. w.Header().Set("X-Raft-Term", fmt.Sprint(resp.Term))
  472. if ev.IsCreated() {
  473. w.WriteHeader(http.StatusCreated)
  474. }
  475. ev = trimEventPrefix(ev, etcdserver.StoreKeysPrefix)
  476. if noValueOnSuccess &&
  477. (ev.Action == store.Set || ev.Action == store.CompareAndSwap ||
  478. ev.Action == store.Create || ev.Action == store.Update) {
  479. ev.Node = nil
  480. ev.PrevNode = nil
  481. }
  482. return json.NewEncoder(w).Encode(ev)
  483. }
  484. func writeKeyNoAuth(w http.ResponseWriter) {
  485. e := etcdErr.NewError(etcdErr.EcodeUnauthorized, "Insufficient credentials", 0)
  486. e.WriteTo(w)
  487. }
  488. // writeKeyError logs and writes the given Error to the ResponseWriter.
  489. // If Error is not an etcdErr, the error will be converted to an etcd error.
  490. func writeKeyError(w http.ResponseWriter, err error) {
  491. if err == nil {
  492. return
  493. }
  494. switch e := err.(type) {
  495. case *etcdErr.Error:
  496. e.WriteTo(w)
  497. default:
  498. switch err {
  499. case etcdserver.ErrTimeoutDueToLeaderFail, etcdserver.ErrTimeoutDueToConnectionLost:
  500. mlog.MergeError(err)
  501. default:
  502. mlog.MergeErrorf("got unexpected response error (%v)", err)
  503. }
  504. ee := etcdErr.NewError(etcdErr.EcodeRaftInternal, err.Error(), 0)
  505. ee.WriteTo(w)
  506. }
  507. }
  508. func handleKeyWatch(ctx context.Context, w http.ResponseWriter, resp etcdserver.Response, stream bool) {
  509. wa := resp.Watcher
  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(resp.Index))
  519. w.Header().Set("X-Raft-Term", fmt.Sprint(resp.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. }