interceptor.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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 v3rpc
  15. import (
  16. "strings"
  17. "sync"
  18. "time"
  19. "github.com/coreos/etcd/etcdserver"
  20. "github.com/coreos/etcd/etcdserver/api"
  21. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  22. "github.com/coreos/etcd/pkg/types"
  23. "github.com/coreos/etcd/raft"
  24. prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
  25. "golang.org/x/net/context"
  26. "google.golang.org/grpc"
  27. "google.golang.org/grpc/metadata"
  28. )
  29. const (
  30. maxNoLeaderCnt = 3
  31. )
  32. type streamsMap struct {
  33. mu sync.Mutex
  34. streams map[grpc.ServerStream]struct{}
  35. }
  36. func newUnaryInterceptor(s *etcdserver.EtcdServer) grpc.UnaryServerInterceptor {
  37. return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
  38. if !api.IsCapabilityEnabled(api.V3rpcCapability) {
  39. return nil, rpctypes.ErrGRPCNotCapable
  40. }
  41. md, ok := metadata.FromContext(ctx)
  42. if ok {
  43. if ks := md[rpctypes.MetadataRequireLeaderKey]; len(ks) > 0 && ks[0] == rpctypes.MetadataHasLeader {
  44. if s.Leader() == types.ID(raft.None) {
  45. return nil, rpctypes.ErrGRPCNoLeader
  46. }
  47. }
  48. }
  49. return prometheus.UnaryServerInterceptor(ctx, req, info, handler)
  50. }
  51. }
  52. func newStreamInterceptor(s *etcdserver.EtcdServer) grpc.StreamServerInterceptor {
  53. smap := monitorLeader(s)
  54. return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
  55. if !api.IsCapabilityEnabled(api.V3rpcCapability) {
  56. return rpctypes.ErrGRPCNotCapable
  57. }
  58. md, ok := metadata.FromContext(ss.Context())
  59. if ok {
  60. if ks := md[rpctypes.MetadataRequireLeaderKey]; len(ks) > 0 && ks[0] == rpctypes.MetadataHasLeader {
  61. if s.Leader() == types.ID(raft.None) {
  62. return rpctypes.ErrGRPCNoLeader
  63. }
  64. cctx, cancel := context.WithCancel(ss.Context())
  65. ss = serverStreamWithCtx{ctx: cctx, cancel: &cancel, ServerStream: ss}
  66. smap.mu.Lock()
  67. smap.streams[ss] = struct{}{}
  68. smap.mu.Unlock()
  69. defer func() {
  70. smap.mu.Lock()
  71. delete(smap.streams, ss)
  72. smap.mu.Unlock()
  73. cancel()
  74. }()
  75. }
  76. }
  77. return prometheus.StreamServerInterceptor(srv, ss, info, handler)
  78. }
  79. }
  80. func splitMethodName(fullMethodName string) (string, string) {
  81. fullMethodName = strings.TrimPrefix(fullMethodName, "/") // remove leading slash
  82. if i := strings.Index(fullMethodName, "/"); i >= 0 {
  83. return fullMethodName[:i], fullMethodName[i+1:]
  84. }
  85. return "unknown", "unknown"
  86. }
  87. type serverStreamWithCtx struct {
  88. grpc.ServerStream
  89. ctx context.Context
  90. cancel *context.CancelFunc
  91. }
  92. func (ssc serverStreamWithCtx) Context() context.Context { return ssc.ctx }
  93. func monitorLeader(s *etcdserver.EtcdServer) *streamsMap {
  94. smap := &streamsMap{
  95. streams: make(map[grpc.ServerStream]struct{}),
  96. }
  97. go func() {
  98. election := time.Duration(s.Cfg.TickMs) * time.Duration(s.Cfg.ElectionTicks) * time.Millisecond
  99. noLeaderCnt := 0
  100. for {
  101. select {
  102. case <-s.StopNotify():
  103. return
  104. case <-time.After(election):
  105. if s.Leader() == types.ID(raft.None) {
  106. noLeaderCnt++
  107. } else {
  108. noLeaderCnt = 0
  109. }
  110. // We are more conservative on canceling existing streams. Reconnecting streams
  111. // cost much more than just rejecting new requests. So we wait until the member
  112. // cannot find a leader for maxNoLeaderCnt election timeouts to cancel existing streams.
  113. if noLeaderCnt >= maxNoLeaderCnt {
  114. smap.mu.Lock()
  115. for ss := range smap.streams {
  116. if ssWithCtx, ok := ss.(serverStreamWithCtx); ok {
  117. (*ssWithCtx.cancel)()
  118. <-ss.Context().Done()
  119. }
  120. }
  121. smap.streams = make(map[grpc.ServerStream]struct{})
  122. smap.mu.Unlock()
  123. }
  124. }
  125. }
  126. }()
  127. return smap
  128. }