lease.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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. "google.golang.org/grpc/metadata"
  23. )
  24. type (
  25. LeaseRevokeResponse pb.LeaseRevokeResponse
  26. LeaseID int64
  27. )
  28. // LeaseGrantResponse is used to convert the protobuf grant response.
  29. type LeaseGrantResponse struct {
  30. *pb.ResponseHeader
  31. ID LeaseID
  32. TTL int64
  33. Error string
  34. }
  35. // LeaseKeepAliveResponse is used to convert the protobuf keepalive response.
  36. type LeaseKeepAliveResponse struct {
  37. *pb.ResponseHeader
  38. ID LeaseID
  39. TTL int64
  40. Err error
  41. Deadline time.Time
  42. }
  43. // LeaseTimeToLiveResponse is used to convert the protobuf lease timetolive response.
  44. type LeaseTimeToLiveResponse struct {
  45. *pb.ResponseHeader
  46. ID LeaseID `json:"id"`
  47. // TTL is the remaining TTL in seconds for the lease; the lease will expire in under TTL+1 seconds.
  48. TTL int64 `json:"ttl"`
  49. // GrantedTTL is the initial granted time in seconds upon lease creation/renewal.
  50. GrantedTTL int64 `json:"granted-ttl"`
  51. // Keys is the list of keys attached to this lease.
  52. Keys [][]byte `json:"keys"`
  53. }
  54. const (
  55. // defaultTTL is the assumed lease TTL used for the first keepalive
  56. // deadline before the actual TTL is known to the client.
  57. defaultTTL = 5 * time.Second
  58. // a small buffer to store unsent lease responses.
  59. leaseResponseChSize = 16
  60. // NoLease is a lease ID for the absence of a lease.
  61. NoLease LeaseID = 0
  62. // retryConnWait is how long to wait before retrying on a lost leader
  63. // or keep alive loop failure.
  64. retryConnWait = 500 * time.Millisecond
  65. )
  66. type LeaseKeepAliveChan <-chan LeaseKeepAliveResponse
  67. type Lease interface {
  68. // Grant creates a new lease.
  69. Grant(ctx context.Context, ttl int64) (*LeaseGrantResponse, error)
  70. // Revoke revokes the given lease.
  71. Revoke(ctx context.Context, id LeaseID) (*LeaseRevokeResponse, error)
  72. // TimeToLive retrieves the lease information of the given lease ID.
  73. TimeToLive(ctx context.Context, id LeaseID, opts ...LeaseOption) (*LeaseTimeToLiveResponse, error)
  74. // KeepAlive keeps the given lease alive forever. If the keepalive response posted to
  75. // the channel is not consumed immediately, the lease client will continue sending keep alive requests
  76. // to the etcd server at least every second until latest response is consumed.
  77. //
  78. // The KeepAlive channel closes if the underlying keep alive stream is interrupted in some
  79. // way the client cannot handle itself; the error will be posted in the last keep
  80. // alive message before closing. If there is no keepalive response within the
  81. // lease's time-out, the channel will close with no error. In most cases calling
  82. // KeepAlive again will re-establish keepalives with the target lease if it has not
  83. // expired.
  84. KeepAlive(ctx context.Context, id LeaseID) LeaseKeepAliveChan
  85. // KeepAliveOnce renews the lease once. The response corresponds to the
  86. // first message from calling KeepAlive. If the response has a recoverable
  87. // error, KeepAliveOnce will retry the RPC with a new keep alive message.
  88. //
  89. // In most of the cases, Keepalive should be used instead of KeepAliveOnce.
  90. KeepAliveOnce(ctx context.Context, id LeaseID) LeaseKeepAliveResponse
  91. // Close releases all resources Lease keeps for efficient communication
  92. // with the etcd server.
  93. Close() error
  94. }
  95. type lessor struct {
  96. mu sync.Mutex // guards all fields
  97. // donec is closed when all goroutines are torn down from Close()
  98. donec chan struct{}
  99. remote pb.LeaseClient
  100. stream pb.Lease_LeaseKeepAliveClient
  101. streamCancel context.CancelFunc
  102. stopCtx context.Context
  103. stopCancel context.CancelFunc
  104. keepAlives map[LeaseID]*keepAlive
  105. // firstKeepAliveTimeout is the timeout for the first keepalive request
  106. // before the actual TTL is known to the lease client
  107. firstKeepAliveTimeout time.Duration
  108. // firstKeepAliveOnce ensures stream starts after first KeepAlive call.
  109. firstKeepAliveOnce sync.Once
  110. }
  111. // keepAlive multiplexes a keepalive for a lease over multiple channels
  112. type keepAlive struct {
  113. chs []chan<- LeaseKeepAliveResponse
  114. ctxs []context.Context
  115. // deadline is the time the keep alive channels close if no response
  116. deadline time.Time
  117. // nextKeepAlive is when to send the next keep alive message
  118. nextKeepAlive time.Time
  119. // donec is closed on lease revoke, expiration, or cancel.
  120. donec chan struct{}
  121. }
  122. func NewLease(c *Client) Lease {
  123. return NewLeaseFromLeaseClient(RetryLeaseClient(c), c.cfg.DialTimeout+time.Second)
  124. }
  125. func NewLeaseFromLeaseClient(remote pb.LeaseClient, keepAliveTimeout time.Duration) Lease {
  126. l := &lessor{
  127. donec: make(chan struct{}),
  128. keepAlives: make(map[LeaseID]*keepAlive),
  129. remote: remote,
  130. firstKeepAliveTimeout: keepAliveTimeout,
  131. }
  132. if l.firstKeepAliveTimeout == time.Second {
  133. l.firstKeepAliveTimeout = defaultTTL
  134. }
  135. reqLeaderCtx := WithRequireLeader(context.Background())
  136. l.stopCtx, l.stopCancel = context.WithCancel(reqLeaderCtx)
  137. return l
  138. }
  139. func (l *lessor) Grant(ctx context.Context, ttl int64) (*LeaseGrantResponse, error) {
  140. for {
  141. r := &pb.LeaseGrantRequest{TTL: ttl}
  142. resp, err := l.remote.LeaseGrant(ctx, r)
  143. if err == nil {
  144. gresp := &LeaseGrantResponse{
  145. ResponseHeader: resp.GetHeader(),
  146. ID: LeaseID(resp.ID),
  147. TTL: resp.TTL,
  148. Error: resp.Error,
  149. }
  150. return gresp, nil
  151. }
  152. if isHaltErr(ctx, err) {
  153. return nil, toErr(ctx, err)
  154. }
  155. }
  156. }
  157. func (l *lessor) Revoke(ctx context.Context, id LeaseID) (*LeaseRevokeResponse, error) {
  158. for {
  159. r := &pb.LeaseRevokeRequest{ID: int64(id)}
  160. resp, err := l.remote.LeaseRevoke(ctx, r)
  161. if err == nil {
  162. return (*LeaseRevokeResponse)(resp), nil
  163. }
  164. if isHaltErr(ctx, err) {
  165. return nil, toErr(ctx, err)
  166. }
  167. }
  168. }
  169. func (l *lessor) TimeToLive(ctx context.Context, id LeaseID, opts ...LeaseOption) (*LeaseTimeToLiveResponse, error) {
  170. for {
  171. r := toLeaseTimeToLiveRequest(id, opts...)
  172. resp, err := l.remote.LeaseTimeToLive(ctx, r, grpc.FailFast(false))
  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. if isHaltErr(ctx, err) {
  184. return nil, toErr(ctx, err)
  185. }
  186. }
  187. }
  188. func (l *lessor) KeepAlive(ctx context.Context, id LeaseID) LeaseKeepAliveChan {
  189. ch := make(chan LeaseKeepAliveResponse, leaseResponseChSize)
  190. l.mu.Lock()
  191. // ensure that recvKeepAliveLoop is still running
  192. select {
  193. case <-l.donec:
  194. close(ch)
  195. return ch
  196. default:
  197. }
  198. ka, ok := l.keepAlives[id]
  199. if !ok {
  200. // create fresh keep alive
  201. ka = &keepAlive{
  202. chs: []chan<- LeaseKeepAliveResponse{ch},
  203. ctxs: []context.Context{ctx},
  204. deadline: time.Now().Add(l.firstKeepAliveTimeout),
  205. nextKeepAlive: time.Now(),
  206. donec: make(chan struct{}),
  207. }
  208. l.keepAlives[id] = ka
  209. } else {
  210. // add channel and context to existing keep alive
  211. ka.ctxs = append(ka.ctxs, ctx)
  212. ka.chs = append(ka.chs, ch)
  213. }
  214. l.mu.Unlock()
  215. go l.keepAliveCtxCloser(id, ctx, ka.donec)
  216. l.firstKeepAliveOnce.Do(func() {
  217. go func() {
  218. defer func() {
  219. l.mu.Lock()
  220. for _, ka := range l.keepAlives {
  221. ka.Close(nil)
  222. }
  223. close(l.donec)
  224. l.mu.Unlock()
  225. }()
  226. for l.stopCtx.Err() == nil {
  227. err := l.recvKeepAliveLoop()
  228. if err == context.Canceled {
  229. // canceled by user; no error like WatchChan
  230. err = nil
  231. }
  232. l.mu.Lock()
  233. for _, ka := range l.keepAlives {
  234. ka.Close(err)
  235. }
  236. l.keepAlives = make(map[LeaseID]*keepAlive)
  237. l.mu.Unlock()
  238. select {
  239. case <-l.stopCtx.Done():
  240. case <-time.After(retryConnWait):
  241. }
  242. }
  243. }()
  244. go l.deadlineLoop()
  245. })
  246. return ch
  247. }
  248. func (l *lessor) KeepAliveOnce(ctx context.Context, id LeaseID) LeaseKeepAliveResponse {
  249. for {
  250. resp := l.keepAliveOnce(ctx, id)
  251. if resp.Err == nil {
  252. if resp.TTL <= 0 {
  253. resp.Err = rpctypes.ErrLeaseNotFound
  254. }
  255. return resp
  256. }
  257. if isHaltErr(ctx, resp.Err) {
  258. return resp
  259. }
  260. }
  261. }
  262. func (l *lessor) Close() error {
  263. l.stopCancel()
  264. // close for synchronous teardown if stream goroutines never launched
  265. l.firstKeepAliveOnce.Do(func() { close(l.donec) })
  266. <-l.donec
  267. return nil
  268. }
  269. func (l *lessor) keepAliveCtxCloser(id LeaseID, ctx context.Context, donec <-chan struct{}) {
  270. select {
  271. case <-donec:
  272. return
  273. case <-l.donec:
  274. return
  275. case <-ctx.Done():
  276. }
  277. l.mu.Lock()
  278. defer l.mu.Unlock()
  279. ka, ok := l.keepAlives[id]
  280. if !ok {
  281. return
  282. }
  283. // close channel and remove context if still associated with keep alive
  284. for i, c := range ka.ctxs {
  285. if c == ctx {
  286. close(ka.chs[i])
  287. ka.ctxs = append(ka.ctxs[:i], ka.ctxs[i+1:]...)
  288. ka.chs = append(ka.chs[:i], ka.chs[i+1:]...)
  289. break
  290. }
  291. }
  292. // remove if no one more listeners
  293. if len(ka.chs) == 0 {
  294. delete(l.keepAlives, id)
  295. }
  296. }
  297. // closeRequireLeader scans all keep alives for ctxs that have require leader
  298. // and closes the associated channels.
  299. func (l *lessor) closeRequireLeader() {
  300. l.mu.Lock()
  301. defer l.mu.Unlock()
  302. for _, ka := range l.keepAlives {
  303. reqIdxs := 0
  304. // find all required leader channels, close, mark as nil
  305. for i, ctx := range ka.ctxs {
  306. md, ok := metadata.FromContext(ctx)
  307. if !ok {
  308. continue
  309. }
  310. ks := md[rpctypes.MetadataRequireLeaderKey]
  311. if len(ks) < 1 || ks[0] != rpctypes.MetadataHasLeader {
  312. continue
  313. }
  314. close(ka.chs[i])
  315. ka.chs[i] = nil
  316. reqIdxs++
  317. }
  318. if reqIdxs == 0 {
  319. continue
  320. }
  321. // remove all channels that required a leader from keepalive
  322. newChs := make([]chan<- LeaseKeepAliveResponse, len(ka.chs)-reqIdxs)
  323. newCtxs := make([]context.Context, len(newChs))
  324. newIdx := 0
  325. for i := range ka.chs {
  326. if ka.chs[i] == nil {
  327. continue
  328. }
  329. newChs[newIdx], newCtxs[newIdx] = ka.chs[i], ka.ctxs[newIdx]
  330. newIdx++
  331. }
  332. ka.chs, ka.ctxs = newChs, newCtxs
  333. }
  334. }
  335. func (l *lessor) keepAliveOnce(ctx context.Context, id LeaseID) LeaseKeepAliveResponse {
  336. cctx, cancel := context.WithCancel(ctx)
  337. defer cancel()
  338. stream, err := l.remote.LeaseKeepAlive(cctx, grpc.FailFast(false))
  339. if err != nil {
  340. return LeaseKeepAliveResponse{Err: toErr(ctx, err)}
  341. }
  342. err = stream.Send(&pb.LeaseKeepAliveRequest{ID: int64(id)})
  343. if err != nil {
  344. return LeaseKeepAliveResponse{Err: toErr(ctx, err)}
  345. }
  346. resp, rerr := stream.Recv()
  347. if rerr != nil {
  348. return LeaseKeepAliveResponse{Err: toErr(ctx, rerr)}
  349. }
  350. return LeaseKeepAliveResponse{
  351. ResponseHeader: resp.GetHeader(),
  352. ID: LeaseID(resp.ID),
  353. TTL: resp.TTL,
  354. Deadline: time.Now().Add(time.Duration(resp.TTL) * time.Second),
  355. }
  356. }
  357. func (l *lessor) recvKeepAliveLoop() (gerr error) {
  358. stream, serr := l.resetRecv()
  359. for serr == nil {
  360. resp, err := stream.Recv()
  361. if err == nil {
  362. l.recvKeepAlive(resp)
  363. continue
  364. }
  365. err = toErr(l.stopCtx, err)
  366. if err == rpctypes.ErrNoLeader {
  367. l.closeRequireLeader()
  368. select {
  369. case <-time.After(retryConnWait):
  370. case <-l.stopCtx.Done():
  371. return err
  372. }
  373. } else if isHaltErr(l.stopCtx, err) {
  374. return err
  375. }
  376. stream, serr = l.resetRecv()
  377. }
  378. return serr
  379. }
  380. // resetRecv opens a new lease stream and starts sending LeaseKeepAliveRequests
  381. func (l *lessor) resetRecv() (pb.Lease_LeaseKeepAliveClient, error) {
  382. sctx, cancel := context.WithCancel(l.stopCtx)
  383. stream, err := l.remote.LeaseKeepAlive(sctx, grpc.FailFast(false))
  384. if err = toErr(sctx, err); err != nil {
  385. cancel()
  386. return nil, err
  387. }
  388. l.mu.Lock()
  389. defer l.mu.Unlock()
  390. if l.stream != nil && l.streamCancel != nil {
  391. l.streamCancel()
  392. }
  393. l.streamCancel = cancel
  394. l.stream = stream
  395. go l.sendKeepAliveLoop(stream)
  396. return stream, nil
  397. }
  398. // recvKeepAlive updates a lease based on its LeaseKeepAliveResponse
  399. func (l *lessor) recvKeepAlive(resp *pb.LeaseKeepAliveResponse) {
  400. karesp := &LeaseKeepAliveResponse{
  401. ResponseHeader: resp.GetHeader(),
  402. ID: LeaseID(resp.ID),
  403. TTL: resp.TTL,
  404. Deadline: time.Now().Add(time.Duration(resp.TTL) * time.Second),
  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(nil)
  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(nil)
  444. delete(l.keepAlives, id)
  445. }
  446. }
  447. l.mu.Unlock()
  448. }
  449. }
  450. // sendKeepAliveLoop sends LeaseKeepAliveRequests for the lifetime of a lease 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(err error) {
  481. close(ka.donec)
  482. for _, ch := range ka.chs {
  483. if err != nil {
  484. // try to post error if buffer space available
  485. select {
  486. case ch <- LeaseKeepAliveResponse{Err: err}:
  487. default:
  488. }
  489. }
  490. close(ch)
  491. }
  492. // so keepAliveCtxClose doesn't double-close ka.chs
  493. ka.chs, ka.ctxs = nil, nil
  494. }