lease.go 12 KB

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