lease.go 11 KB

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