checks.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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 main
  15. import (
  16. "fmt"
  17. "time"
  18. "google.golang.org/grpc"
  19. "github.com/coreos/etcd/clientv3"
  20. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  21. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  22. "golang.org/x/net/context"
  23. )
  24. const (
  25. retries = 7
  26. )
  27. type Checker interface {
  28. // Check returns an error if the system fails a consistency check.
  29. Check() error
  30. }
  31. type hashAndRevGetter interface {
  32. getRevisionHash() (revs map[string]int64, hashes map[string]int64, err error)
  33. }
  34. type hashChecker struct {
  35. hrg hashAndRevGetter
  36. }
  37. func newHashChecker(hrg hashAndRevGetter) Checker { return &hashChecker{hrg} }
  38. const leaseCheckerTimeout = 10 * time.Second
  39. func (hc *hashChecker) checkRevAndHashes() (err error) {
  40. var (
  41. revs map[string]int64
  42. hashes map[string]int64
  43. )
  44. // retries in case of transient failure or etcd cluster has not stablized yet.
  45. for i := 0; i < retries; i++ {
  46. revs, hashes, err = hc.hrg.getRevisionHash()
  47. if err != nil {
  48. plog.Warningf("retry %d. failed to retrieve revison and hash (%v)", i, err)
  49. } else {
  50. sameRev := getSameValue(revs)
  51. sameHashes := getSameValue(hashes)
  52. if sameRev && sameHashes {
  53. return nil
  54. }
  55. plog.Warningf("retry %d. etcd cluster is not stable: [revisions: %v] and [hashes: %v]", i, revs, hashes)
  56. }
  57. time.Sleep(time.Second)
  58. }
  59. if err != nil {
  60. return fmt.Errorf("failed revision and hash check (%v)", err)
  61. }
  62. return fmt.Errorf("etcd cluster is not stable: [revisions: %v] and [hashes: %v]", revs, hashes)
  63. }
  64. func (hc *hashChecker) Check() error {
  65. return hc.checkRevAndHashes()
  66. }
  67. type leaseChecker struct {
  68. endpoint string
  69. ls *leaseStresser
  70. leaseClient pb.LeaseClient
  71. kvc pb.KVClient
  72. }
  73. func (lc *leaseChecker) Check() error {
  74. conn, err := grpc.Dial(lc.ls.endpoint, grpc.WithInsecure(), grpc.WithBackoffMaxDelay(1))
  75. if err != nil {
  76. return fmt.Errorf("%v (%s)", err, lc.ls.endpoint)
  77. }
  78. defer func() {
  79. if conn != nil {
  80. conn.Close()
  81. }
  82. }()
  83. lc.kvc = pb.NewKVClient(conn)
  84. lc.leaseClient = pb.NewLeaseClient(conn)
  85. if err := lc.check(true, lc.ls.revokedLeases.leases); err != nil {
  86. return err
  87. }
  88. if err := lc.check(false, lc.ls.aliveLeases.leases); err != nil {
  89. return err
  90. }
  91. return lc.checkShortLivedLeases()
  92. }
  93. // checkShortLivedLeases ensures leases expire.
  94. func (lc *leaseChecker) checkShortLivedLeases() error {
  95. ctx, cancel := context.WithTimeout(context.Background(), leaseCheckerTimeout)
  96. errc := make(chan error)
  97. defer cancel()
  98. for leaseID := range lc.ls.shortLivedLeases.leases {
  99. go func(id int64) {
  100. errc <- lc.checkShortLivedLease(ctx, id)
  101. }(leaseID)
  102. }
  103. var errs []error
  104. for range lc.ls.shortLivedLeases.leases {
  105. if err := <-errc; err != nil {
  106. errs = append(errs, err)
  107. }
  108. }
  109. return errsToError(errs)
  110. }
  111. func (lc *leaseChecker) checkShortLivedLease(ctx context.Context, leaseID int64) (err error) {
  112. // retry in case of transient failure or lease is expired but not yet revoked due to the fact that etcd cluster didn't have enought time to delete it.
  113. var resp *pb.LeaseTimeToLiveResponse
  114. for i := 0; i < retries; i++ {
  115. resp, err = lc.getLeaseByID(ctx, leaseID)
  116. // lease not found, for ~v3.1 compatibilities, check ErrLeaseNotFound
  117. if (err == nil && resp.TTL == -1) || (err != nil && rpctypes.Error(err) == rpctypes.ErrLeaseNotFound) {
  118. return nil
  119. }
  120. if err != nil {
  121. plog.Debugf("retry %d. failed to retrieve lease %v error (%v)", i, leaseID, err)
  122. continue
  123. }
  124. if resp.TTL > 0 {
  125. plog.Debugf("lease %v is not expired. sleep for %d until it expires.", leaseID, resp.TTL)
  126. time.Sleep(time.Duration(resp.TTL) * time.Second)
  127. } else {
  128. plog.Debugf("retry %d. lease %v is expired but not yet revoked", i, leaseID)
  129. time.Sleep(time.Second)
  130. }
  131. if err = lc.checkLease(ctx, false, leaseID); err != nil {
  132. continue
  133. }
  134. return nil
  135. }
  136. return err
  137. }
  138. func (lc *leaseChecker) checkLease(ctx context.Context, expired bool, leaseID int64) error {
  139. keysExpired, err := lc.hasKeysAttachedToLeaseExpired(ctx, leaseID)
  140. if err != nil {
  141. plog.Errorf("hasKeysAttachedToLeaseExpired error %v (endpoint %q)", err, lc.endpoint)
  142. return err
  143. }
  144. leaseExpired, err := lc.hasLeaseExpired(ctx, leaseID)
  145. if err != nil {
  146. plog.Errorf("hasLeaseExpired error %v (endpoint %q)", err, lc.endpoint)
  147. return err
  148. }
  149. if leaseExpired != keysExpired {
  150. return fmt.Errorf("lease %v expiration mismatch (lease expired=%v, keys expired=%v)", leaseID, leaseExpired, keysExpired)
  151. }
  152. if leaseExpired != expired {
  153. return fmt.Errorf("lease %v expected expired=%v, got %v", leaseID, expired, leaseExpired)
  154. }
  155. return nil
  156. }
  157. func (lc *leaseChecker) check(expired bool, leases map[int64]time.Time) error {
  158. ctx, cancel := context.WithTimeout(context.Background(), leaseCheckerTimeout)
  159. defer cancel()
  160. for leaseID := range leases {
  161. if err := lc.checkLease(ctx, expired, leaseID); err != nil {
  162. return err
  163. }
  164. }
  165. return nil
  166. }
  167. func (lc *leaseChecker) getLeaseByID(ctx context.Context, leaseID int64) (*pb.LeaseTimeToLiveResponse, error) {
  168. ltl := &pb.LeaseTimeToLiveRequest{ID: leaseID, Keys: true}
  169. return lc.leaseClient.LeaseTimeToLive(ctx, ltl, grpc.FailFast(false))
  170. }
  171. func (lc *leaseChecker) hasLeaseExpired(ctx context.Context, leaseID int64) (bool, error) {
  172. // keep retrying until lease's state is known or ctx is being canceled
  173. for ctx.Err() == nil {
  174. resp, err := lc.getLeaseByID(ctx, leaseID)
  175. if err != nil {
  176. // for ~v3.1 compatibilities
  177. if rpctypes.Error(err) == rpctypes.ErrLeaseNotFound {
  178. return true, nil
  179. }
  180. } else {
  181. return resp.TTL == -1, nil
  182. }
  183. plog.Warningf("hasLeaseExpired %v resp %v error %v (endpoint %q)", leaseID, resp, err, lc.endpoint)
  184. }
  185. return false, ctx.Err()
  186. }
  187. // The keys attached to the lease has the format of "<leaseID>_<idx>" where idx is the ordering key creation
  188. // Since the format of keys contains about leaseID, finding keys base on "<leaseID>" prefix
  189. // determines whether the attached keys for a given leaseID has been deleted or not
  190. func (lc *leaseChecker) hasKeysAttachedToLeaseExpired(ctx context.Context, leaseID int64) (bool, error) {
  191. resp, err := lc.kvc.Range(ctx, &pb.RangeRequest{
  192. Key: []byte(fmt.Sprintf("%d", leaseID)),
  193. RangeEnd: []byte(clientv3.GetPrefixRangeEnd(fmt.Sprintf("%d", leaseID))),
  194. }, grpc.FailFast(false))
  195. if err != nil {
  196. plog.Errorf("retrieving keys attached to lease %v error %v (endpoint %q)", leaseID, err, lc.endpoint)
  197. return false, err
  198. }
  199. return len(resp.Kvs) == 0, nil
  200. }
  201. // compositeChecker implements a checker that runs a slice of Checkers concurrently.
  202. type compositeChecker struct{ checkers []Checker }
  203. func newCompositeChecker(checkers []Checker) Checker {
  204. return &compositeChecker{checkers}
  205. }
  206. func (cchecker *compositeChecker) Check() error {
  207. errc := make(chan error)
  208. for _, c := range cchecker.checkers {
  209. go func(chk Checker) { errc <- chk.Check() }(c)
  210. }
  211. var errs []error
  212. for range cchecker.checkers {
  213. if err := <-errc; err != nil {
  214. errs = append(errs, err)
  215. }
  216. }
  217. return errsToError(errs)
  218. }
  219. type runnerChecker struct {
  220. errc chan error
  221. }
  222. func (rc *runnerChecker) Check() error {
  223. select {
  224. case err := <-rc.errc:
  225. return err
  226. default:
  227. return nil
  228. }
  229. }
  230. type noChecker struct{}
  231. func newNoChecker() Checker { return &noChecker{} }
  232. func (nc *noChecker) Check() error { return nil }