http.go 8.7 KB

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