lease.go 14 KB

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