http.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. // Copyright 2016 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package leasehttp
  15. import (
  16. "bytes"
  17. "context"
  18. "errors"
  19. "fmt"
  20. "io/ioutil"
  21. "net/http"
  22. "time"
  23. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  24. "github.com/coreos/etcd/lease"
  25. "github.com/coreos/etcd/lease/leasepb"
  26. "github.com/coreos/etcd/pkg/httputil"
  27. )
  28. var (
  29. LeasePrefix = "/leases"
  30. LeaseInternalPrefix = "/leases/internal"
  31. applyTimeout = time.Second
  32. ErrLeaseHTTPTimeout = errors.New("waiting for node to catch up its applied index has timed out")
  33. )
  34. // NewHandler returns an http Handler for lease renewals
  35. func NewHandler(l lease.Lessor, waitch func() <-chan struct{}) http.Handler {
  36. return &leaseHandler{l, waitch}
  37. }
  38. type leaseHandler struct {
  39. l lease.Lessor
  40. waitch func() <-chan struct{}
  41. }
  42. func (h *leaseHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  43. if r.Method != "POST" {
  44. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  45. return
  46. }
  47. b, err := ioutil.ReadAll(r.Body)
  48. if err != nil {
  49. http.Error(w, "error reading body", http.StatusBadRequest)
  50. return
  51. }
  52. var v []byte
  53. switch r.URL.Path {
  54. case LeasePrefix:
  55. lreq := pb.LeaseKeepAliveRequest{}
  56. if err := lreq.Unmarshal(b); err != nil {
  57. http.Error(w, "error unmarshalling request", http.StatusBadRequest)
  58. return
  59. }
  60. select {
  61. case <-h.waitch():
  62. case <-time.After(applyTimeout):
  63. http.Error(w, ErrLeaseHTTPTimeout.Error(), http.StatusRequestTimeout)
  64. return
  65. }
  66. ttl, err := h.l.Renew(lease.LeaseID(lreq.ID))
  67. if err != nil {
  68. if err == lease.ErrLeaseNotFound {
  69. http.Error(w, err.Error(), http.StatusNotFound)
  70. return
  71. }
  72. http.Error(w, err.Error(), http.StatusBadRequest)
  73. return
  74. }
  75. // TODO: fill out ResponseHeader
  76. resp := &pb.LeaseKeepAliveResponse{ID: lreq.ID, TTL: ttl}
  77. v, err = resp.Marshal()
  78. if err != nil {
  79. http.Error(w, err.Error(), http.StatusInternalServerError)
  80. return
  81. }
  82. case LeaseInternalPrefix:
  83. lreq := leasepb.LeaseInternalRequest{}
  84. if err := lreq.Unmarshal(b); err != nil {
  85. http.Error(w, "error unmarshalling request", http.StatusBadRequest)
  86. return
  87. }
  88. select {
  89. case <-h.waitch():
  90. case <-time.After(applyTimeout):
  91. http.Error(w, ErrLeaseHTTPTimeout.Error(), http.StatusRequestTimeout)
  92. return
  93. }
  94. l := h.l.Lookup(lease.LeaseID(lreq.LeaseTimeToLiveRequest.ID))
  95. if l == nil {
  96. http.Error(w, lease.ErrLeaseNotFound.Error(), http.StatusNotFound)
  97. return
  98. }
  99. // TODO: fill out ResponseHeader
  100. resp := &leasepb.LeaseInternalResponse{
  101. LeaseTimeToLiveResponse: &pb.LeaseTimeToLiveResponse{
  102. Header: &pb.ResponseHeader{},
  103. ID: lreq.LeaseTimeToLiveRequest.ID,
  104. TTL: int64(l.Remaining().Seconds()),
  105. GrantedTTL: l.TTL(),
  106. },
  107. }
  108. if lreq.LeaseTimeToLiveRequest.Keys {
  109. ks := l.Keys()
  110. kbs := make([][]byte, len(ks))
  111. for i := range ks {
  112. kbs[i] = []byte(ks[i])
  113. }
  114. resp.LeaseTimeToLiveResponse.Keys = kbs
  115. }
  116. v, err = resp.Marshal()
  117. if err != nil {
  118. http.Error(w, err.Error(), http.StatusInternalServerError)
  119. return
  120. }
  121. default:
  122. http.Error(w, fmt.Sprintf("unknown request path %q", r.URL.Path), http.StatusBadRequest)
  123. return
  124. }
  125. w.Header().Set("Content-Type", "application/protobuf")
  126. w.Write(v)
  127. }
  128. // RenewHTTP renews a lease at a given primary server.
  129. // TODO: Batch request in future?
  130. func RenewHTTP(ctx context.Context, id lease.LeaseID, url string, rt http.RoundTripper) (int64, error) {
  131. // will post lreq protobuf to leader
  132. lreq, err := (&pb.LeaseKeepAliveRequest{ID: int64(id)}).Marshal()
  133. if err != nil {
  134. return -1, err
  135. }
  136. cc := &http.Client{Transport: rt}
  137. req, err := http.NewRequest("POST", url, bytes.NewReader(lreq))
  138. if err != nil {
  139. return -1, err
  140. }
  141. req.Header.Set("Content-Type", "application/protobuf")
  142. req.Cancel = ctx.Done()
  143. resp, err := cc.Do(req)
  144. if err != nil {
  145. return -1, err
  146. }
  147. b, err := readResponse(resp)
  148. if err != nil {
  149. return -1, err
  150. }
  151. if resp.StatusCode == http.StatusRequestTimeout {
  152. return -1, ErrLeaseHTTPTimeout
  153. }
  154. if resp.StatusCode == http.StatusNotFound {
  155. return -1, lease.ErrLeaseNotFound
  156. }
  157. if resp.StatusCode != http.StatusOK {
  158. return -1, fmt.Errorf("lease: unknown error(%s)", string(b))
  159. }
  160. lresp := &pb.LeaseKeepAliveResponse{}
  161. if err := lresp.Unmarshal(b); err != nil {
  162. return -1, fmt.Errorf(`lease: %v. data = "%s"`, err, string(b))
  163. }
  164. if lresp.ID != int64(id) {
  165. return -1, fmt.Errorf("lease: renew id mismatch")
  166. }
  167. return lresp.TTL, nil
  168. }
  169. // TimeToLiveHTTP retrieves lease information of the given lease ID.
  170. func TimeToLiveHTTP(ctx context.Context, id lease.LeaseID, keys bool, url string, rt http.RoundTripper) (*leasepb.LeaseInternalResponse, error) {
  171. // will post lreq protobuf to leader
  172. lreq, err := (&leasepb.LeaseInternalRequest{
  173. LeaseTimeToLiveRequest: &pb.LeaseTimeToLiveRequest{
  174. ID: int64(id),
  175. Keys: keys,
  176. },
  177. }).Marshal()
  178. if err != nil {
  179. return nil, err
  180. }
  181. req, err := http.NewRequest("POST", url, bytes.NewReader(lreq))
  182. if err != nil {
  183. return nil, err
  184. }
  185. req.Header.Set("Content-Type", "application/protobuf")
  186. req = req.WithContext(ctx)
  187. cc := &http.Client{Transport: rt}
  188. var b []byte
  189. // buffer errc channel so that errc don't block inside the go routinue
  190. resp, err := cc.Do(req)
  191. if err != nil {
  192. return nil, err
  193. }
  194. b, err = readResponse(resp)
  195. if err != nil {
  196. return nil, err
  197. }
  198. if resp.StatusCode == http.StatusRequestTimeout {
  199. return nil, ErrLeaseHTTPTimeout
  200. }
  201. if resp.StatusCode == http.StatusNotFound {
  202. return nil, lease.ErrLeaseNotFound
  203. }
  204. if resp.StatusCode != http.StatusOK {
  205. return nil, fmt.Errorf("lease: unknown error(%s)", string(b))
  206. }
  207. lresp := &leasepb.LeaseInternalResponse{}
  208. if err := lresp.Unmarshal(b); err != nil {
  209. return nil, fmt.Errorf(`lease: %v. data = "%s"`, err, string(b))
  210. }
  211. if lresp.LeaseTimeToLiveResponse.ID != int64(id) {
  212. return nil, fmt.Errorf("lease: renew id mismatch")
  213. }
  214. return lresp, nil
  215. }
  216. func readResponse(resp *http.Response) (b []byte, err error) {
  217. b, err = ioutil.ReadAll(resp.Body)
  218. httputil.GracefulClose(resp)
  219. return
  220. }