http.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. "strconv"
  14. "strings"
  15. "time"
  16. crand "crypto/rand"
  17. "math/rand"
  18. "github.com/coreos/etcd/elog"
  19. etcderrors "github.com/coreos/etcd/error"
  20. "github.com/coreos/etcd/etcdserver"
  21. "github.com/coreos/etcd/etcdserver/etcdserverpb"
  22. "github.com/coreos/etcd/raft/raftpb"
  23. "github.com/coreos/etcd/store"
  24. "github.com/coreos/etcd/third_party/code.google.com/p/go.net/context"
  25. )
  26. type Peers map[int64][]string
  27. func (ps Peers) Pick(id int64) string {
  28. addrs := ps[id]
  29. if len(addrs) == 0 {
  30. return ""
  31. }
  32. return fmt.Sprintf("http://%s", addrs[rand.Intn(len(addrs))])
  33. }
  34. // Set parses command line sets of names to ips formatted like:
  35. // a=1.1.1.1&a=1.1.1.2&b=2.2.2.2
  36. func (ps Peers) Set(s string) error {
  37. v, err := url.ParseQuery(s)
  38. if err != nil {
  39. return err
  40. }
  41. for k, v := range v {
  42. id, err := strconv.ParseInt(k, 0, 64)
  43. if err != nil {
  44. return err
  45. }
  46. ps[id] = v
  47. }
  48. return nil
  49. }
  50. func (ps Peers) String() string {
  51. return "todo"
  52. }
  53. func (ps Peers) Ids() []int64 {
  54. var ids []int64
  55. for id, _ := range ps {
  56. ids = append(ids, id)
  57. }
  58. return ids
  59. }
  60. var errClosed = errors.New("etcdhttp: client closed connection")
  61. const DefaultTimeout = 500 * time.Millisecond
  62. func Sender(p Peers) func(msgs []raftpb.Message) {
  63. return func(msgs []raftpb.Message) {
  64. for _, m := range msgs {
  65. // TODO: create workers that deal with message sending
  66. // concurrently as to not block progress
  67. for {
  68. url := p.Pick(m.To)
  69. if url == "" {
  70. // TODO: unknown peer id.. what do we do? I
  71. // don't think his should ever happen, need to
  72. // look into this further.
  73. log.Println("etcdhttp: no addr for %d", m.To)
  74. break
  75. }
  76. url += "/raft"
  77. // TODO: don't block. we should be able to have 1000s
  78. // of messages out at a time.
  79. data, err := m.Marshal()
  80. if err != nil {
  81. log.Println("etcdhttp: dropping message:", err)
  82. break // drop bad message
  83. }
  84. if httpPost(url, data) {
  85. break // success
  86. }
  87. // TODO: backoff
  88. }
  89. }
  90. }
  91. }
  92. func httpPost(url string, data []byte) bool {
  93. // TODO: set timeouts
  94. resp, err := http.Post(url, "application/protobuf", bytes.NewBuffer(data))
  95. if err != nil {
  96. elog.TODO()
  97. return false
  98. }
  99. if resp.StatusCode != 200 {
  100. elog.TODO()
  101. return false
  102. }
  103. return true
  104. }
  105. // Handler implements the http.Handler interface and serves etcd client and
  106. // raft communication.
  107. type Handler struct {
  108. Timeout time.Duration
  109. Server *etcdserver.Server
  110. }
  111. func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  112. // TODO: set read/write timeout?
  113. timeout := h.Timeout
  114. if timeout == 0 {
  115. timeout = DefaultTimeout
  116. }
  117. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  118. defer cancel()
  119. switch {
  120. case strings.HasPrefix(r.URL.Path, "/raft"):
  121. h.serveRaft(ctx, w, r)
  122. case strings.HasPrefix(r.URL.Path, "/v2/keys/"):
  123. h.serveKeys(ctx, w, r)
  124. default:
  125. http.NotFound(w, r)
  126. }
  127. }
  128. func (h Handler) serveKeys(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  129. rr, err := parseRequest(r)
  130. if err != nil {
  131. log.Println(err) // reading of body failed
  132. return
  133. }
  134. resp, err := h.Server.Do(ctx, rr)
  135. switch e := err.(type) {
  136. case nil:
  137. case *etcderrors.Error:
  138. // TODO: gross. this should be handled in encodeResponse
  139. log.Println(err)
  140. e.Write(w)
  141. return
  142. default:
  143. log.Println(err)
  144. http.Error(w, "Internal Server Error", 500)
  145. return
  146. }
  147. if err := encodeResponse(ctx, w, resp); err != nil {
  148. http.Error(w, "Timeout while waiting for response", 504)
  149. return
  150. }
  151. }
  152. func (h Handler) serveRaft(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  153. b, err := ioutil.ReadAll(r.Body)
  154. if err != nil {
  155. log.Println("etcdhttp: error reading raft message:", err)
  156. }
  157. var m raftpb.Message
  158. if err := m.Unmarshal(b); err != nil {
  159. log.Println("etcdhttp: error unmarshaling raft message:", err)
  160. }
  161. log.Printf("etcdhttp: raft recv message from %#x: %+v", m.From, m)
  162. if err := h.Server.Node.Step(ctx, m); err != nil {
  163. log.Println("etcdhttp: error stepping raft messages:", err)
  164. }
  165. }
  166. // genId generates a random id that is: n < 0 < n.
  167. func genId() int64 {
  168. for {
  169. b := make([]byte, 8)
  170. if _, err := io.ReadFull(crand.Reader, b); err != nil {
  171. panic(err) // really bad stuff happened
  172. }
  173. n := int64(binary.BigEndian.Uint64(b))
  174. if n != 0 {
  175. return n
  176. }
  177. }
  178. }
  179. func parseRequest(r *http.Request) (etcdserverpb.Request, error) {
  180. if err := r.ParseForm(); err != nil {
  181. return etcdserverpb.Request{}, err
  182. }
  183. q := r.URL.Query()
  184. rr := etcdserverpb.Request{
  185. Id: genId(),
  186. Method: r.Method,
  187. Val: r.FormValue("value"),
  188. Path: r.URL.Path[len("/v2/keys"):],
  189. PrevValue: q.Get("prevValue"),
  190. PrevIndex: parseUint64(q.Get("prevIndex")),
  191. Recursive: parseBool(q.Get("recursive")),
  192. Since: parseUint64(q.Get("waitIndex")),
  193. Sorted: parseBool(q.Get("sorted")),
  194. Wait: parseBool(q.Get("wait")),
  195. }
  196. // PrevExists is nullable, so we leave it null if prevExist wasn't
  197. // specified.
  198. _, ok := q["prevExists"]
  199. if ok {
  200. bv := parseBool(q.Get("prevExists"))
  201. rr.PrevExists = &bv
  202. }
  203. ttl := parseUint64(q.Get("ttl"))
  204. if ttl > 0 {
  205. expr := time.Duration(ttl) * time.Second
  206. rr.Expiration = time.Now().Add(expr).UnixNano()
  207. }
  208. return rr, nil
  209. }
  210. func parseBool(s string) bool {
  211. v, _ := strconv.ParseBool(s)
  212. return v
  213. }
  214. func parseUint64(s string) uint64 {
  215. v, _ := strconv.ParseUint(s, 10, 64)
  216. return v
  217. }
  218. func encodeResponse(ctx context.Context, w http.ResponseWriter, resp etcdserver.Response) (err error) {
  219. var ev *store.Event
  220. switch {
  221. case resp.Event != nil:
  222. ev = resp.Event
  223. case resp.Watcher != nil:
  224. ev, err = waitForEvent(ctx, w, resp.Watcher)
  225. if err != nil {
  226. return err
  227. }
  228. default:
  229. panic("should not be reachable")
  230. }
  231. w.Header().Set("Content-Type", "application/json")
  232. w.Header().Add("X-Etcd-Index", fmt.Sprint(ev.Index()))
  233. if ev.IsCreated() {
  234. w.WriteHeader(http.StatusCreated)
  235. }
  236. if err := json.NewEncoder(w).Encode(ev); err != nil {
  237. panic(err) // should never be reached
  238. }
  239. return nil
  240. }
  241. func waitForEvent(ctx context.Context, w http.ResponseWriter, wa *store.Watcher) (*store.Event, error) {
  242. // TODO(bmizerany): support streaming?
  243. defer wa.Remove()
  244. var nch <-chan bool
  245. if x, ok := w.(http.CloseNotifier); ok {
  246. nch = x.CloseNotify()
  247. }
  248. select {
  249. case ev := <-wa.EventChan:
  250. return ev, nil
  251. case <-nch:
  252. elog.TODO()
  253. return nil, errClosed
  254. case <-ctx.Done():
  255. return nil, ctx.Err()
  256. }
  257. }