lease.go 15 KB

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