http.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. package etcdhttp
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "log"
  11. "net/http"
  12. "net/url"
  13. "sort"
  14. "strconv"
  15. "strings"
  16. "time"
  17. crand "crypto/rand"
  18. "math/rand"
  19. "github.com/coreos/etcd/elog"
  20. etcderrors "github.com/coreos/etcd/error"
  21. "github.com/coreos/etcd/etcdserver"
  22. "github.com/coreos/etcd/etcdserver/etcdserverpb"
  23. "github.com/coreos/etcd/raft/raftpb"
  24. "github.com/coreos/etcd/store"
  25. "github.com/coreos/etcd/third_party/code.google.com/p/go.net/context"
  26. )
  27. const (
  28. keysPrefix = "/v2/keys"
  29. machinesPrefix = "/v2/machines"
  30. )
  31. type Peers map[int64][]string
  32. func (ps Peers) Pick(id int64) string {
  33. addrs := ps[id]
  34. if len(addrs) == 0 {
  35. return ""
  36. }
  37. return addScheme(addrs[rand.Intn(len(addrs))])
  38. }
  39. // TODO: improve this when implementing TLS
  40. func addScheme(addr string) string {
  41. return fmt.Sprintf("http://%s", addr)
  42. }
  43. // Set parses command line sets of names to ips formatted like:
  44. // a=1.1.1.1&a=1.1.1.2&b=2.2.2.2
  45. func (ps *Peers) Set(s string) error {
  46. m := make(map[int64][]string)
  47. v, err := url.ParseQuery(s)
  48. if err != nil {
  49. return err
  50. }
  51. for k, v := range v {
  52. id, err := strconv.ParseInt(k, 0, 64)
  53. if err != nil {
  54. return err
  55. }
  56. m[id] = v
  57. }
  58. *ps = m
  59. return nil
  60. }
  61. func (ps *Peers) String() string {
  62. v := url.Values{}
  63. for k, vv := range *ps {
  64. for i := range vv {
  65. v.Add(strconv.FormatInt(k, 16), vv[i])
  66. }
  67. }
  68. return v.Encode()
  69. }
  70. func (ps Peers) Ids() []int64 {
  71. var ids []int64
  72. for id := range ps {
  73. ids = append(ids, id)
  74. }
  75. return ids
  76. }
  77. var errClosed = errors.New("etcdhttp: client closed connection")
  78. const DefaultTimeout = 500 * time.Millisecond
  79. func Sender(p Peers) func(msgs []raftpb.Message) {
  80. return func(msgs []raftpb.Message) {
  81. for _, m := range msgs {
  82. // TODO: reuse go routines
  83. // limit the number of outgoing connections for the same receiver
  84. go send(p, m)
  85. }
  86. }
  87. }
  88. func send(p Peers, m raftpb.Message) {
  89. // TODO (xiangli): reasonable retry logic
  90. for i := 0; i < 3; i++ {
  91. url := p.Pick(m.To)
  92. if url == "" {
  93. // TODO: unknown peer id.. what do we do? I
  94. // don't think his should ever happen, need to
  95. // look into this further.
  96. log.Println("etcdhttp: no addr for %d", m.To)
  97. return
  98. }
  99. url += "/raft"
  100. // TODO: don't block. we should be able to have 1000s
  101. // of messages out at a time.
  102. data, err := m.Marshal()
  103. if err != nil {
  104. log.Println("etcdhttp: dropping message:", err)
  105. return // drop bad message
  106. }
  107. if httpPost(url, data) {
  108. return // success
  109. }
  110. // TODO: backoff
  111. }
  112. }
  113. func httpPost(url string, data []byte) bool {
  114. // TODO: set timeouts
  115. resp, err := http.Post(url, "application/protobuf", bytes.NewBuffer(data))
  116. if err != nil {
  117. elog.TODO()
  118. return false
  119. }
  120. resp.Body.Close()
  121. if resp.StatusCode != 200 {
  122. elog.TODO()
  123. return false
  124. }
  125. return true
  126. }
  127. // Handler implements the http.Handler interface and serves etcd client and
  128. // raft communication.
  129. type Handler struct {
  130. Timeout time.Duration
  131. Server *etcdserver.Server
  132. // TODO: dynamic configuration may make this outdated. take care of it.
  133. // TODO: dynamic configuration may introduce race also.
  134. Peers Peers
  135. }
  136. func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  137. // TODO: set read/write timeout?
  138. timeout := h.Timeout
  139. if timeout == 0 {
  140. timeout = DefaultTimeout
  141. }
  142. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  143. defer cancel()
  144. switch {
  145. case strings.HasPrefix(r.URL.Path, "/raft"):
  146. h.serveRaft(ctx, w, r)
  147. case strings.HasPrefix(r.URL.Path, keysPrefix):
  148. h.serveKeys(ctx, w, r)
  149. case strings.HasPrefix(r.URL.Path, machinesPrefix):
  150. h.serveMachines(w, r)
  151. default:
  152. http.NotFound(w, r)
  153. }
  154. }
  155. func (h Handler) serveKeys(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  156. rr, err := parseRequest(r, genId())
  157. if err != nil {
  158. log.Println(err) // reading of body failed
  159. return
  160. }
  161. resp, err := h.Server.Do(ctx, rr)
  162. switch e := err.(type) {
  163. case nil:
  164. case *etcderrors.Error:
  165. // TODO: gross. this should be handled in encodeResponse
  166. log.Println(err)
  167. e.Write(w)
  168. return
  169. default:
  170. log.Println(err)
  171. http.Error(w, "Internal Server Error", http.StatusInternalServerError)
  172. return
  173. }
  174. if err := encodeResponse(ctx, w, resp); err != nil {
  175. http.Error(w, "Timeout while waiting for response", http.StatusGatewayTimeout)
  176. return
  177. }
  178. }
  179. // serveMachines responds address list in the format '0.0.0.0, 1.1.1.1'.
  180. // TODO: rethink the format of machine list because it is not json format.
  181. func (h Handler) serveMachines(w http.ResponseWriter, r *http.Request) {
  182. if r.Method != "GET" && r.Method != "HEAD" {
  183. allow(w, "GET", "HEAD")
  184. return
  185. }
  186. urls := make([]string, 0)
  187. for _, addrs := range h.Peers {
  188. for _, addr := range addrs {
  189. urls = append(urls, addScheme(addr))
  190. }
  191. }
  192. sort.Strings(urls)
  193. w.Write([]byte(strings.Join(urls, ", ")))
  194. }
  195. func (h Handler) serveRaft(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  196. b, err := ioutil.ReadAll(r.Body)
  197. if err != nil {
  198. log.Println("etcdhttp: error reading raft message:", err)
  199. }
  200. var m raftpb.Message
  201. if err := m.Unmarshal(b); err != nil {
  202. log.Println("etcdhttp: error unmarshaling raft message:", err)
  203. }
  204. log.Printf("etcdhttp: raft recv message from %#x: %+v", m.From, m)
  205. if err := h.Server.Node.Step(ctx, m); err != nil {
  206. log.Println("etcdhttp: error stepping raft messages:", err)
  207. }
  208. }
  209. // genId generates a random id that is: n < 0 < n.
  210. func genId() int64 {
  211. for {
  212. b := make([]byte, 8)
  213. if _, err := io.ReadFull(crand.Reader, b); err != nil {
  214. panic(err) // really bad stuff happened
  215. }
  216. n := int64(binary.BigEndian.Uint64(b))
  217. if n != 0 {
  218. return n
  219. }
  220. }
  221. }
  222. func parseRequest(r *http.Request, id int64) (etcdserverpb.Request, error) {
  223. if err := r.ParseForm(); err != nil {
  224. return etcdserverpb.Request{}, err
  225. }
  226. if !strings.HasPrefix(r.URL.Path, keysPrefix) {
  227. return etcdserverpb.Request{}, errors.New("unexpected key prefix!")
  228. }
  229. q := r.URL.Query()
  230. // TODO(jonboulle): perform strict validation of all parameters
  231. // https://github.com/coreos/etcd/issues/1011
  232. rr := etcdserverpb.Request{
  233. Id: id,
  234. Method: r.Method,
  235. Val: r.FormValue("value"),
  236. Path: r.URL.Path[len(keysPrefix):],
  237. PrevValue: q.Get("prevValue"),
  238. PrevIndex: parseUint64(q.Get("prevIndex")),
  239. Recursive: parseBool(q.Get("recursive")),
  240. Since: parseUint64(q.Get("waitIndex")),
  241. Sorted: parseBool(q.Get("sorted")),
  242. Wait: parseBool(q.Get("wait")),
  243. }
  244. // PrevExists is nullable, so we leave it null if prevExist wasn't
  245. // specified.
  246. _, ok := q["prevExists"]
  247. if ok {
  248. bv := parseBool(q.Get("prevExists"))
  249. rr.PrevExists = &bv
  250. }
  251. ttl := parseUint64(q.Get("ttl"))
  252. if ttl > 0 {
  253. expr := time.Duration(ttl) * time.Second
  254. // TODO(jonboulle): use fake clock instead of time module
  255. // https://github.com/coreos/etcd/issues/1021
  256. rr.Expiration = time.Now().Add(expr).UnixNano()
  257. }
  258. return rr, nil
  259. }
  260. func parseBool(s string) bool {
  261. v, _ := strconv.ParseBool(s)
  262. return v
  263. }
  264. func parseUint64(s string) uint64 {
  265. v, _ := strconv.ParseUint(s, 10, 64)
  266. return v
  267. }
  268. // encodeResponse serializes the given etcdserver Response and writes the
  269. // resulting JSON to the given ResponseWriter, utilizing the provided context
  270. func encodeResponse(ctx context.Context, w http.ResponseWriter, resp etcdserver.Response) (err error) {
  271. var ev *store.Event
  272. switch {
  273. case resp.Event != nil:
  274. ev = resp.Event
  275. case resp.Watcher != nil:
  276. ev, err = waitForEvent(ctx, w, resp.Watcher)
  277. if err != nil {
  278. return err
  279. }
  280. default:
  281. panic("should not be reachable")
  282. }
  283. w.Header().Set("Content-Type", "application/json")
  284. w.Header().Add("X-Etcd-Index", fmt.Sprint(ev.Index()))
  285. if ev.IsCreated() {
  286. w.WriteHeader(http.StatusCreated)
  287. }
  288. if err := json.NewEncoder(w).Encode(ev); err != nil {
  289. panic(err) // should never be reached
  290. }
  291. return nil
  292. }
  293. // waitForEvent waits for a given watcher to return its associated
  294. // event. It returns a non-nil error if the given Context times out
  295. // or the given ResponseWriter triggers a CloseNotify.
  296. func waitForEvent(ctx context.Context, w http.ResponseWriter, wa store.Watcher) (*store.Event, error) {
  297. // TODO(bmizerany): support streaming?
  298. defer wa.Remove()
  299. var nch <-chan bool
  300. if x, ok := w.(http.CloseNotifier); ok {
  301. nch = x.CloseNotify()
  302. }
  303. select {
  304. case ev := <-wa.EventChan():
  305. return ev, nil
  306. case <-nch:
  307. elog.TODO()
  308. return nil, errClosed
  309. case <-ctx.Done():
  310. return nil, ctx.Err()
  311. }
  312. }
  313. // allow writes response for the case that Method Not Allowed
  314. func allow(w http.ResponseWriter, m ...string) {
  315. w.Header().Set("Allow", strings.Join(m, ","))
  316. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  317. }