lease.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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. 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. return l
  129. }
  130. func (l *lessor) Grant(ctx context.Context, ttl int64) (*LeaseGrantResponse, error) {
  131. for {
  132. r := &pb.LeaseGrantRequest{TTL: ttl}
  133. resp, err := l.remote.LeaseGrant(ctx, r)
  134. if err == nil {
  135. gresp := &LeaseGrantResponse{
  136. ResponseHeader: resp.GetHeader(),
  137. ID: LeaseID(resp.ID),
  138. TTL: resp.TTL,
  139. Error: resp.Error,
  140. }
  141. return gresp, nil
  142. }
  143. if isHaltErr(ctx, err) {
  144. return nil, toErr(ctx, err)
  145. }
  146. }
  147. }
  148. func (l *lessor) Revoke(ctx context.Context, id LeaseID) (*LeaseRevokeResponse, error) {
  149. for {
  150. r := &pb.LeaseRevokeRequest{ID: int64(id)}
  151. resp, err := l.remote.LeaseRevoke(ctx, r)
  152. if err == nil {
  153. return (*LeaseRevokeResponse)(resp), nil
  154. }
  155. if isHaltErr(ctx, err) {
  156. return nil, toErr(ctx, err)
  157. }
  158. }
  159. }
  160. func (l *lessor) TimeToLive(ctx context.Context, id LeaseID, opts ...LeaseOption) (*LeaseTimeToLiveResponse, error) {
  161. for {
  162. r := toLeaseTimeToLiveRequest(id, opts...)
  163. resp, err := l.remote.LeaseTimeToLive(ctx, r, grpc.FailFast(false))
  164. if err == nil {
  165. gresp := &LeaseTimeToLiveResponse{
  166. ResponseHeader: resp.GetHeader(),
  167. ID: LeaseID(resp.ID),
  168. TTL: resp.TTL,
  169. GrantedTTL: resp.GrantedTTL,
  170. Keys: resp.Keys,
  171. }
  172. return gresp, nil
  173. }
  174. if isHaltErr(ctx, err) {
  175. return nil, toErr(ctx, err)
  176. }
  177. }
  178. }
  179. func (l *lessor) KeepAlive(ctx context.Context, id LeaseID) (<-chan *LeaseKeepAliveResponse, error) {
  180. ch := make(chan *LeaseKeepAliveResponse, leaseResponseChSize)
  181. l.mu.Lock()
  182. // ensure that recvKeepAliveLoop is still running
  183. select {
  184. case <-l.donec:
  185. err := l.loopErr
  186. l.mu.Unlock()
  187. close(ch)
  188. return ch, ErrKeepAliveHalted{Reason: err}
  189. default:
  190. }
  191. ka, ok := l.keepAlives[id]
  192. if !ok {
  193. // create fresh keep alive
  194. ka = &keepAlive{
  195. chs: []chan<- *LeaseKeepAliveResponse{ch},
  196. ctxs: []context.Context{ctx},
  197. deadline: time.Now().Add(l.firstKeepAliveTimeout),
  198. nextKeepAlive: time.Now(),
  199. donec: make(chan struct{}),
  200. }
  201. l.keepAlives[id] = ka
  202. } else {
  203. // add channel and context to existing keep alive
  204. ka.ctxs = append(ka.ctxs, ctx)
  205. ka.chs = append(ka.chs, ch)
  206. }
  207. l.mu.Unlock()
  208. go l.keepAliveCtxCloser(id, ctx, ka.donec)
  209. l.firstKeepAliveOnce.Do(func() {
  210. go l.recvKeepAliveLoop()
  211. go l.deadlineLoop()
  212. })
  213. return ch, nil
  214. }
  215. func (l *lessor) KeepAliveOnce(ctx context.Context, id LeaseID) (*LeaseKeepAliveResponse, error) {
  216. for {
  217. resp, err := l.keepAliveOnce(ctx, id)
  218. if err == nil {
  219. if resp.TTL <= 0 {
  220. err = rpctypes.ErrLeaseNotFound
  221. }
  222. return resp, err
  223. }
  224. if isHaltErr(ctx, err) {
  225. return nil, toErr(ctx, err)
  226. }
  227. }
  228. }
  229. func (l *lessor) Close() error {
  230. l.stopCancel()
  231. // close for synchronous teardown if stream goroutines never launched
  232. l.firstKeepAliveOnce.Do(func() { close(l.donec) })
  233. <-l.donec
  234. return nil
  235. }
  236. func (l *lessor) keepAliveCtxCloser(id LeaseID, ctx context.Context, donec <-chan struct{}) {
  237. select {
  238. case <-donec:
  239. return
  240. case <-l.donec:
  241. return
  242. case <-ctx.Done():
  243. }
  244. l.mu.Lock()
  245. defer l.mu.Unlock()
  246. ka, ok := l.keepAlives[id]
  247. if !ok {
  248. return
  249. }
  250. // close channel and remove context if still associated with keep alive
  251. for i, c := range ka.ctxs {
  252. if c == ctx {
  253. close(ka.chs[i])
  254. ka.ctxs = append(ka.ctxs[:i], ka.ctxs[i+1:]...)
  255. ka.chs = append(ka.chs[:i], ka.chs[i+1:]...)
  256. break
  257. }
  258. }
  259. // remove if no one more listeners
  260. if len(ka.chs) == 0 {
  261. delete(l.keepAlives, id)
  262. }
  263. }
  264. func (l *lessor) keepAliveOnce(ctx context.Context, id LeaseID) (*LeaseKeepAliveResponse, error) {
  265. cctx, cancel := context.WithCancel(ctx)
  266. defer cancel()
  267. stream, err := l.remote.LeaseKeepAlive(cctx, grpc.FailFast(false))
  268. if err != nil {
  269. return nil, toErr(ctx, err)
  270. }
  271. err = stream.Send(&pb.LeaseKeepAliveRequest{ID: int64(id)})
  272. if err != nil {
  273. return nil, toErr(ctx, err)
  274. }
  275. resp, rerr := stream.Recv()
  276. if rerr != nil {
  277. return nil, toErr(ctx, rerr)
  278. }
  279. karesp := &LeaseKeepAliveResponse{
  280. ResponseHeader: resp.GetHeader(),
  281. ID: LeaseID(resp.ID),
  282. TTL: resp.TTL,
  283. }
  284. return karesp, nil
  285. }
  286. func (l *lessor) recvKeepAliveLoop() (gerr error) {
  287. defer func() {
  288. l.mu.Lock()
  289. close(l.donec)
  290. l.loopErr = gerr
  291. for _, ka := range l.keepAlives {
  292. ka.Close()
  293. }
  294. l.keepAlives = make(map[LeaseID]*keepAlive)
  295. l.mu.Unlock()
  296. }()
  297. stream, serr := l.resetRecv()
  298. for serr == nil {
  299. resp, err := stream.Recv()
  300. if err != nil {
  301. if isHaltErr(l.stopCtx, err) {
  302. return err
  303. }
  304. stream, serr = l.resetRecv()
  305. continue
  306. }
  307. l.recvKeepAlive(resp)
  308. }
  309. return serr
  310. }
  311. // resetRecv opens a new lease stream and starts sending LeaseKeepAliveRequests
  312. func (l *lessor) resetRecv() (pb.Lease_LeaseKeepAliveClient, error) {
  313. sctx, cancel := context.WithCancel(l.stopCtx)
  314. stream, err := l.remote.LeaseKeepAlive(sctx, grpc.FailFast(false))
  315. if err = toErr(sctx, err); err != nil {
  316. cancel()
  317. return nil, err
  318. }
  319. l.mu.Lock()
  320. defer l.mu.Unlock()
  321. if l.stream != nil && l.streamCancel != nil {
  322. l.stream.CloseSend()
  323. l.streamCancel()
  324. }
  325. l.streamCancel = cancel
  326. l.stream = stream
  327. go l.sendKeepAliveLoop(stream)
  328. return stream, nil
  329. }
  330. // recvKeepAlive updates a lease based on its LeaseKeepAliveResponse
  331. func (l *lessor) recvKeepAlive(resp *pb.LeaseKeepAliveResponse) {
  332. karesp := &LeaseKeepAliveResponse{
  333. ResponseHeader: resp.GetHeader(),
  334. ID: LeaseID(resp.ID),
  335. TTL: resp.TTL,
  336. }
  337. l.mu.Lock()
  338. defer l.mu.Unlock()
  339. ka, ok := l.keepAlives[karesp.ID]
  340. if !ok {
  341. return
  342. }
  343. if karesp.TTL <= 0 {
  344. // lease expired; close all keep alive channels
  345. delete(l.keepAlives, karesp.ID)
  346. ka.Close()
  347. return
  348. }
  349. // send update to all channels
  350. nextKeepAlive := time.Now().Add(time.Duration(karesp.TTL+2) / 3 * time.Second)
  351. ka.deadline = time.Now().Add(time.Duration(karesp.TTL) * time.Second)
  352. for _, ch := range ka.chs {
  353. select {
  354. case ch <- karesp:
  355. ka.nextKeepAlive = nextKeepAlive
  356. default:
  357. }
  358. }
  359. }
  360. // deadlineLoop reaps any keep alive channels that have not received a response
  361. // within the lease TTL
  362. func (l *lessor) deadlineLoop() {
  363. for {
  364. select {
  365. case <-time.After(time.Second):
  366. case <-l.donec:
  367. return
  368. }
  369. now := time.Now()
  370. l.mu.Lock()
  371. for id, ka := range l.keepAlives {
  372. if ka.deadline.Before(now) {
  373. // waited too long for response; lease may be expired
  374. ka.Close()
  375. delete(l.keepAlives, id)
  376. }
  377. }
  378. l.mu.Unlock()
  379. }
  380. }
  381. // sendKeepAliveLoop sends LeaseKeepAliveRequests for the lifetime of a lease stream
  382. func (l *lessor) sendKeepAliveLoop(stream pb.Lease_LeaseKeepAliveClient) {
  383. for {
  384. var tosend []LeaseID
  385. now := time.Now()
  386. l.mu.Lock()
  387. for id, ka := range l.keepAlives {
  388. if ka.nextKeepAlive.Before(now) {
  389. tosend = append(tosend, id)
  390. }
  391. }
  392. l.mu.Unlock()
  393. for _, id := range tosend {
  394. r := &pb.LeaseKeepAliveRequest{ID: int64(id)}
  395. if err := stream.Send(r); err != nil {
  396. // TODO do something with this error?
  397. return
  398. }
  399. }
  400. select {
  401. case <-time.After(500 * time.Millisecond):
  402. case <-stream.Context().Done():
  403. return
  404. case <-l.donec:
  405. return
  406. case <-l.stopCtx.Done():
  407. return
  408. }
  409. }
  410. }
  411. func (ka *keepAlive) Close() {
  412. close(ka.donec)
  413. for _, ch := range ka.chs {
  414. close(ch)
  415. }
  416. }