http.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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 "go.etcd.io/etcd/etcdserver/etcdserverpb"
  24. "go.etcd.io/etcd/lease"
  25. "go.etcd.io/etcd/lease/leasepb"
  26. "go.etcd.io/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. defer r.Body.Close()
  48. b, err := ioutil.ReadAll(r.Body)
  49. if err != nil {
  50. http.Error(w, "error reading body", http.StatusBadRequest)
  51. return
  52. }
  53. var v []byte
  54. switch r.URL.Path {
  55. case LeasePrefix:
  56. lreq := pb.LeaseKeepAliveRequest{}
  57. if uerr := lreq.Unmarshal(b); uerr != nil {
  58. http.Error(w, "error unmarshalling request", http.StatusBadRequest)
  59. return
  60. }
  61. select {
  62. case <-h.waitch():
  63. case <-time.After(applyTimeout):
  64. http.Error(w, ErrLeaseHTTPTimeout.Error(), http.StatusRequestTimeout)
  65. return
  66. }
  67. ttl, rerr := h.l.Renew(lease.LeaseID(lreq.ID))
  68. if rerr != nil {
  69. if rerr == lease.ErrLeaseNotFound {
  70. http.Error(w, rerr.Error(), http.StatusNotFound)
  71. return
  72. }
  73. http.Error(w, rerr.Error(), http.StatusBadRequest)
  74. return
  75. }
  76. // TODO: fill out ResponseHeader
  77. resp := &pb.LeaseKeepAliveResponse{ID: lreq.ID, TTL: ttl}
  78. v, err = resp.Marshal()
  79. if err != nil {
  80. http.Error(w, err.Error(), http.StatusInternalServerError)
  81. return
  82. }
  83. case LeaseInternalPrefix:
  84. lreq := leasepb.LeaseInternalRequest{}
  85. if lerr := lreq.Unmarshal(b); lerr != nil {
  86. http.Error(w, "error unmarshalling request", http.StatusBadRequest)
  87. return
  88. }
  89. select {
  90. case <-h.waitch():
  91. case <-time.After(applyTimeout):
  92. http.Error(w, ErrLeaseHTTPTimeout.Error(), http.StatusRequestTimeout)
  93. return
  94. }
  95. l := h.l.Lookup(lease.LeaseID(lreq.LeaseTimeToLiveRequest.ID))
  96. if l == nil {
  97. http.Error(w, lease.ErrLeaseNotFound.Error(), http.StatusNotFound)
  98. return
  99. }
  100. // TODO: fill out ResponseHeader
  101. resp := &leasepb.LeaseInternalResponse{
  102. LeaseTimeToLiveResponse: &pb.LeaseTimeToLiveResponse{
  103. Header: &pb.ResponseHeader{},
  104. ID: lreq.LeaseTimeToLiveRequest.ID,
  105. TTL: int64(l.Remaining().Seconds()),
  106. GrantedTTL: l.TTL(),
  107. },
  108. }
  109. if lreq.LeaseTimeToLiveRequest.Keys {
  110. ks := l.Keys()
  111. kbs := make([][]byte, len(ks))
  112. for i := range ks {
  113. kbs[i] = []byte(ks[i])
  114. }
  115. resp.LeaseTimeToLiveResponse.Keys = kbs
  116. }
  117. v, err = resp.Marshal()
  118. if err != nil {
  119. http.Error(w, err.Error(), http.StatusInternalServerError)
  120. return
  121. }
  122. default:
  123. http.Error(w, fmt.Sprintf("unknown request path %q", r.URL.Path), http.StatusBadRequest)
  124. return
  125. }
  126. w.Header().Set("Content-Type", "application/protobuf")
  127. w.Write(v)
  128. }
  129. // RenewHTTP renews a lease at a given primary server.
  130. // TODO: Batch request in future?
  131. func RenewHTTP(ctx context.Context, id lease.LeaseID, url string, rt http.RoundTripper) (int64, error) {
  132. // will post lreq protobuf to leader
  133. lreq, err := (&pb.LeaseKeepAliveRequest{ID: int64(id)}).Marshal()
  134. if err != nil {
  135. return -1, err
  136. }
  137. cc := &http.Client{Transport: rt}
  138. req, err := http.NewRequest("POST", url, bytes.NewReader(lreq))
  139. if err != nil {
  140. return -1, err
  141. }
  142. req.Header.Set("Content-Type", "application/protobuf")
  143. req.Cancel = ctx.Done()
  144. resp, err := cc.Do(req)
  145. if err != nil {
  146. return -1, err
  147. }
  148. b, err := readResponse(resp)
  149. if err != nil {
  150. return -1, err
  151. }
  152. if resp.StatusCode == http.StatusRequestTimeout {
  153. return -1, ErrLeaseHTTPTimeout
  154. }
  155. if resp.StatusCode == http.StatusNotFound {
  156. return -1, lease.ErrLeaseNotFound
  157. }
  158. if resp.StatusCode != http.StatusOK {
  159. return -1, fmt.Errorf("lease: unknown error(%s)", string(b))
  160. }
  161. lresp := &pb.LeaseKeepAliveResponse{}
  162. if err := lresp.Unmarshal(b); err != nil {
  163. return -1, fmt.Errorf(`lease: %v. data = "%s"`, err, string(b))
  164. }
  165. if lresp.ID != int64(id) {
  166. return -1, fmt.Errorf("lease: renew id mismatch")
  167. }
  168. return lresp.TTL, nil
  169. }
  170. // TimeToLiveHTTP retrieves lease information of the given lease ID.
  171. func TimeToLiveHTTP(ctx context.Context, id lease.LeaseID, keys bool, url string, rt http.RoundTripper) (*leasepb.LeaseInternalResponse, error) {
  172. // will post lreq protobuf to leader
  173. lreq, err := (&leasepb.LeaseInternalRequest{
  174. LeaseTimeToLiveRequest: &pb.LeaseTimeToLiveRequest{
  175. ID: int64(id),
  176. Keys: keys,
  177. },
  178. }).Marshal()
  179. if err != nil {
  180. return nil, err
  181. }
  182. req, err := http.NewRequest("POST", url, bytes.NewReader(lreq))
  183. if err != nil {
  184. return nil, err
  185. }
  186. req.Header.Set("Content-Type", "application/protobuf")
  187. req = req.WithContext(ctx)
  188. cc := &http.Client{Transport: rt}
  189. var b []byte
  190. // buffer errc channel so that errc don't block inside the go routinue
  191. resp, err := cc.Do(req)
  192. if err != nil {
  193. return nil, err
  194. }
  195. b, err = readResponse(resp)
  196. if err != nil {
  197. return nil, err
  198. }
  199. if resp.StatusCode == http.StatusRequestTimeout {
  200. return nil, ErrLeaseHTTPTimeout
  201. }
  202. if resp.StatusCode == http.StatusNotFound {
  203. return nil, lease.ErrLeaseNotFound
  204. }
  205. if resp.StatusCode != http.StatusOK {
  206. return nil, fmt.Errorf("lease: unknown error(%s)", string(b))
  207. }
  208. lresp := &leasepb.LeaseInternalResponse{}
  209. if err := lresp.Unmarshal(b); err != nil {
  210. return nil, fmt.Errorf(`lease: %v. data = "%s"`, err, string(b))
  211. }
  212. if lresp.LeaseTimeToLiveResponse.ID != int64(id) {
  213. return nil, fmt.Errorf("lease: renew id mismatch")
  214. }
  215. return lresp, nil
  216. }
  217. func readResponse(resp *http.Response) (b []byte, err error) {
  218. b, err = ioutil.ReadAll(resp.Body)
  219. httputil.GracefulClose(resp)
  220. return
  221. }