http.go 6.4 KB

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