client.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package etcdhttp
  14. import (
  15. "encoding/json"
  16. "errors"
  17. "fmt"
  18. "io/ioutil"
  19. "log"
  20. "net/http"
  21. "net/url"
  22. "path"
  23. "strconv"
  24. "strings"
  25. "time"
  26. "github.com/coreos/etcd/Godeps/_workspace/src/code.google.com/p/go.net/context"
  27. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/jonboulle/clockwork"
  28. etcdErr "github.com/coreos/etcd/error"
  29. "github.com/coreos/etcd/etcdserver"
  30. "github.com/coreos/etcd/etcdserver/etcdserverpb"
  31. "github.com/coreos/etcd/pkg/types"
  32. "github.com/coreos/etcd/store"
  33. "github.com/coreos/etcd/version"
  34. )
  35. const (
  36. keysPrefix = "/v2/keys"
  37. deprecatedMachinesPrefix = "/v2/machines"
  38. adminMembersPrefix = "/v2/admin/members/"
  39. statsPrefix = "/v2/stats"
  40. versionPrefix = "/version"
  41. )
  42. // NewClientHandler generates a muxed http.Handler with the given parameters to serve etcd client requests.
  43. func NewClientHandler(server *etcdserver.EtcdServer) http.Handler {
  44. kh := &keysHandler{
  45. server: server,
  46. timer: server,
  47. timeout: defaultServerTimeout,
  48. }
  49. sh := &statsHandler{
  50. stats: server,
  51. }
  52. amh := &adminMembersHandler{
  53. server: server,
  54. clusterInfo: server.Cluster,
  55. clock: clockwork.NewRealClock(),
  56. }
  57. dmh := &deprecatedMachinesHandler{
  58. clusterInfo: server.Cluster,
  59. }
  60. mux := http.NewServeMux()
  61. mux.HandleFunc("/", http.NotFound)
  62. mux.HandleFunc(versionPrefix, serveVersion)
  63. mux.Handle(keysPrefix, kh)
  64. mux.Handle(keysPrefix+"/", kh)
  65. mux.HandleFunc(statsPrefix+"/store", sh.serveStore)
  66. mux.HandleFunc(statsPrefix+"/self", sh.serveSelf)
  67. mux.HandleFunc(statsPrefix+"/leader", sh.serveLeader)
  68. mux.Handle(adminMembersPrefix, amh)
  69. mux.Handle(deprecatedMachinesPrefix, dmh)
  70. return mux
  71. }
  72. type keysHandler struct {
  73. server etcdserver.Server
  74. timer etcdserver.RaftTimer
  75. timeout time.Duration
  76. }
  77. func (h *keysHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  78. if !allowMethod(w, r.Method, "GET", "PUT", "POST", "DELETE") {
  79. return
  80. }
  81. ctx, cancel := context.WithTimeout(context.Background(), h.timeout)
  82. defer cancel()
  83. rr, err := parseKeyRequest(r, etcdserver.GenID(), clockwork.NewRealClock())
  84. if err != nil {
  85. writeError(w, err)
  86. return
  87. }
  88. resp, err := h.server.Do(ctx, rr)
  89. if err != nil {
  90. err = trimErrorPrefix(err, etcdserver.StoreKeysPrefix)
  91. writeError(w, err)
  92. return
  93. }
  94. switch {
  95. case resp.Event != nil:
  96. if err := writeKeyEvent(w, resp.Event, h.timer); err != nil {
  97. // Should never be reached
  98. log.Printf("error writing event: %v", err)
  99. }
  100. case resp.Watcher != nil:
  101. ctx, cancel := context.WithTimeout(context.Background(), defaultWatchTimeout)
  102. defer cancel()
  103. handleKeyWatch(ctx, w, resp.Watcher, rr.Stream, h.timer)
  104. default:
  105. writeError(w, errors.New("received response with no Event/Watcher!"))
  106. }
  107. }
  108. type deprecatedMachinesHandler struct {
  109. clusterInfo etcdserver.ClusterInfo
  110. }
  111. func (h *deprecatedMachinesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  112. if !allowMethod(w, r.Method, "GET", "HEAD") {
  113. return
  114. }
  115. endpoints := h.clusterInfo.ClientURLs()
  116. w.Write([]byte(strings.Join(endpoints, ", ")))
  117. }
  118. type adminMembersHandler struct {
  119. server etcdserver.Server
  120. clusterInfo etcdserver.ClusterInfo
  121. clock clockwork.Clock
  122. }
  123. func (h *adminMembersHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  124. if !allowMethod(w, r.Method, "GET", "POST", "DELETE") {
  125. return
  126. }
  127. ctx, cancel := context.WithTimeout(context.Background(), defaultServerTimeout)
  128. defer cancel()
  129. switch r.Method {
  130. case "GET":
  131. if s := strings.TrimPrefix(r.URL.Path, adminMembersPrefix); s != "" {
  132. http.NotFound(w, r)
  133. return
  134. }
  135. ms := struct {
  136. Members []*etcdserver.Member `json:"members"`
  137. }{
  138. Members: h.clusterInfo.Members(),
  139. }
  140. w.Header().Set("Content-Type", "application/json")
  141. if err := json.NewEncoder(w).Encode(ms); err != nil {
  142. log.Printf("etcdhttp: %v", err)
  143. }
  144. case "POST":
  145. ctype := r.Header.Get("Content-Type")
  146. if ctype != "application/json" {
  147. http.Error(w, fmt.Sprintf("bad Content-Type %s, accept application/json", ctype), http.StatusBadRequest)
  148. return
  149. }
  150. b, err := ioutil.ReadAll(r.Body)
  151. if err != nil {
  152. http.Error(w, err.Error(), http.StatusBadRequest)
  153. return
  154. }
  155. raftAttr := etcdserver.RaftAttributes{}
  156. if err := json.Unmarshal(b, &raftAttr); err != nil {
  157. http.Error(w, err.Error(), http.StatusBadRequest)
  158. return
  159. }
  160. validURLs, err := types.NewURLs(raftAttr.PeerURLs)
  161. if err != nil {
  162. http.Error(w, "bad peer urls", http.StatusBadRequest)
  163. return
  164. }
  165. now := h.clock.Now()
  166. m := etcdserver.NewMember("", validURLs, "", &now)
  167. if err := h.server.AddMember(ctx, *m); err != nil {
  168. log.Printf("etcdhttp: error adding node %x: %v", m.ID, err)
  169. writeError(w, err)
  170. return
  171. }
  172. log.Printf("etcdhttp: added node %x with peer urls %v", m.ID, raftAttr.PeerURLs)
  173. w.Header().Set("Content-Type", "application/json")
  174. w.WriteHeader(http.StatusCreated)
  175. if err := json.NewEncoder(w).Encode(m); err != nil {
  176. log.Printf("etcdhttp: %v", err)
  177. }
  178. case "DELETE":
  179. idStr := strings.TrimPrefix(r.URL.Path, adminMembersPrefix)
  180. id, err := strconv.ParseUint(idStr, 16, 64)
  181. if err != nil {
  182. http.Error(w, err.Error(), http.StatusBadRequest)
  183. return
  184. }
  185. log.Printf("etcdhttp: remove node %x", id)
  186. if err := h.server.RemoveMember(ctx, id); err != nil {
  187. log.Printf("etcdhttp: error removing node %x: %v", id, err)
  188. writeError(w, err)
  189. return
  190. }
  191. w.WriteHeader(http.StatusNoContent)
  192. }
  193. }
  194. type statsHandler struct {
  195. stats etcdserver.Stats
  196. }
  197. func (h *statsHandler) serveStore(w http.ResponseWriter, r *http.Request) {
  198. if !allowMethod(w, r.Method, "GET") {
  199. return
  200. }
  201. w.Header().Set("Content-Type", "application/json")
  202. w.Write(h.stats.StoreStats())
  203. }
  204. func (h *statsHandler) serveSelf(w http.ResponseWriter, r *http.Request) {
  205. if !allowMethod(w, r.Method, "GET") {
  206. return
  207. }
  208. w.Header().Set("Content-Type", "application/json")
  209. w.Write(h.stats.SelfStats())
  210. }
  211. func (h *statsHandler) serveLeader(w http.ResponseWriter, r *http.Request) {
  212. if !allowMethod(w, r.Method, "GET") {
  213. return
  214. }
  215. w.Header().Set("Content-Type", "application/json")
  216. w.Write(h.stats.LeaderStats())
  217. }
  218. func serveVersion(w http.ResponseWriter, r *http.Request) {
  219. if !allowMethod(w, r.Method, "GET") {
  220. return
  221. }
  222. w.Write([]byte("etcd " + version.Version))
  223. }
  224. // parseKeyRequest converts a received http.Request on keysPrefix to
  225. // a server Request, performing validation of supplied fields as appropriate.
  226. // If any validation fails, an empty Request and non-nil error is returned.
  227. func parseKeyRequest(r *http.Request, id uint64, clock clockwork.Clock) (etcdserverpb.Request, error) {
  228. emptyReq := etcdserverpb.Request{}
  229. err := r.ParseForm()
  230. if err != nil {
  231. return emptyReq, etcdErr.NewRequestError(
  232. etcdErr.EcodeInvalidForm,
  233. err.Error(),
  234. )
  235. }
  236. if !strings.HasPrefix(r.URL.Path, keysPrefix) {
  237. return emptyReq, etcdErr.NewRequestError(
  238. etcdErr.EcodeInvalidForm,
  239. "incorrect key prefix",
  240. )
  241. }
  242. p := path.Join(etcdserver.StoreKeysPrefix, r.URL.Path[len(keysPrefix):])
  243. var pIdx, wIdx uint64
  244. if pIdx, err = getUint64(r.Form, "prevIndex"); err != nil {
  245. return emptyReq, etcdErr.NewRequestError(
  246. etcdErr.EcodeIndexNaN,
  247. `invalid value for "prevIndex"`,
  248. )
  249. }
  250. if wIdx, err = getUint64(r.Form, "waitIndex"); err != nil {
  251. return emptyReq, etcdErr.NewRequestError(
  252. etcdErr.EcodeIndexNaN,
  253. `invalid value for "waitIndex"`,
  254. )
  255. }
  256. var rec, sort, wait, dir, quorum, stream bool
  257. if rec, err = getBool(r.Form, "recursive"); err != nil {
  258. return emptyReq, etcdErr.NewRequestError(
  259. etcdErr.EcodeInvalidField,
  260. `invalid value for "recursive"`,
  261. )
  262. }
  263. if sort, err = getBool(r.Form, "sorted"); err != nil {
  264. return emptyReq, etcdErr.NewRequestError(
  265. etcdErr.EcodeInvalidField,
  266. `invalid value for "sorted"`,
  267. )
  268. }
  269. if wait, err = getBool(r.Form, "wait"); err != nil {
  270. return emptyReq, etcdErr.NewRequestError(
  271. etcdErr.EcodeInvalidField,
  272. `invalid value for "wait"`,
  273. )
  274. }
  275. // TODO(jonboulle): define what parameters dir is/isn't compatible with?
  276. if dir, err = getBool(r.Form, "dir"); err != nil {
  277. return emptyReq, etcdErr.NewRequestError(
  278. etcdErr.EcodeInvalidField,
  279. `invalid value for "dir"`,
  280. )
  281. }
  282. if quorum, err = getBool(r.Form, "quorum"); err != nil {
  283. return emptyReq, etcdErr.NewRequestError(
  284. etcdErr.EcodeInvalidField,
  285. `invalid value for "quorum"`,
  286. )
  287. }
  288. if stream, err = getBool(r.Form, "stream"); err != nil {
  289. return emptyReq, etcdErr.NewRequestError(
  290. etcdErr.EcodeInvalidField,
  291. `invalid value for "stream"`,
  292. )
  293. }
  294. if wait && r.Method != "GET" {
  295. return emptyReq, etcdErr.NewRequestError(
  296. etcdErr.EcodeInvalidField,
  297. `"wait" can only be used with GET requests`,
  298. )
  299. }
  300. pV := r.FormValue("prevValue")
  301. if _, ok := r.Form["prevValue"]; ok && pV == "" {
  302. return emptyReq, etcdErr.NewRequestError(
  303. etcdErr.EcodeInvalidField,
  304. `"prevValue" cannot be empty`,
  305. )
  306. }
  307. // TTL is nullable, so leave it null if not specified
  308. // or an empty string
  309. var ttl *uint64
  310. if len(r.FormValue("ttl")) > 0 {
  311. i, err := getUint64(r.Form, "ttl")
  312. if err != nil {
  313. return emptyReq, etcdErr.NewRequestError(
  314. etcdErr.EcodeTTLNaN,
  315. `invalid value for "ttl"`,
  316. )
  317. }
  318. ttl = &i
  319. }
  320. // prevExist is nullable, so leave it null if not specified
  321. var pe *bool
  322. if _, ok := r.Form["prevExist"]; ok {
  323. bv, err := getBool(r.Form, "prevExist")
  324. if err != nil {
  325. return emptyReq, etcdErr.NewRequestError(
  326. etcdErr.EcodeInvalidField,
  327. "invalid value for prevExist",
  328. )
  329. }
  330. pe = &bv
  331. }
  332. rr := etcdserverpb.Request{
  333. ID: id,
  334. Method: r.Method,
  335. Path: p,
  336. Val: r.FormValue("value"),
  337. Dir: dir,
  338. PrevValue: pV,
  339. PrevIndex: pIdx,
  340. PrevExist: pe,
  341. Wait: wait,
  342. Since: wIdx,
  343. Recursive: rec,
  344. Sorted: sort,
  345. Quorum: quorum,
  346. Stream: stream,
  347. }
  348. if pe != nil {
  349. rr.PrevExist = pe
  350. }
  351. // Null TTL is equivalent to unset Expiration
  352. if ttl != nil {
  353. expr := time.Duration(*ttl) * time.Second
  354. rr.Expiration = clock.Now().Add(expr).UnixNano()
  355. }
  356. return rr, nil
  357. }
  358. // writeKeyEvent trims the prefix of key path in a single Event under
  359. // StoreKeysPrefix, serializes it and writes the resulting JSON to the given
  360. // ResponseWriter, along with the appropriate headers.
  361. func writeKeyEvent(w http.ResponseWriter, ev *store.Event, rt etcdserver.RaftTimer) error {
  362. if ev == nil {
  363. return errors.New("cannot write empty Event!")
  364. }
  365. w.Header().Set("Content-Type", "application/json")
  366. w.Header().Set("X-Etcd-Index", fmt.Sprint(ev.EtcdIndex))
  367. w.Header().Set("X-Raft-Index", fmt.Sprint(rt.Index()))
  368. w.Header().Set("X-Raft-Term", fmt.Sprint(rt.Term()))
  369. if ev.IsCreated() {
  370. w.WriteHeader(http.StatusCreated)
  371. }
  372. ev = trimEventPrefix(ev, etcdserver.StoreKeysPrefix)
  373. return json.NewEncoder(w).Encode(ev)
  374. }
  375. func handleKeyWatch(ctx context.Context, w http.ResponseWriter, wa store.Watcher, stream bool, rt etcdserver.RaftTimer) {
  376. defer wa.Remove()
  377. ech := wa.EventChan()
  378. var nch <-chan bool
  379. if x, ok := w.(http.CloseNotifier); ok {
  380. nch = x.CloseNotify()
  381. }
  382. w.Header().Set("Content-Type", "application/json")
  383. w.Header().Set("X-Etcd-Index", fmt.Sprint(wa.StartIndex()))
  384. w.Header().Set("X-Raft-Index", fmt.Sprint(rt.Index()))
  385. w.Header().Set("X-Raft-Term", fmt.Sprint(rt.Term()))
  386. w.WriteHeader(http.StatusOK)
  387. // Ensure headers are flushed early, in case of long polling
  388. w.(http.Flusher).Flush()
  389. for {
  390. select {
  391. case <-nch:
  392. // Client closed connection. Nothing to do.
  393. return
  394. case <-ctx.Done():
  395. // Timed out. net/http will close the connection for us, so nothing to do.
  396. return
  397. case ev, ok := <-ech:
  398. if !ok {
  399. // If the channel is closed this may be an indication of
  400. // that notifications are much more than we are able to
  401. // send to the client in time. Then we simply end streaming.
  402. return
  403. }
  404. ev = trimEventPrefix(ev, etcdserver.StoreKeysPrefix)
  405. if err := json.NewEncoder(w).Encode(ev); err != nil {
  406. // Should never be reached
  407. log.Printf("error writing event: %v\n", err)
  408. return
  409. }
  410. if !stream {
  411. return
  412. }
  413. w.(http.Flusher).Flush()
  414. }
  415. }
  416. }
  417. func trimEventPrefix(ev *store.Event, prefix string) *store.Event {
  418. if ev == nil {
  419. return nil
  420. }
  421. ev.Node = trimNodeExternPrefix(ev.Node, prefix)
  422. ev.PrevNode = trimNodeExternPrefix(ev.PrevNode, prefix)
  423. return ev
  424. }
  425. func trimNodeExternPrefix(n *store.NodeExtern, prefix string) *store.NodeExtern {
  426. if n == nil {
  427. return nil
  428. }
  429. n.Key = strings.TrimPrefix(n.Key, prefix)
  430. for _, nn := range n.Nodes {
  431. nn = trimNodeExternPrefix(nn, prefix)
  432. }
  433. return n
  434. }
  435. func trimErrorPrefix(err error, prefix string) error {
  436. if e, ok := err.(*etcdErr.Error); ok {
  437. e.Cause = strings.TrimPrefix(e.Cause, prefix)
  438. }
  439. return err
  440. }
  441. // getUint64 extracts a uint64 by the given key from a Form. If the key does
  442. // not exist in the form, 0 is returned. If the key exists but the value is
  443. // badly formed, an error is returned. If multiple values are present only the
  444. // first is considered.
  445. func getUint64(form url.Values, key string) (i uint64, err error) {
  446. if vals, ok := form[key]; ok {
  447. i, err = strconv.ParseUint(vals[0], 10, 64)
  448. }
  449. return
  450. }
  451. // getBool extracts a bool by the given key from a Form. If the key does not
  452. // exist in the form, false is returned. If the key exists but the value is
  453. // badly formed, an error is returned. If multiple values are present only the
  454. // first is considered.
  455. func getBool(form url.Values, key string) (b bool, err error) {
  456. if vals, ok := form[key]; ok {
  457. b, err = strconv.ParseBool(vals[0])
  458. }
  459. return
  460. }