You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

195 lines
5.4 KiB

5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
  1. package pb
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "sync"
  9. "time"
  10. "google.golang.org/grpc"
  11. "google.golang.org/grpc/keepalive"
  12. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  13. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  14. )
  15. const (
  16. Max_Message_Size = 1 << 30 // 1 GB
  17. )
  18. var (
  19. // cache grpc connections
  20. grpcClients = make(map[string]*grpc.ClientConn)
  21. grpcClientsLock sync.Mutex
  22. )
  23. func init() {
  24. http.DefaultTransport.(*http.Transport).MaxIdleConnsPerHost = 1024
  25. }
  26. func NewGrpcServer(opts ...grpc.ServerOption) *grpc.Server {
  27. var options []grpc.ServerOption
  28. options = append(options,
  29. grpc.KeepaliveParams(keepalive.ServerParameters{
  30. Time: 10 * time.Second, // wait time before ping if no activity
  31. Timeout: 20 * time.Second, // ping timeout
  32. }),
  33. grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
  34. MinTime: 60 * time.Second, // min time a client should wait before sending a ping
  35. PermitWithoutStream: true,
  36. }),
  37. grpc.MaxRecvMsgSize(Max_Message_Size),
  38. grpc.MaxSendMsgSize(Max_Message_Size),
  39. )
  40. for _, opt := range opts {
  41. if opt != nil {
  42. options = append(options, opt)
  43. }
  44. }
  45. return grpc.NewServer(options...)
  46. }
  47. func GrpcDial(ctx context.Context, address string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
  48. // opts = append(opts, grpc.WithBlock())
  49. // opts = append(opts, grpc.WithTimeout(time.Duration(5*time.Second)))
  50. var options []grpc.DialOption
  51. options = append(options,
  52. // grpc.WithInsecure(),
  53. grpc.WithDefaultCallOptions(
  54. grpc.MaxCallSendMsgSize(Max_Message_Size),
  55. grpc.MaxCallRecvMsgSize(Max_Message_Size),
  56. ),
  57. grpc.WithKeepaliveParams(keepalive.ClientParameters{
  58. Time: 30 * time.Second, // client ping server if no activity for this long
  59. Timeout: 20 * time.Second,
  60. PermitWithoutStream: true,
  61. }))
  62. for _, opt := range opts {
  63. if opt != nil {
  64. options = append(options, opt)
  65. }
  66. }
  67. return grpc.DialContext(ctx, address, options...)
  68. }
  69. func WithCachedGrpcClient(fn func(*grpc.ClientConn) error, address string, opts ...grpc.DialOption) error {
  70. grpcClientsLock.Lock()
  71. existingConnection, found := grpcClients[address]
  72. if found {
  73. grpcClientsLock.Unlock()
  74. err := fn(existingConnection)
  75. if err != nil {
  76. grpcClientsLock.Lock()
  77. delete(grpcClients, address)
  78. grpcClientsLock.Unlock()
  79. existingConnection.Close()
  80. }
  81. return err
  82. }
  83. grpcConnection, err := GrpcDial(context.Background(), address, opts...)
  84. if err != nil {
  85. grpcClientsLock.Unlock()
  86. return fmt.Errorf("fail to dial %s: %v", address, err)
  87. }
  88. grpcClients[address] = grpcConnection
  89. grpcClientsLock.Unlock()
  90. err = fn(grpcConnection)
  91. if err != nil {
  92. grpcClientsLock.Lock()
  93. delete(grpcClients, address)
  94. grpcClientsLock.Unlock()
  95. grpcConnection.Close()
  96. }
  97. return err
  98. }
  99. func ParseServerToGrpcAddress(server string) (serverGrpcAddress string, err error) {
  100. colonIndex := strings.LastIndex(server, ":")
  101. if colonIndex < 0 {
  102. return "", fmt.Errorf("server should have hostname:port format: %v", server)
  103. }
  104. port, parseErr := strconv.ParseUint(server[colonIndex+1:], 10, 64)
  105. if parseErr != nil {
  106. return "", fmt.Errorf("server port parse error: %v", parseErr)
  107. }
  108. grpcPort := int(port) + 10000
  109. return fmt.Sprintf("%s:%d", server[:colonIndex], grpcPort), nil
  110. }
  111. func ServerToGrpcAddress(server string) (serverGrpcAddress string) {
  112. hostnameAndPort := strings.Split(server, ":")
  113. if len(hostnameAndPort) != 2 {
  114. return fmt.Sprintf("unexpected server address: %s", server)
  115. }
  116. port, parseErr := strconv.ParseUint(hostnameAndPort[1], 10, 64)
  117. if parseErr != nil {
  118. return fmt.Sprintf("failed to parse port for %s:%s", hostnameAndPort[0], hostnameAndPort[1])
  119. }
  120. grpcPort := int(port) + 10000
  121. return fmt.Sprintf("%s:%d", hostnameAndPort[0], grpcPort)
  122. }
  123. func WithMasterClient(master string, grpcDialOption grpc.DialOption, fn func(client master_pb.SeaweedClient) error) error {
  124. masterGrpcAddress, parseErr := ParseServerToGrpcAddress(master)
  125. if parseErr != nil {
  126. return fmt.Errorf("failed to parse master grpc %v: %v", master, parseErr)
  127. }
  128. return WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  129. client := master_pb.NewSeaweedClient(grpcConnection)
  130. return fn(client)
  131. }, masterGrpcAddress, grpcDialOption)
  132. }
  133. func WithFilerClient(filer string, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) error {
  134. filerGrpcAddress, parseErr := ParseServerToGrpcAddress(filer)
  135. if parseErr != nil {
  136. return fmt.Errorf("failed to parse filer grpc %v: %v", filer, parseErr)
  137. }
  138. return WithGrpcFilerClient(filerGrpcAddress, grpcDialOption, fn)
  139. }
  140. func WithGrpcFilerClient(filerGrpcAddress string, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) error {
  141. return WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  142. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  143. return fn(client)
  144. }, filerGrpcAddress, grpcDialOption)
  145. }
  146. func ParseFilerGrpcAddress(filer string) (filerGrpcAddress string, err error) {
  147. hostnameAndPort := strings.Split(filer, ":")
  148. if len(hostnameAndPort) != 2 {
  149. return "", fmt.Errorf("filer should have hostname:port format: %v", hostnameAndPort)
  150. }
  151. filerPort, parseErr := strconv.ParseUint(hostnameAndPort[1], 10, 64)
  152. if parseErr != nil {
  153. return "", fmt.Errorf("filer port parse error: %v", parseErr)
  154. }
  155. filerGrpcPort := int(filerPort) + 10000
  156. return fmt.Sprintf("%s:%d", hostnameAndPort[0], filerGrpcPort), nil
  157. }