lease.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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 clientv3
  15. import (
  16. "sync"
  17. "time"
  18. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  19. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  20. "golang.org/x/net/context"
  21. "google.golang.org/grpc"
  22. )
  23. type (
  24. LeaseRevokeResponse pb.LeaseRevokeResponse
  25. LeaseID int64
  26. )
  27. // LeaseGrantResponse is used to convert the protobuf grant response.
  28. type LeaseGrantResponse struct {
  29. *pb.ResponseHeader
  30. ID LeaseID
  31. TTL int64
  32. Error string
  33. }
  34. // LeaseKeepAliveResponse is used to convert the protobuf keepalive response.
  35. type LeaseKeepAliveResponse struct {
  36. *pb.ResponseHeader
  37. ID LeaseID
  38. TTL int64
  39. }
  40. // LeaseTimeToLiveResponse is used to convert the protobuf lease timetolive response.
  41. type LeaseTimeToLiveResponse struct {
  42. *pb.ResponseHeader
  43. ID LeaseID `json:"id"`
  44. // TTL is the remaining TTL in seconds for the lease; the lease will expire in under TTL+1 seconds.
  45. TTL int64 `json:"ttl"`
  46. // GrantedTTL is the initial granted time in seconds upon lease creation/renewal.
  47. GrantedTTL int64 `json:"granted-ttl"`
  48. // Keys is the list of keys attached to this lease.
  49. Keys [][]byte `json:"keys"`
  50. }
  51. const (
  52. // defaultTTL is the assumed lease TTL used for the first keepalive
  53. // deadline before the actual TTL is known to the client.
  54. defaultTTL = 5 * time.Second
  55. // a small buffer to store unsent lease responses.
  56. leaseResponseChSize = 16
  57. // NoLease is a lease ID for the absence of a lease.
  58. NoLease LeaseID = 0
  59. )
  60. // ErrKeepAliveHalted is returned if client keep alive loop halts with an unexpected error.
  61. //
  62. // This usually means that automatic lease renewal via KeepAlive is broken, but KeepAliveOnce will still work as expected.
  63. type ErrKeepAliveHalted struct {
  64. Reason error
  65. }
  66. func (e ErrKeepAliveHalted) Error() string {
  67. s := "etcdclient: leases keep alive halted"
  68. if e.Reason != nil {
  69. s += ": " + e.Reason.Error()
  70. }
  71. return s
  72. }
  73. type Lease interface {
  74. // Grant creates a new lease.
  75. Grant(ctx context.Context, ttl int64) (*LeaseGrantResponse, error)
  76. // Revoke revokes the given lease.
  77. Revoke(ctx context.Context, id LeaseID) (*LeaseRevokeResponse, error)
  78. // TimeToLive retrieves the lease information of the given lease ID.
  79. TimeToLive(ctx context.Context, id LeaseID, opts ...LeaseOption) (*LeaseTimeToLiveResponse, error)
  80. // KeepAlive keeps the given lease alive forever.
  81. KeepAlive(ctx context.Context, id LeaseID) (<-chan *LeaseKeepAliveResponse, error)
  82. // KeepAliveOnce renews the lease once. In most of the cases, Keepalive
  83. // should be used instead of KeepAliveOnce.
  84. KeepAliveOnce(ctx context.Context, id LeaseID) (*LeaseKeepAliveResponse, error)
  85. // Close releases all resources Lease keeps for efficient communication
  86. // with the etcd server.
  87. Close() error
  88. }
  89. type lessor struct {
  90. mu sync.Mutex // guards all fields
  91. // donec is closed and loopErr is set when recvKeepAliveLoop stops
  92. donec chan struct{}
  93. loopErr error
  94. remote pb.LeaseClient
  95. stream pb.Lease_LeaseKeepAliveClient
  96. streamCancel context.CancelFunc
  97. stopCtx context.Context
  98. stopCancel context.CancelFunc
  99. keepAlives map[LeaseID]*keepAlive
  100. // firstKeepAliveTimeout is the timeout for the first keepalive request
  101. // before the actual TTL is known to the lease client
  102. firstKeepAliveTimeout time.Duration
  103. }
  104. // keepAlive multiplexes a keepalive for a lease over multiple channels
  105. type keepAlive struct {
  106. chs []chan<- *LeaseKeepAliveResponse
  107. ctxs []context.Context
  108. // deadline is the time the keep alive channels close if no response
  109. deadline time.Time
  110. // nextKeepAlive is when to send the next keep alive message
  111. nextKeepAlive time.Time
  112. // donec is closed on lease revoke, expiration, or cancel.
  113. donec chan struct{}
  114. }
  115. func NewLease(c *Client) Lease {
  116. l := &lessor{
  117. donec: make(chan struct{}),
  118. keepAlives: make(map[LeaseID]*keepAlive),
  119. remote: RetryLeaseClient(c),
  120. firstKeepAliveTimeout: c.cfg.DialTimeout + time.Second,
  121. }
  122. if l.firstKeepAliveTimeout == time.Second {
  123. l.firstKeepAliveTimeout = defaultTTL
  124. }
  125. l.stopCtx, l.stopCancel = context.WithCancel(context.Background())
  126. go l.recvKeepAliveLoop()
  127. go l.deadlineLoop()
  128. return l
  129. }
  130. func (l *lessor) Grant(ctx context.Context, ttl int64) (*LeaseGrantResponse, error) {
  131. for {
  132. r := &pb.LeaseGrantRequest{TTL: ttl}
  133. resp, err := l.remote.LeaseGrant(ctx, r)
  134. if err == nil {
  135. gresp := &LeaseGrantResponse{
  136. ResponseHeader: resp.GetHeader(),
  137. ID: LeaseID(resp.ID),
  138. TTL: resp.TTL,
  139. Error: resp.Error,
  140. }
  141. return gresp, nil
  142. }
  143. if isHaltErr(ctx, err) {
  144. return nil, toErr(ctx, err)
  145. }
  146. }
  147. }
  148. func (l *lessor) Revoke(ctx context.Context, id LeaseID) (*LeaseRevokeResponse, error) {
  149. for {
  150. r := &pb.LeaseRevokeRequest{ID: int64(id)}
  151. resp, err := l.remote.LeaseRevoke(ctx, r)
  152. if err == nil {
  153. return (*LeaseRevokeResponse)(resp), nil
  154. }
  155. if isHaltErr(ctx, err) {
  156. return nil, toErr(ctx, err)
  157. }
  158. }
  159. }
  160. func (l *lessor) TimeToLive(ctx context.Context, id LeaseID, opts ...LeaseOption) (*LeaseTimeToLiveResponse, error) {
  161. for {
  162. r := toLeaseTimeToLiveRequest(id, opts...)
  163. resp, err := l.remote.LeaseTimeToLive(ctx, r, grpc.FailFast(false))
  164. if err == nil {
  165. gresp := &LeaseTimeToLiveResponse{
  166. ResponseHeader: resp.GetHeader(),
  167. ID: LeaseID(resp.ID),
  168. TTL: resp.TTL,
  169. GrantedTTL: resp.GrantedTTL,
  170. Keys: resp.Keys,
  171. }
  172. return gresp, nil
  173. }
  174. if isHaltErr(ctx, err) {
  175. return nil, toErr(ctx, err)
  176. }
  177. }
  178. }
  179. func (l *lessor) KeepAlive(ctx context.Context, id LeaseID) (<-chan *LeaseKeepAliveResponse, error) {
  180. ch := make(chan *LeaseKeepAliveResponse, leaseResponseChSize)
  181. l.mu.Lock()
  182. // ensure that recvKeepAliveLoop is still running
  183. select {
  184. case <-l.donec:
  185. err := l.loopErr
  186. l.mu.Unlock()
  187. close(ch)
  188. return ch, ErrKeepAliveHalted{Reason: err}
  189. default:
  190. }
  191. ka, ok := l.keepAlives[id]
  192. if !ok {
  193. // create fresh keep alive
  194. ka = &keepAlive{
  195. chs: []chan<- *LeaseKeepAliveResponse{ch},
  196. ctxs: []context.Context{ctx},
  197. deadline: time.Now().Add(l.firstKeepAliveTimeout),
  198. nextKeepAlive: time.Now(),
  199. donec: make(chan struct{}),
  200. }
  201. l.keepAlives[id] = ka
  202. } else {
  203. // add channel and context to existing keep alive
  204. ka.ctxs = append(ka.ctxs, ctx)
  205. ka.chs = append(ka.chs, ch)
  206. }
  207. l.mu.Unlock()
  208. go l.keepAliveCtxCloser(id, ctx, ka.donec)
  209. return ch, nil
  210. }
  211. func (l *lessor) KeepAliveOnce(ctx context.Context, id LeaseID) (*LeaseKeepAliveResponse, error) {
  212. for {
  213. resp, err := l.keepAliveOnce(ctx, id)
  214. if err == nil {
  215. if resp.TTL == 0 {
  216. err = rpctypes.ErrLeaseNotFound
  217. }
  218. return resp, err
  219. }
  220. if isHaltErr(ctx, err) {
  221. return nil, toErr(ctx, err)
  222. }
  223. }
  224. }
  225. func (l *lessor) Close() error {
  226. l.stopCancel()
  227. <-l.donec
  228. return nil
  229. }
  230. func (l *lessor) keepAliveCtxCloser(id LeaseID, ctx context.Context, donec <-chan struct{}) {
  231. select {
  232. case <-donec:
  233. return
  234. case <-l.donec:
  235. return
  236. case <-ctx.Done():
  237. }
  238. l.mu.Lock()
  239. defer l.mu.Unlock()
  240. ka, ok := l.keepAlives[id]
  241. if !ok {
  242. return
  243. }
  244. // close channel and remove context if still associated with keep alive
  245. for i, c := range ka.ctxs {
  246. if c == ctx {
  247. close(ka.chs[i])
  248. ka.ctxs = append(ka.ctxs[:i], ka.ctxs[i+1:]...)
  249. ka.chs = append(ka.chs[:i], ka.chs[i+1:]...)
  250. break
  251. }
  252. }
  253. // remove if no one more listeners
  254. if len(ka.chs) == 0 {
  255. delete(l.keepAlives, id)
  256. }
  257. }
  258. func (l *lessor) keepAliveOnce(ctx context.Context, id LeaseID) (*LeaseKeepAliveResponse, error) {
  259. cctx, cancel := context.WithCancel(ctx)
  260. defer cancel()
  261. stream, err := l.remote.LeaseKeepAlive(cctx, grpc.FailFast(false))
  262. if err != nil {
  263. return nil, toErr(ctx, err)
  264. }
  265. err = stream.Send(&pb.LeaseKeepAliveRequest{ID: int64(id)})
  266. if err != nil {
  267. return nil, toErr(ctx, err)
  268. }
  269. resp, rerr := stream.Recv()
  270. if rerr != nil {
  271. return nil, toErr(ctx, rerr)
  272. }
  273. karesp := &LeaseKeepAliveResponse{
  274. ResponseHeader: resp.GetHeader(),
  275. ID: LeaseID(resp.ID),
  276. TTL: resp.TTL,
  277. }
  278. return karesp, nil
  279. }
  280. func (l *lessor) recvKeepAliveLoop() (gerr error) {
  281. defer func() {
  282. l.mu.Lock()
  283. close(l.donec)
  284. l.loopErr = gerr
  285. for _, ka := range l.keepAlives {
  286. ka.Close()
  287. }
  288. l.keepAlives = make(map[LeaseID]*keepAlive)
  289. l.mu.Unlock()
  290. }()
  291. stream, serr := l.resetRecv()
  292. for serr == nil {
  293. resp, err := stream.Recv()
  294. if err != nil {
  295. if isHaltErr(l.stopCtx, err) {
  296. return err
  297. }
  298. stream, serr = l.resetRecv()
  299. continue
  300. }
  301. l.recvKeepAlive(resp)
  302. }
  303. return serr
  304. }
  305. // resetRecv opens a new lease stream and starts sending LeaseKeepAliveRequests
  306. func (l *lessor) resetRecv() (pb.Lease_LeaseKeepAliveClient, error) {
  307. sctx, cancel := context.WithCancel(l.stopCtx)
  308. stream, err := l.remote.LeaseKeepAlive(sctx, grpc.FailFast(false))
  309. if err = toErr(sctx, err); err != nil {
  310. cancel()
  311. return nil, err
  312. }
  313. l.mu.Lock()
  314. defer l.mu.Unlock()
  315. if l.stream != nil && l.streamCancel != nil {
  316. l.stream.CloseSend()
  317. l.streamCancel()
  318. }
  319. l.streamCancel = cancel
  320. l.stream = stream
  321. go l.sendKeepAliveLoop(stream)
  322. return stream, nil
  323. }
  324. // recvKeepAlive updates a lease based on its LeaseKeepAliveResponse
  325. func (l *lessor) recvKeepAlive(resp *pb.LeaseKeepAliveResponse) {
  326. karesp := &LeaseKeepAliveResponse{
  327. ResponseHeader: resp.GetHeader(),
  328. ID: LeaseID(resp.ID),
  329. TTL: resp.TTL,
  330. }
  331. l.mu.Lock()
  332. defer l.mu.Unlock()
  333. ka, ok := l.keepAlives[karesp.ID]
  334. if !ok {
  335. return
  336. }
  337. if karesp.TTL <= 0 {
  338. // lease expired; close all keep alive channels
  339. delete(l.keepAlives, karesp.ID)
  340. ka.Close()
  341. return
  342. }
  343. // send update to all channels
  344. nextKeepAlive := time.Now().Add(1 + time.Duration(karesp.TTL/3)*time.Second)
  345. ka.deadline = time.Now().Add(time.Duration(karesp.TTL) * time.Second)
  346. for _, ch := range ka.chs {
  347. select {
  348. case ch <- karesp:
  349. ka.nextKeepAlive = nextKeepAlive
  350. default:
  351. }
  352. }
  353. }
  354. // deadlineLoop reaps any keep alive channels that have not received a response
  355. // within the lease TTL
  356. func (l *lessor) deadlineLoop() {
  357. for {
  358. select {
  359. case <-time.After(time.Second):
  360. case <-l.donec:
  361. return
  362. }
  363. now := time.Now()
  364. l.mu.Lock()
  365. for id, ka := range l.keepAlives {
  366. if ka.deadline.Before(now) {
  367. // waited too long for response; lease may be expired
  368. ka.Close()
  369. delete(l.keepAlives, id)
  370. }
  371. }
  372. l.mu.Unlock()
  373. }
  374. }
  375. // sendKeepAliveLoop sends LeaseKeepAliveRequests for the lifetime of a lease stream
  376. func (l *lessor) sendKeepAliveLoop(stream pb.Lease_LeaseKeepAliveClient) {
  377. for {
  378. var tosend []LeaseID
  379. now := time.Now()
  380. l.mu.Lock()
  381. for id, ka := range l.keepAlives {
  382. if ka.nextKeepAlive.Before(now) {
  383. tosend = append(tosend, id)
  384. }
  385. }
  386. l.mu.Unlock()
  387. for _, id := range tosend {
  388. r := &pb.LeaseKeepAliveRequest{ID: int64(id)}
  389. if err := stream.Send(r); err != nil {
  390. // TODO do something with this error?
  391. return
  392. }
  393. }
  394. select {
  395. case <-time.After(500 * time.Millisecond):
  396. case <-stream.Context().Done():
  397. return
  398. case <-l.donec:
  399. return
  400. case <-l.stopCtx.Done():
  401. return
  402. }
  403. }
  404. }
  405. func (ka *keepAlive) Close() {
  406. close(ka.donec)
  407. for _, ch := range ka.chs {
  408. close(ch)
  409. }
  410. }