lease.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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. cctx, cancel := context.WithCancel(ctx)
  132. done := cancelWhenStop(cancel, l.stopCtx.Done())
  133. defer close(done)
  134. for {
  135. r := &pb.LeaseGrantRequest{TTL: ttl}
  136. resp, err := l.remote.LeaseGrant(cctx, r)
  137. if err == nil {
  138. gresp := &LeaseGrantResponse{
  139. ResponseHeader: resp.GetHeader(),
  140. ID: LeaseID(resp.ID),
  141. TTL: resp.TTL,
  142. Error: resp.Error,
  143. }
  144. return gresp, nil
  145. }
  146. if isHaltErr(cctx, err) {
  147. return nil, toErr(cctx, err)
  148. }
  149. }
  150. }
  151. func (l *lessor) Revoke(ctx context.Context, id LeaseID) (*LeaseRevokeResponse, error) {
  152. cctx, cancel := context.WithCancel(ctx)
  153. done := cancelWhenStop(cancel, l.stopCtx.Done())
  154. defer close(done)
  155. for {
  156. r := &pb.LeaseRevokeRequest{ID: int64(id)}
  157. resp, err := l.remote.LeaseRevoke(cctx, r)
  158. if err == nil {
  159. return (*LeaseRevokeResponse)(resp), nil
  160. }
  161. if isHaltErr(ctx, err) {
  162. return nil, toErr(ctx, err)
  163. }
  164. }
  165. }
  166. func (l *lessor) TimeToLive(ctx context.Context, id LeaseID, opts ...LeaseOption) (*LeaseTimeToLiveResponse, error) {
  167. cctx, cancel := context.WithCancel(ctx)
  168. done := cancelWhenStop(cancel, l.stopCtx.Done())
  169. defer close(done)
  170. for {
  171. r := toLeaseTimeToLiveRequest(id, opts...)
  172. resp, err := l.remote.LeaseTimeToLive(cctx, r, grpc.FailFast(false))
  173. if err == nil {
  174. gresp := &LeaseTimeToLiveResponse{
  175. ResponseHeader: resp.GetHeader(),
  176. ID: LeaseID(resp.ID),
  177. TTL: resp.TTL,
  178. GrantedTTL: resp.GrantedTTL,
  179. Keys: resp.Keys,
  180. }
  181. return gresp, nil
  182. }
  183. if isHaltErr(cctx, err) {
  184. return nil, toErr(cctx, err)
  185. }
  186. }
  187. }
  188. func (l *lessor) KeepAlive(ctx context.Context, id LeaseID) (<-chan *LeaseKeepAliveResponse, error) {
  189. ch := make(chan *LeaseKeepAliveResponse, leaseResponseChSize)
  190. l.mu.Lock()
  191. // ensure that recvKeepAliveLoop is still running
  192. select {
  193. case <-l.donec:
  194. err := l.loopErr
  195. l.mu.Unlock()
  196. close(ch)
  197. return ch, ErrKeepAliveHalted{Reason: err}
  198. default:
  199. }
  200. ka, ok := l.keepAlives[id]
  201. if !ok {
  202. // create fresh keep alive
  203. ka = &keepAlive{
  204. chs: []chan<- *LeaseKeepAliveResponse{ch},
  205. ctxs: []context.Context{ctx},
  206. deadline: time.Now().Add(l.firstKeepAliveTimeout),
  207. nextKeepAlive: time.Now(),
  208. donec: make(chan struct{}),
  209. }
  210. l.keepAlives[id] = ka
  211. } else {
  212. // add channel and context to existing keep alive
  213. ka.ctxs = append(ka.ctxs, ctx)
  214. ka.chs = append(ka.chs, ch)
  215. }
  216. l.mu.Unlock()
  217. go l.keepAliveCtxCloser(id, ctx, ka.donec)
  218. return ch, nil
  219. }
  220. func (l *lessor) KeepAliveOnce(ctx context.Context, id LeaseID) (*LeaseKeepAliveResponse, error) {
  221. cctx, cancel := context.WithCancel(ctx)
  222. done := cancelWhenStop(cancel, l.stopCtx.Done())
  223. defer close(done)
  224. for {
  225. resp, err := l.keepAliveOnce(cctx, id)
  226. if err == nil {
  227. if resp.TTL == 0 {
  228. err = rpctypes.ErrLeaseNotFound
  229. }
  230. return resp, err
  231. }
  232. if isHaltErr(ctx, err) {
  233. return nil, toErr(ctx, err)
  234. }
  235. }
  236. }
  237. func (l *lessor) Close() error {
  238. l.stopCancel()
  239. <-l.donec
  240. return nil
  241. }
  242. func (l *lessor) keepAliveCtxCloser(id LeaseID, ctx context.Context, donec <-chan struct{}) {
  243. select {
  244. case <-donec:
  245. return
  246. case <-l.donec:
  247. return
  248. case <-ctx.Done():
  249. }
  250. l.mu.Lock()
  251. defer l.mu.Unlock()
  252. ka, ok := l.keepAlives[id]
  253. if !ok {
  254. return
  255. }
  256. // close channel and remove context if still associated with keep alive
  257. for i, c := range ka.ctxs {
  258. if c == ctx {
  259. close(ka.chs[i])
  260. ka.ctxs = append(ka.ctxs[:i], ka.ctxs[i+1:]...)
  261. ka.chs = append(ka.chs[:i], ka.chs[i+1:]...)
  262. break
  263. }
  264. }
  265. // remove if no one more listeners
  266. if len(ka.chs) == 0 {
  267. delete(l.keepAlives, id)
  268. }
  269. }
  270. func (l *lessor) keepAliveOnce(ctx context.Context, id LeaseID) (*LeaseKeepAliveResponse, error) {
  271. cctx, cancel := context.WithCancel(ctx)
  272. defer cancel()
  273. stream, err := l.remote.LeaseKeepAlive(cctx, grpc.FailFast(false))
  274. if err != nil {
  275. return nil, toErr(ctx, err)
  276. }
  277. err = stream.Send(&pb.LeaseKeepAliveRequest{ID: int64(id)})
  278. if err != nil {
  279. return nil, toErr(ctx, err)
  280. }
  281. resp, rerr := stream.Recv()
  282. if rerr != nil {
  283. return nil, toErr(ctx, rerr)
  284. }
  285. karesp := &LeaseKeepAliveResponse{
  286. ResponseHeader: resp.GetHeader(),
  287. ID: LeaseID(resp.ID),
  288. TTL: resp.TTL,
  289. }
  290. return karesp, nil
  291. }
  292. func (l *lessor) recvKeepAliveLoop() (gerr error) {
  293. defer func() {
  294. l.mu.Lock()
  295. close(l.donec)
  296. l.loopErr = gerr
  297. for _, ka := range l.keepAlives {
  298. ka.Close()
  299. }
  300. l.keepAlives = make(map[LeaseID]*keepAlive)
  301. l.mu.Unlock()
  302. }()
  303. stream, serr := l.resetRecv()
  304. for serr == nil {
  305. resp, err := stream.Recv()
  306. if err != nil {
  307. if isHaltErr(l.stopCtx, err) {
  308. return err
  309. }
  310. stream, serr = l.resetRecv()
  311. continue
  312. }
  313. l.recvKeepAlive(resp)
  314. }
  315. return serr
  316. }
  317. // resetRecv opens a new lease stream and starts sending LeaseKeepAliveRequests
  318. func (l *lessor) resetRecv() (pb.Lease_LeaseKeepAliveClient, error) {
  319. sctx, cancel := context.WithCancel(l.stopCtx)
  320. stream, err := l.remote.LeaseKeepAlive(sctx, grpc.FailFast(false))
  321. if err = toErr(sctx, err); err != nil {
  322. cancel()
  323. return nil, err
  324. }
  325. l.mu.Lock()
  326. defer l.mu.Unlock()
  327. if l.stream != nil && l.streamCancel != nil {
  328. l.stream.CloseSend()
  329. l.streamCancel()
  330. }
  331. l.streamCancel = cancel
  332. l.stream = stream
  333. go l.sendKeepAliveLoop(stream)
  334. return stream, nil
  335. }
  336. // recvKeepAlive updates a lease based on its LeaseKeepAliveResponse
  337. func (l *lessor) recvKeepAlive(resp *pb.LeaseKeepAliveResponse) {
  338. karesp := &LeaseKeepAliveResponse{
  339. ResponseHeader: resp.GetHeader(),
  340. ID: LeaseID(resp.ID),
  341. TTL: resp.TTL,
  342. }
  343. l.mu.Lock()
  344. defer l.mu.Unlock()
  345. ka, ok := l.keepAlives[karesp.ID]
  346. if !ok {
  347. return
  348. }
  349. if karesp.TTL <= 0 {
  350. // lease expired; close all keep alive channels
  351. delete(l.keepAlives, karesp.ID)
  352. ka.Close()
  353. return
  354. }
  355. // send update to all channels
  356. nextKeepAlive := time.Now().Add(1 + time.Duration(karesp.TTL/3)*time.Second)
  357. ka.deadline = time.Now().Add(time.Duration(karesp.TTL) * time.Second)
  358. for _, ch := range ka.chs {
  359. select {
  360. case ch <- karesp:
  361. ka.nextKeepAlive = nextKeepAlive
  362. default:
  363. }
  364. }
  365. }
  366. // deadlineLoop reaps any keep alive channels that have not received a response
  367. // within the lease TTL
  368. func (l *lessor) deadlineLoop() {
  369. for {
  370. select {
  371. case <-time.After(time.Second):
  372. case <-l.donec:
  373. return
  374. }
  375. now := time.Now()
  376. l.mu.Lock()
  377. for id, ka := range l.keepAlives {
  378. if ka.deadline.Before(now) {
  379. // waited too long for response; lease may be expired
  380. ka.Close()
  381. delete(l.keepAlives, id)
  382. }
  383. }
  384. l.mu.Unlock()
  385. }
  386. }
  387. // sendKeepAliveLoop sends LeaseKeepAliveRequests for the lifetime of a lease stream
  388. func (l *lessor) sendKeepAliveLoop(stream pb.Lease_LeaseKeepAliveClient) {
  389. for {
  390. select {
  391. case <-time.After(500 * time.Millisecond):
  392. case <-stream.Context().Done():
  393. return
  394. case <-l.donec:
  395. return
  396. case <-l.stopCtx.Done():
  397. return
  398. }
  399. var tosend []LeaseID
  400. now := time.Now()
  401. l.mu.Lock()
  402. for id, ka := range l.keepAlives {
  403. if ka.nextKeepAlive.Before(now) {
  404. tosend = append(tosend, id)
  405. }
  406. }
  407. l.mu.Unlock()
  408. for _, id := range tosend {
  409. r := &pb.LeaseKeepAliveRequest{ID: int64(id)}
  410. if err := stream.Send(r); err != nil {
  411. // TODO do something with this error?
  412. return
  413. }
  414. }
  415. }
  416. }
  417. func (ka *keepAlive) Close() {
  418. close(ka.donec)
  419. for _, ch := range ka.chs {
  420. close(ch)
  421. }
  422. }
  423. // cancelWhenStop calls cancel when the given stopc fires. It returns a done chan. done
  424. // should be closed when the work is finished. When done fires, cancelWhenStop will release
  425. // its internal resource.
  426. func cancelWhenStop(cancel context.CancelFunc, stopc <-chan struct{}) chan<- struct{} {
  427. done := make(chan struct{}, 1)
  428. go func() {
  429. select {
  430. case <-stopc:
  431. case <-done:
  432. }
  433. cancel()
  434. }()
  435. return done
  436. }