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.

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