lease.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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. "context"
  17. "sync"
  18. "time"
  19. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  20. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  21. "google.golang.org/grpc"
  22. "google.golang.org/grpc/metadata"
  23. )
  24. type (
  25. LeaseRevokeResponse pb.LeaseRevokeResponse
  26. LeaseID int64
  27. )
  28. // LeaseGrantResponse wraps the protobuf message LeaseGrantResponse.
  29. type LeaseGrantResponse struct {
  30. *pb.ResponseHeader
  31. ID LeaseID
  32. TTL int64
  33. Error string
  34. }
  35. // LeaseKeepAliveResponse wraps the protobuf message LeaseKeepAliveResponse.
  36. type LeaseKeepAliveResponse struct {
  37. *pb.ResponseHeader
  38. ID LeaseID
  39. TTL int64
  40. }
  41. // LeaseTimeToLiveResponse wraps the protobuf message LeaseTimeToLiveResponse.
  42. type LeaseTimeToLiveResponse struct {
  43. *pb.ResponseHeader
  44. ID LeaseID `json:"id"`
  45. // TTL is the remaining TTL in seconds for the lease; the lease will expire in under TTL+1 seconds. Expired lease will return -1.
  46. TTL int64 `json:"ttl"`
  47. // GrantedTTL is the initial granted time in seconds upon lease creation/renewal.
  48. GrantedTTL int64 `json:"granted-ttl"`
  49. // Keys is the list of keys attached to this lease.
  50. Keys [][]byte `json:"keys"`
  51. }
  52. // LeaseStatus represents a lease status.
  53. type LeaseStatus struct {
  54. ID LeaseID `json:"id"`
  55. // TODO: TTL int64
  56. }
  57. // LeaseLeasesResponse wraps the protobuf message LeaseLeasesResponse.
  58. type LeaseLeasesResponse struct {
  59. *pb.ResponseHeader
  60. Leases []LeaseStatus `json:"leases"`
  61. }
  62. const (
  63. // defaultTTL is the assumed lease TTL used for the first keepalive
  64. // deadline before the actual TTL is known to the client.
  65. defaultTTL = 5 * time.Second
  66. // a small buffer to store unsent lease responses.
  67. leaseResponseChSize = 16
  68. // NoLease is a lease ID for the absence of a lease.
  69. NoLease LeaseID = 0
  70. // retryConnWait is how long to wait before retrying request due to an error
  71. retryConnWait = 500 * time.Millisecond
  72. )
  73. // ErrKeepAliveHalted is returned if client keep alive loop halts with an unexpected error.
  74. //
  75. // This usually means that automatic lease renewal via KeepAlive is broken, but KeepAliveOnce will still work as expected.
  76. type ErrKeepAliveHalted struct {
  77. Reason error
  78. }
  79. func (e ErrKeepAliveHalted) Error() string {
  80. s := "etcdclient: leases keep alive halted"
  81. if e.Reason != nil {
  82. s += ": " + e.Reason.Error()
  83. }
  84. return s
  85. }
  86. type Lease interface {
  87. // Grant creates a new lease.
  88. Grant(ctx context.Context, ttl int64) (*LeaseGrantResponse, error)
  89. // Revoke revokes the given lease.
  90. Revoke(ctx context.Context, id LeaseID) (*LeaseRevokeResponse, error)
  91. // TimeToLive retrieves the lease information of the given lease ID.
  92. TimeToLive(ctx context.Context, id LeaseID, opts ...LeaseOption) (*LeaseTimeToLiveResponse, error)
  93. // Leases retrieves all leases.
  94. Leases(ctx context.Context) (*LeaseLeasesResponse, error)
  95. // KeepAlive keeps the given lease alive forever. If the keepalive response
  96. // posted to the channel is not consumed immediately, the lease client will
  97. // continue sending keep alive requests to the etcd server at least every
  98. // second until latest response is consumed.
  99. //
  100. // The returned "LeaseKeepAliveResponse" channel closes if underlying keep
  101. // alive stream is interrupted in some way the client cannot handle itself;
  102. // given context "ctx" is canceled or timed out. "LeaseKeepAliveResponse"
  103. // from this closed channel is nil.
  104. //
  105. // If client keep alive loop halts with an unexpected error (e.g. "etcdserver:
  106. // no leader") or canceled by the caller (e.g. context.Canceled), the error
  107. // is returned. Otherwise, it retries.
  108. //
  109. // TODO(v4.0): post errors to last keep alive message before closing
  110. // (see https://github.com/coreos/etcd/pull/7866)
  111. KeepAlive(ctx context.Context, id LeaseID) (<-chan *LeaseKeepAliveResponse, error)
  112. // KeepAliveOnce renews the lease once. The response corresponds to the
  113. // first message from calling KeepAlive. If the response has a recoverable
  114. // error, KeepAliveOnce will retry the RPC with a new keep alive message.
  115. //
  116. // In most of the cases, Keepalive should be used instead of KeepAliveOnce.
  117. KeepAliveOnce(ctx context.Context, id LeaseID) (*LeaseKeepAliveResponse, error)
  118. // Close releases all resources Lease keeps for efficient communication
  119. // with the etcd server.
  120. Close() error
  121. }
  122. type lessor struct {
  123. mu sync.Mutex // guards all fields
  124. // donec is closed and loopErr is set when recvKeepAliveLoop stops
  125. donec chan struct{}
  126. loopErr error
  127. remote pb.LeaseClient
  128. stream pb.Lease_LeaseKeepAliveClient
  129. streamCancel context.CancelFunc
  130. stopCtx context.Context
  131. stopCancel context.CancelFunc
  132. keepAlives map[LeaseID]*keepAlive
  133. // firstKeepAliveTimeout is the timeout for the first keepalive request
  134. // before the actual TTL is known to the lease client
  135. firstKeepAliveTimeout time.Duration
  136. // firstKeepAliveOnce ensures stream starts after first KeepAlive call.
  137. firstKeepAliveOnce sync.Once
  138. callOpts []grpc.CallOption
  139. }
  140. // keepAlive multiplexes a keepalive for a lease over multiple channels
  141. type keepAlive struct {
  142. chs []chan<- *LeaseKeepAliveResponse
  143. ctxs []context.Context
  144. // deadline is the time the keep alive channels close if no response
  145. deadline time.Time
  146. // nextKeepAlive is when to send the next keep alive message
  147. nextKeepAlive time.Time
  148. // donec is closed on lease revoke, expiration, or cancel.
  149. donec chan struct{}
  150. }
  151. func NewLease(c *Client) Lease {
  152. return NewLeaseFromLeaseClient(RetryLeaseClient(c), c, c.cfg.DialTimeout+time.Second)
  153. }
  154. func NewLeaseFromLeaseClient(remote pb.LeaseClient, c *Client, keepAliveTimeout time.Duration) Lease {
  155. l := &lessor{
  156. donec: make(chan struct{}),
  157. keepAlives: make(map[LeaseID]*keepAlive),
  158. remote: remote,
  159. firstKeepAliveTimeout: keepAliveTimeout,
  160. }
  161. if l.firstKeepAliveTimeout == time.Second {
  162. l.firstKeepAliveTimeout = defaultTTL
  163. }
  164. if c != nil {
  165. l.callOpts = c.callOpts
  166. }
  167. reqLeaderCtx := WithRequireLeader(context.Background())
  168. l.stopCtx, l.stopCancel = context.WithCancel(reqLeaderCtx)
  169. return l
  170. }
  171. func (l *lessor) Grant(ctx context.Context, ttl int64) (*LeaseGrantResponse, error) {
  172. r := &pb.LeaseGrantRequest{TTL: ttl}
  173. resp, err := l.remote.LeaseGrant(ctx, r, l.callOpts...)
  174. if err == nil {
  175. gresp := &LeaseGrantResponse{
  176. ResponseHeader: resp.GetHeader(),
  177. ID: LeaseID(resp.ID),
  178. TTL: resp.TTL,
  179. Error: resp.Error,
  180. }
  181. return gresp, nil
  182. }
  183. return nil, toErr(ctx, err)
  184. }
  185. func (l *lessor) Revoke(ctx context.Context, id LeaseID) (*LeaseRevokeResponse, error) {
  186. r := &pb.LeaseRevokeRequest{ID: int64(id)}
  187. resp, err := l.remote.LeaseRevoke(ctx, r, l.callOpts...)
  188. if err == nil {
  189. return (*LeaseRevokeResponse)(resp), nil
  190. }
  191. return nil, toErr(ctx, err)
  192. }
  193. func (l *lessor) TimeToLive(ctx context.Context, id LeaseID, opts ...LeaseOption) (*LeaseTimeToLiveResponse, error) {
  194. r := toLeaseTimeToLiveRequest(id, opts...)
  195. resp, err := l.remote.LeaseTimeToLive(ctx, r, l.callOpts...)
  196. if err == nil {
  197. gresp := &LeaseTimeToLiveResponse{
  198. ResponseHeader: resp.GetHeader(),
  199. ID: LeaseID(resp.ID),
  200. TTL: resp.TTL,
  201. GrantedTTL: resp.GrantedTTL,
  202. Keys: resp.Keys,
  203. }
  204. return gresp, nil
  205. }
  206. return nil, toErr(ctx, err)
  207. }
  208. func (l *lessor) Leases(ctx context.Context) (*LeaseLeasesResponse, error) {
  209. resp, err := l.remote.LeaseLeases(ctx, &pb.LeaseLeasesRequest{}, l.callOpts...)
  210. if err == nil {
  211. leases := make([]LeaseStatus, len(resp.Leases))
  212. for i := range resp.Leases {
  213. leases[i] = LeaseStatus{ID: LeaseID(resp.Leases[i].ID)}
  214. }
  215. return &LeaseLeasesResponse{ResponseHeader: resp.GetHeader(), Leases: leases}, nil
  216. }
  217. return nil, toErr(ctx, err)
  218. }
  219. func (l *lessor) KeepAlive(ctx context.Context, id LeaseID) (<-chan *LeaseKeepAliveResponse, error) {
  220. ch := make(chan *LeaseKeepAliveResponse, leaseResponseChSize)
  221. l.mu.Lock()
  222. // ensure that recvKeepAliveLoop is still running
  223. select {
  224. case <-l.donec:
  225. err := l.loopErr
  226. l.mu.Unlock()
  227. close(ch)
  228. return ch, ErrKeepAliveHalted{Reason: err}
  229. default:
  230. }
  231. ka, ok := l.keepAlives[id]
  232. if !ok {
  233. // create fresh keep alive
  234. ka = &keepAlive{
  235. chs: []chan<- *LeaseKeepAliveResponse{ch},
  236. ctxs: []context.Context{ctx},
  237. deadline: time.Now().Add(l.firstKeepAliveTimeout),
  238. nextKeepAlive: time.Now(),
  239. donec: make(chan struct{}),
  240. }
  241. l.keepAlives[id] = ka
  242. } else {
  243. // add channel and context to existing keep alive
  244. ka.ctxs = append(ka.ctxs, ctx)
  245. ka.chs = append(ka.chs, ch)
  246. }
  247. l.mu.Unlock()
  248. go l.keepAliveCtxCloser(id, ctx, ka.donec)
  249. l.firstKeepAliveOnce.Do(func() {
  250. go l.recvKeepAliveLoop()
  251. go l.deadlineLoop()
  252. })
  253. return ch, nil
  254. }
  255. func (l *lessor) KeepAliveOnce(ctx context.Context, id LeaseID) (*LeaseKeepAliveResponse, error) {
  256. for {
  257. resp, err := l.keepAliveOnce(ctx, id)
  258. if err == nil {
  259. if resp.TTL <= 0 {
  260. err = rpctypes.ErrLeaseNotFound
  261. }
  262. return resp, err
  263. }
  264. if isHaltErr(ctx, err) {
  265. return nil, toErr(ctx, err)
  266. }
  267. }
  268. }
  269. func (l *lessor) Close() error {
  270. l.stopCancel()
  271. // close for synchronous teardown if stream goroutines never launched
  272. l.firstKeepAliveOnce.Do(func() { close(l.donec) })
  273. <-l.donec
  274. return nil
  275. }
  276. func (l *lessor) keepAliveCtxCloser(id LeaseID, ctx context.Context, donec <-chan struct{}) {
  277. select {
  278. case <-donec:
  279. return
  280. case <-l.donec:
  281. return
  282. case <-ctx.Done():
  283. }
  284. l.mu.Lock()
  285. defer l.mu.Unlock()
  286. ka, ok := l.keepAlives[id]
  287. if !ok {
  288. return
  289. }
  290. // close channel and remove context if still associated with keep alive
  291. for i, c := range ka.ctxs {
  292. if c == ctx {
  293. close(ka.chs[i])
  294. ka.ctxs = append(ka.ctxs[:i], ka.ctxs[i+1:]...)
  295. ka.chs = append(ka.chs[:i], ka.chs[i+1:]...)
  296. break
  297. }
  298. }
  299. // remove if no one more listeners
  300. if len(ka.chs) == 0 {
  301. delete(l.keepAlives, id)
  302. }
  303. }
  304. // closeRequireLeader scans keepAlives for ctxs that have require leader
  305. // and closes the associated channels.
  306. func (l *lessor) closeRequireLeader() {
  307. l.mu.Lock()
  308. defer l.mu.Unlock()
  309. for _, ka := range l.keepAlives {
  310. reqIdxs := 0
  311. // find all required leader channels, close, mark as nil
  312. for i, ctx := range ka.ctxs {
  313. md, ok := metadata.FromOutgoingContext(ctx)
  314. if !ok {
  315. continue
  316. }
  317. ks := md[rpctypes.MetadataRequireLeaderKey]
  318. if len(ks) < 1 || ks[0] != rpctypes.MetadataHasLeader {
  319. continue
  320. }
  321. close(ka.chs[i])
  322. ka.chs[i] = nil
  323. reqIdxs++
  324. }
  325. if reqIdxs == 0 {
  326. continue
  327. }
  328. // remove all channels that required a leader from keepalive
  329. newChs := make([]chan<- *LeaseKeepAliveResponse, len(ka.chs)-reqIdxs)
  330. newCtxs := make([]context.Context, len(newChs))
  331. newIdx := 0
  332. for i := range ka.chs {
  333. if ka.chs[i] == nil {
  334. continue
  335. }
  336. newChs[newIdx], newCtxs[newIdx] = ka.chs[i], ka.ctxs[newIdx]
  337. newIdx++
  338. }
  339. ka.chs, ka.ctxs = newChs, newCtxs
  340. }
  341. }
  342. func (l *lessor) keepAliveOnce(ctx context.Context, id LeaseID) (*LeaseKeepAliveResponse, error) {
  343. cctx, cancel := context.WithCancel(ctx)
  344. defer cancel()
  345. stream, err := l.remote.LeaseKeepAlive(cctx, l.callOpts...)
  346. if err != nil {
  347. return nil, toErr(ctx, err)
  348. }
  349. err = stream.Send(&pb.LeaseKeepAliveRequest{ID: int64(id)})
  350. if err != nil {
  351. return nil, toErr(ctx, err)
  352. }
  353. resp, rerr := stream.Recv()
  354. if rerr != nil {
  355. return nil, toErr(ctx, rerr)
  356. }
  357. karesp := &LeaseKeepAliveResponse{
  358. ResponseHeader: resp.GetHeader(),
  359. ID: LeaseID(resp.ID),
  360. TTL: resp.TTL,
  361. }
  362. return karesp, nil
  363. }
  364. func (l *lessor) recvKeepAliveLoop() (gerr error) {
  365. defer func() {
  366. l.mu.Lock()
  367. close(l.donec)
  368. l.loopErr = gerr
  369. for _, ka := range l.keepAlives {
  370. ka.close()
  371. }
  372. l.keepAlives = make(map[LeaseID]*keepAlive)
  373. l.mu.Unlock()
  374. }()
  375. for {
  376. stream, err := l.resetRecv()
  377. if err != nil {
  378. if canceledByCaller(l.stopCtx, err) {
  379. return err
  380. }
  381. } else {
  382. for {
  383. resp, err := stream.Recv()
  384. if err != nil {
  385. if canceledByCaller(l.stopCtx, err) {
  386. return err
  387. }
  388. if toErr(l.stopCtx, err) == rpctypes.ErrNoLeader {
  389. l.closeRequireLeader()
  390. }
  391. break
  392. }
  393. l.recvKeepAlive(resp)
  394. }
  395. }
  396. select {
  397. case <-time.After(retryConnWait):
  398. continue
  399. case <-l.stopCtx.Done():
  400. return l.stopCtx.Err()
  401. }
  402. }
  403. }
  404. // resetRecv opens a new lease stream and starts sending keep alive requests.
  405. func (l *lessor) resetRecv() (pb.Lease_LeaseKeepAliveClient, error) {
  406. sctx, cancel := context.WithCancel(l.stopCtx)
  407. stream, err := l.remote.LeaseKeepAlive(sctx, l.callOpts...)
  408. if err != nil {
  409. cancel()
  410. return nil, err
  411. }
  412. l.mu.Lock()
  413. defer l.mu.Unlock()
  414. if l.stream != nil && l.streamCancel != nil {
  415. l.streamCancel()
  416. }
  417. l.streamCancel = cancel
  418. l.stream = stream
  419. go l.sendKeepAliveLoop(stream)
  420. return stream, nil
  421. }
  422. // recvKeepAlive updates a lease based on its LeaseKeepAliveResponse
  423. func (l *lessor) recvKeepAlive(resp *pb.LeaseKeepAliveResponse) {
  424. karesp := &LeaseKeepAliveResponse{
  425. ResponseHeader: resp.GetHeader(),
  426. ID: LeaseID(resp.ID),
  427. TTL: resp.TTL,
  428. }
  429. l.mu.Lock()
  430. defer l.mu.Unlock()
  431. ka, ok := l.keepAlives[karesp.ID]
  432. if !ok {
  433. return
  434. }
  435. if karesp.TTL <= 0 {
  436. // lease expired; close all keep alive channels
  437. delete(l.keepAlives, karesp.ID)
  438. ka.close()
  439. return
  440. }
  441. // send update to all channels
  442. nextKeepAlive := time.Now().Add((time.Duration(karesp.TTL) * time.Second) / 3.0)
  443. ka.deadline = time.Now().Add(time.Duration(karesp.TTL) * time.Second)
  444. for _, ch := range ka.chs {
  445. select {
  446. case ch <- karesp:
  447. ka.nextKeepAlive = nextKeepAlive
  448. default:
  449. }
  450. }
  451. }
  452. // deadlineLoop reaps any keep alive channels that have not received a response
  453. // within the lease TTL
  454. func (l *lessor) deadlineLoop() {
  455. for {
  456. select {
  457. case <-time.After(time.Second):
  458. case <-l.donec:
  459. return
  460. }
  461. now := time.Now()
  462. l.mu.Lock()
  463. for id, ka := range l.keepAlives {
  464. if ka.deadline.Before(now) {
  465. // waited too long for response; lease may be expired
  466. ka.close()
  467. delete(l.keepAlives, id)
  468. }
  469. }
  470. l.mu.Unlock()
  471. }
  472. }
  473. // sendKeepAliveLoop sends keep alive requests for the lifetime of the given stream.
  474. func (l *lessor) sendKeepAliveLoop(stream pb.Lease_LeaseKeepAliveClient) {
  475. for {
  476. var tosend []LeaseID
  477. now := time.Now()
  478. l.mu.Lock()
  479. for id, ka := range l.keepAlives {
  480. if ka.nextKeepAlive.Before(now) {
  481. tosend = append(tosend, id)
  482. }
  483. }
  484. l.mu.Unlock()
  485. for _, id := range tosend {
  486. r := &pb.LeaseKeepAliveRequest{ID: int64(id)}
  487. if err := stream.Send(r); err != nil {
  488. // TODO do something with this error?
  489. return
  490. }
  491. }
  492. select {
  493. case <-time.After(500 * time.Millisecond):
  494. case <-stream.Context().Done():
  495. return
  496. case <-l.donec:
  497. return
  498. case <-l.stopCtx.Done():
  499. return
  500. }
  501. }
  502. }
  503. func (ka *keepAlive) close() {
  504. close(ka.donec)
  505. for _, ch := range ka.chs {
  506. close(ch)
  507. }
  508. }