lease.go 12 KB

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