lease.go 12 KB

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