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.

270 lines
8.0 KiB

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