client.go 18 KB

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