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.

208 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. println(" dialing to", address, "...")
  86. grpcConnection, err := GrpcDial(context.Background(), address, opts...)
  87. if err != nil {
  88. grpcClientsLock.Unlock()
  89. return fmt.Errorf("fail to dial %s: %v", address, err)
  90. }
  91. grpcClients[address] = grpcConnection
  92. grpcClientsLock.Unlock()
  93. err = fn(grpcConnection)
  94. if err != nil {
  95. grpcClientsLock.Lock()
  96. // delete(grpcClients, address)
  97. grpcClientsLock.Unlock()
  98. // println("closing created new connection to", grpcConnection.Target())
  99. // grpcConnection.Close()
  100. }
  101. return err
  102. }
  103. func ParseServerToGrpcAddress(server string) (serverGrpcAddress string, err error) {
  104. colonIndex := strings.LastIndex(server, ":")
  105. if colonIndex < 0 {
  106. return "", fmt.Errorf("server should have hostname:port format: %v", server)
  107. }
  108. port, parseErr := strconv.ParseUint(server[colonIndex+1:], 10, 64)
  109. if parseErr != nil {
  110. return "", fmt.Errorf("server port parse error: %v", parseErr)
  111. }
  112. grpcPort := int(port) + 10000
  113. return fmt.Sprintf("%s:%d", server[:colonIndex], grpcPort), nil
  114. }
  115. func ServerToGrpcAddress(server string) (serverGrpcAddress string) {
  116. hostnameAndPort := strings.Split(server, ":")
  117. if len(hostnameAndPort) != 2 {
  118. return fmt.Sprintf("unexpected server address: %s", server)
  119. }
  120. port, parseErr := strconv.ParseUint(hostnameAndPort[1], 10, 64)
  121. if parseErr != nil {
  122. return fmt.Sprintf("failed to parse port for %s:%s", hostnameAndPort[0], hostnameAndPort[1])
  123. }
  124. grpcPort := int(port) + 10000
  125. return fmt.Sprintf("%s:%d", hostnameAndPort[0], grpcPort)
  126. }
  127. func WithMasterClient(master string, grpcDialOption grpc.DialOption, fn func(client master_pb.SeaweedClient) error) error {
  128. masterGrpcAddress, parseErr := ParseServerToGrpcAddress(master)
  129. if parseErr != nil {
  130. return fmt.Errorf("failed to parse master grpc %v: %v", master, parseErr)
  131. }
  132. return WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  133. client := master_pb.NewSeaweedClient(grpcConnection)
  134. return fn(client)
  135. }, masterGrpcAddress, grpcDialOption)
  136. }
  137. func WithBrokerGrpcClient(brokerGrpcAddress string, grpcDialOption grpc.DialOption, fn func(client messaging_pb.SeaweedMessagingClient) error) error {
  138. return WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  139. client := messaging_pb.NewSeaweedMessagingClient(grpcConnection)
  140. return fn(client)
  141. }, brokerGrpcAddress, grpcDialOption)
  142. }
  143. func WithFilerClient(filer string, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) error {
  144. filerGrpcAddress, parseErr := ParseServerToGrpcAddress(filer)
  145. if parseErr != nil {
  146. return fmt.Errorf("failed to parse filer grpc %v: %v", filer, parseErr)
  147. }
  148. return WithGrpcFilerClient(filerGrpcAddress, grpcDialOption, fn)
  149. }
  150. func WithGrpcFilerClient(filerGrpcAddress string, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) error {
  151. return WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  152. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  153. return fn(client)
  154. }, filerGrpcAddress, grpcDialOption)
  155. }
  156. func ParseFilerGrpcAddress(filer string) (filerGrpcAddress string, err error) {
  157. hostnameAndPort := strings.Split(filer, ":")
  158. if len(hostnameAndPort) != 2 {
  159. return "", fmt.Errorf("filer should have hostname:port format: %v", hostnameAndPort)
  160. }
  161. filerPort, parseErr := strconv.ParseUint(hostnameAndPort[1], 10, 64)
  162. if parseErr != nil {
  163. return "", fmt.Errorf("filer port parse error: %v", parseErr)
  164. }
  165. filerGrpcPort := int(filerPort) + 10000
  166. return fmt.Sprintf("%s:%d", hostnameAndPort[0], filerGrpcPort), nil
  167. }