lease.go 13 KB

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