http.go 6.6 KB

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