session.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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 concurrency
  15. import (
  16. "context"
  17. "time"
  18. v3 "go.etcd.io/etcd/clientv3"
  19. )
  20. const defaultSessionTTL = 60
  21. // Session represents a lease kept alive for the lifetime of a client.
  22. // Fault-tolerant applications may use sessions to reason about liveness.
  23. type Session struct {
  24. client *v3.Client
  25. opts *sessionOptions
  26. id v3.LeaseID
  27. cancel context.CancelFunc
  28. donec <-chan struct{}
  29. }
  30. // NewSession gets the leased session for a client.
  31. func NewSession(client *v3.Client, opts ...SessionOption) (*Session, error) {
  32. ops := &sessionOptions{ttl: defaultSessionTTL, ctx: client.Ctx()}
  33. for _, opt := range opts {
  34. opt(ops)
  35. }
  36. id := ops.leaseID
  37. if id == v3.NoLease {
  38. resp, err := client.Grant(ops.ctx, int64(ops.ttl))
  39. if err != nil {
  40. return nil, err
  41. }
  42. id = resp.ID
  43. }
  44. ctx, cancel := context.WithCancel(ops.ctx)
  45. keepAlive, err := client.KeepAlive(ctx, id)
  46. if err != nil || keepAlive == nil {
  47. cancel()
  48. return nil, err
  49. }
  50. donec := make(chan struct{})
  51. s := &Session{client: client, opts: ops, id: id, cancel: cancel, donec: donec}
  52. // keep the lease alive until client error or cancelled context
  53. go func() {
  54. defer close(donec)
  55. for range keepAlive {
  56. // eat messages until keep alive channel closes
  57. }
  58. }()
  59. return s, nil
  60. }
  61. // Client is the etcd client that is attached to the session.
  62. func (s *Session) Client() *v3.Client {
  63. return s.client
  64. }
  65. // Lease is the lease ID for keys bound to the session.
  66. func (s *Session) Lease() v3.LeaseID { return s.id }
  67. // Done returns a channel that closes when the lease is orphaned, expires, or
  68. // is otherwise no longer being refreshed.
  69. func (s *Session) Done() <-chan struct{} { return s.donec }
  70. // Orphan ends the refresh for the session lease. This is useful
  71. // in case the state of the client connection is indeterminate (revoke
  72. // would fail) or when transferring lease ownership.
  73. func (s *Session) Orphan() {
  74. s.cancel()
  75. <-s.donec
  76. }
  77. // Close orphans the session and revokes the session lease.
  78. func (s *Session) Close() error {
  79. s.Orphan()
  80. // if revoke takes longer than the ttl, lease is expired anyway
  81. ctx, cancel := context.WithTimeout(s.opts.ctx, time.Duration(s.opts.ttl)*time.Second)
  82. _, err := s.client.Revoke(ctx, s.id)
  83. cancel()
  84. return err
  85. }
  86. type sessionOptions struct {
  87. ttl int
  88. leaseID v3.LeaseID
  89. ctx context.Context
  90. }
  91. // SessionOption configures Session.
  92. type SessionOption func(*sessionOptions)
  93. // WithTTL configures the session's TTL in seconds.
  94. // If TTL is <= 0, the default 60 seconds TTL will be used.
  95. func WithTTL(ttl int) SessionOption {
  96. return func(so *sessionOptions) {
  97. if ttl > 0 {
  98. so.ttl = ttl
  99. }
  100. }
  101. }
  102. // WithLease specifies the existing leaseID to be used for the session.
  103. // This is useful in process restart scenario, for example, to reclaim
  104. // leadership from an election prior to restart.
  105. func WithLease(leaseID v3.LeaseID) SessionOption {
  106. return func(so *sessionOptions) {
  107. so.leaseID = leaseID
  108. }
  109. }
  110. // WithContext assigns a context to the session instead of defaulting to
  111. // using the client context. This is useful for canceling NewSession and
  112. // Close operations immediately without having to close the client. If the
  113. // context is canceled before Close() completes, the session's lease will be
  114. // abandoned and left to expire instead of being revoked.
  115. func WithContext(ctx context.Context) SessionOption {
  116. return func(so *sessionOptions) {
  117. so.ctx = ctx
  118. }
  119. }