lease.go 16 KB

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