grpc_client_server.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. package pb
  2. import (
  3. "context"
  4. "fmt"
  5. "math/rand/v2"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "sync"
  10. "time"
  11. "github.com/google/uuid"
  12. "github.com/seaweedfs/seaweedfs/weed/util/request_id"
  13. "google.golang.org/grpc/metadata"
  14. "github.com/seaweedfs/seaweedfs/weed/glog"
  15. "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
  16. "github.com/seaweedfs/seaweedfs/weed/util"
  17. "google.golang.org/grpc"
  18. "google.golang.org/grpc/keepalive"
  19. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  20. "github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
  21. "github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
  22. "github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
  23. )
  24. const (
  25. Max_Message_Size = 1 << 30 // 1 GB
  26. )
  27. var (
  28. // cache grpc connections
  29. grpcClients = make(map[string]*versionedGrpcClient)
  30. grpcClientsLock sync.Mutex
  31. )
  32. type versionedGrpcClient struct {
  33. *grpc.ClientConn
  34. version int
  35. errCount int
  36. }
  37. func init() {
  38. http.DefaultTransport.(*http.Transport).MaxIdleConnsPerHost = 1024
  39. http.DefaultTransport.(*http.Transport).MaxIdleConns = 1024
  40. }
  41. func NewGrpcServer(opts ...grpc.ServerOption) *grpc.Server {
  42. var options []grpc.ServerOption
  43. options = append(options,
  44. grpc.KeepaliveParams(keepalive.ServerParameters{
  45. Time: 10 * time.Second, // wait time before ping if no activity
  46. Timeout: 20 * time.Second, // ping timeout
  47. // MaxConnectionAge: 10 * time.Hour,
  48. }),
  49. grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
  50. MinTime: 60 * time.Second, // min time a client should wait before sending a ping
  51. PermitWithoutStream: true,
  52. }),
  53. grpc.MaxRecvMsgSize(Max_Message_Size),
  54. grpc.MaxSendMsgSize(Max_Message_Size),
  55. grpc.UnaryInterceptor(requestIDUnaryInterceptor()),
  56. )
  57. for _, opt := range opts {
  58. if opt != nil {
  59. options = append(options, opt)
  60. }
  61. }
  62. return grpc.NewServer(options...)
  63. }
  64. func GrpcDial(ctx context.Context, address string, waitForReady bool, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
  65. // opts = append(opts, grpc.WithBlock())
  66. // opts = append(opts, grpc.WithTimeout(time.Duration(5*time.Second)))
  67. var options []grpc.DialOption
  68. options = append(options,
  69. // grpc.WithTransportCredentials(insecure.NewCredentials()),
  70. grpc.WithDefaultCallOptions(
  71. grpc.MaxCallSendMsgSize(Max_Message_Size),
  72. grpc.MaxCallRecvMsgSize(Max_Message_Size),
  73. grpc.WaitForReady(waitForReady),
  74. ),
  75. grpc.WithKeepaliveParams(keepalive.ClientParameters{
  76. Time: 30 * time.Second, // client ping server if no activity for this long
  77. Timeout: 20 * time.Second,
  78. PermitWithoutStream: true,
  79. }))
  80. for _, opt := range opts {
  81. if opt != nil {
  82. options = append(options, opt)
  83. }
  84. }
  85. return grpc.DialContext(ctx, address, options...)
  86. }
  87. func getOrCreateConnection(address string, waitForReady bool, opts ...grpc.DialOption) (*versionedGrpcClient, error) {
  88. grpcClientsLock.Lock()
  89. defer grpcClientsLock.Unlock()
  90. existingConnection, found := grpcClients[address]
  91. if found {
  92. return existingConnection, nil
  93. }
  94. ctx := context.Background()
  95. grpcConnection, err := GrpcDial(ctx, address, waitForReady, opts...)
  96. if err != nil {
  97. return nil, fmt.Errorf("fail to dial %s: %v", address, err)
  98. }
  99. vgc := &versionedGrpcClient{
  100. grpcConnection,
  101. rand.Int(),
  102. 0,
  103. }
  104. grpcClients[address] = vgc
  105. return vgc, nil
  106. }
  107. func requestIDUnaryInterceptor() grpc.UnaryServerInterceptor {
  108. return func(
  109. ctx context.Context,
  110. req interface{},
  111. info *grpc.UnaryServerInfo,
  112. handler grpc.UnaryHandler,
  113. ) (interface{}, error) {
  114. incomingMd, _ := metadata.FromIncomingContext(ctx)
  115. idList := incomingMd.Get(request_id.AmzRequestIDHeader)
  116. var reqID string
  117. if len(idList) > 0 {
  118. reqID = idList[0]
  119. }
  120. if reqID == "" {
  121. reqID = uuid.New().String()
  122. }
  123. ctx = metadata.NewOutgoingContext(ctx,
  124. metadata.New(map[string]string{
  125. request_id.AmzRequestIDHeader: reqID,
  126. }))
  127. ctx = request_id.Set(ctx, reqID)
  128. grpc.SetTrailer(ctx, metadata.Pairs(request_id.AmzRequestIDHeader, reqID))
  129. return handler(ctx, req)
  130. }
  131. }
  132. // WithGrpcClient In streamingMode, always use a fresh connection. Otherwise, try to reuse an existing connection.
  133. func WithGrpcClient(streamingMode bool, signature int32, fn func(*grpc.ClientConn) error, address string, waitForReady bool, opts ...grpc.DialOption) error {
  134. if !streamingMode {
  135. vgc, err := getOrCreateConnection(address, waitForReady, opts...)
  136. if err != nil {
  137. return fmt.Errorf("getOrCreateConnection %s: %v", address, err)
  138. }
  139. executionErr := fn(vgc.ClientConn)
  140. if executionErr != nil {
  141. if strings.Contains(executionErr.Error(), "transport") ||
  142. strings.Contains(executionErr.Error(), "connection closed") {
  143. grpcClientsLock.Lock()
  144. if t, ok := grpcClients[address]; ok {
  145. if t.version == vgc.version {
  146. vgc.Close()
  147. delete(grpcClients, address)
  148. }
  149. }
  150. grpcClientsLock.Unlock()
  151. }
  152. }
  153. return executionErr
  154. } else {
  155. ctx := context.Background()
  156. if signature != 0 {
  157. md := metadata.New(map[string]string{"sw-client-id": fmt.Sprintf("%d", signature)})
  158. ctx = metadata.NewOutgoingContext(ctx, md)
  159. }
  160. grpcConnection, err := GrpcDial(ctx, address, waitForReady, opts...)
  161. if err != nil {
  162. return fmt.Errorf("fail to dial %s: %v", address, err)
  163. }
  164. defer grpcConnection.Close()
  165. executionErr := fn(grpcConnection)
  166. if executionErr != nil {
  167. return executionErr
  168. }
  169. return nil
  170. }
  171. }
  172. func ParseServerAddress(server string, deltaPort int) (newServerAddress string, err error) {
  173. host, port, parseErr := hostAndPort(server)
  174. if parseErr != nil {
  175. return "", fmt.Errorf("server port parse error: %w", parseErr)
  176. }
  177. newPort := int(port) + deltaPort
  178. return util.JoinHostPort(host, newPort), nil
  179. }
  180. func hostAndPort(address string) (host string, port uint64, err error) {
  181. colonIndex := strings.LastIndex(address, ":")
  182. if colonIndex < 0 {
  183. return "", 0, fmt.Errorf("server should have hostname:port format: %v", address)
  184. }
  185. port, err = strconv.ParseUint(address[colonIndex+1:], 10, 64)
  186. if err != nil {
  187. return "", 0, fmt.Errorf("server port parse error: %w", err)
  188. }
  189. return address[:colonIndex], port, err
  190. }
  191. func ServerToGrpcAddress(server string) (serverGrpcAddress string) {
  192. host, port, parseErr := hostAndPort(server)
  193. if parseErr != nil {
  194. glog.Fatalf("server address %s parse error: %v", server, parseErr)
  195. }
  196. grpcPort := int(port) + 10000
  197. return util.JoinHostPort(host, grpcPort)
  198. }
  199. func GrpcAddressToServerAddress(grpcAddress string) (serverAddress string) {
  200. host, grpcPort, parseErr := hostAndPort(grpcAddress)
  201. if parseErr != nil {
  202. glog.Fatalf("server grpc address %s parse error: %v", grpcAddress, parseErr)
  203. }
  204. port := int(grpcPort) - 10000
  205. return util.JoinHostPort(host, port)
  206. }
  207. func WithMasterClient(streamingMode bool, master ServerAddress, grpcDialOption grpc.DialOption, waitForReady bool, fn func(client master_pb.SeaweedClient) error) error {
  208. return WithGrpcClient(streamingMode, 0, func(grpcConnection *grpc.ClientConn) error {
  209. client := master_pb.NewSeaweedClient(grpcConnection)
  210. return fn(client)
  211. }, master.ToGrpcAddress(), waitForReady, grpcDialOption)
  212. }
  213. func WithVolumeServerClient(streamingMode bool, volumeServer ServerAddress, grpcDialOption grpc.DialOption, fn func(client volume_server_pb.VolumeServerClient) error) error {
  214. return WithGrpcClient(streamingMode, 0, func(grpcConnection *grpc.ClientConn) error {
  215. client := volume_server_pb.NewVolumeServerClient(grpcConnection)
  216. return fn(client)
  217. }, volumeServer.ToGrpcAddress(), false, grpcDialOption)
  218. }
  219. func WithOneOfGrpcMasterClients(streamingMode bool, masterGrpcAddresses map[string]ServerAddress, grpcDialOption grpc.DialOption, fn func(client master_pb.SeaweedClient) error) (err error) {
  220. for _, masterGrpcAddress := range masterGrpcAddresses {
  221. err = WithGrpcClient(streamingMode, 0, func(grpcConnection *grpc.ClientConn) error {
  222. client := master_pb.NewSeaweedClient(grpcConnection)
  223. return fn(client)
  224. }, masterGrpcAddress.ToGrpcAddress(), false, grpcDialOption)
  225. if err == nil {
  226. return nil
  227. }
  228. }
  229. return err
  230. }
  231. func WithBrokerGrpcClient(streamingMode bool, brokerGrpcAddress string, grpcDialOption grpc.DialOption, fn func(client mq_pb.SeaweedMessagingClient) error) error {
  232. return WithGrpcClient(streamingMode, 0, func(grpcConnection *grpc.ClientConn) error {
  233. client := mq_pb.NewSeaweedMessagingClient(grpcConnection)
  234. return fn(client)
  235. }, brokerGrpcAddress, false, grpcDialOption)
  236. }
  237. func WithFilerClient(streamingMode bool, signature int32, filer ServerAddress, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) error {
  238. return WithGrpcFilerClient(streamingMode, signature, filer, grpcDialOption, fn)
  239. }
  240. func WithGrpcFilerClient(streamingMode bool, signature int32, filerGrpcAddress ServerAddress, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) error {
  241. return WithGrpcClient(streamingMode, signature, func(grpcConnection *grpc.ClientConn) error {
  242. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  243. return fn(client)
  244. }, filerGrpcAddress.ToGrpcAddress(), false, grpcDialOption)
  245. }
  246. func WithOneOfGrpcFilerClients(streamingMode bool, filerAddresses []ServerAddress, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) (err error) {
  247. for _, filerAddress := range filerAddresses {
  248. err = WithGrpcClient(streamingMode, 0, func(grpcConnection *grpc.ClientConn) error {
  249. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  250. return fn(client)
  251. }, filerAddress.ToGrpcAddress(), false, grpcDialOption)
  252. if err == nil {
  253. return nil
  254. }
  255. }
  256. return err
  257. }
  258. func WithWorkerClient(streamingMode bool, workerAddress string, grpcDialOption grpc.DialOption, fn func(client worker_pb.WorkerServiceClient) error) error {
  259. return WithGrpcClient(streamingMode, 0, func(grpcConnection *grpc.ClientConn) error {
  260. client := worker_pb.NewWorkerServiceClient(grpcConnection)
  261. return fn(client)
  262. }, workerAddress, false, grpcDialOption)
  263. }