http.go 6.4 KB

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