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.

272 lines
7.6 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
6 years ago
5 years ago
6 years ago
3 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
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
  1. package pb
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/glog"
  6. "github.com/chrislusf/seaweedfs/weed/util"
  7. "math/rand"
  8. "net/http"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "time"
  13. "google.golang.org/grpc"
  14. "google.golang.org/grpc/keepalive"
  15. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  16. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  17. "github.com/chrislusf/seaweedfs/weed/pb/messaging_pb"
  18. )
  19. const (
  20. Max_Message_Size = 1 << 30 // 1 GB
  21. )
  22. var (
  23. // cache grpc connections
  24. grpcClients = make(map[string]*versionedGrpcClient)
  25. grpcClientsLock sync.Mutex
  26. )
  27. type versionedGrpcClient struct {
  28. *grpc.ClientConn
  29. version int
  30. errCount int
  31. }
  32. func init() {
  33. http.DefaultTransport.(*http.Transport).MaxIdleConnsPerHost = 1024
  34. http.DefaultTransport.(*http.Transport).MaxIdleConns = 1024
  35. }
  36. func NewGrpcServer(opts ...grpc.ServerOption) *grpc.Server {
  37. var options []grpc.ServerOption
  38. options = append(options,
  39. grpc.KeepaliveParams(keepalive.ServerParameters{
  40. Time: 10 * time.Second, // wait time before ping if no activity
  41. Timeout: 20 * time.Second, // ping timeout
  42. MaxConnectionAge: 10 * time.Hour,
  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. grpcConnection, err := GrpcDial(context.Background(), address, opts...)
  88. if err != nil {
  89. return nil, fmt.Errorf("fail to dial %s: %v", address, err)
  90. }
  91. vgc := &versionedGrpcClient{
  92. grpcConnection,
  93. rand.Int(),
  94. 0,
  95. }
  96. grpcClients[address] = vgc
  97. return vgc, nil
  98. }
  99. func WithCachedGrpcClient(fn func(*grpc.ClientConn) error, address string, opts ...grpc.DialOption) error {
  100. vgc, err := getOrCreateConnection(address, opts...)
  101. if err != nil {
  102. return fmt.Errorf("getOrCreateConnection %s: %v", address, err)
  103. }
  104. executionErr := fn(vgc.ClientConn)
  105. if executionErr != nil {
  106. if strings.Contains(executionErr.Error(), "transport") ||
  107. strings.Contains(executionErr.Error(), "connection closed") {
  108. grpcClientsLock.Lock()
  109. if t, ok := grpcClients[address]; ok {
  110. if t.version == vgc.version {
  111. vgc.Close()
  112. delete(grpcClients, address)
  113. }
  114. }
  115. grpcClientsLock.Unlock()
  116. }
  117. }
  118. return executionErr
  119. }
  120. func ParseServerToGrpcAddress(server string) (serverGrpcAddress string, err error) {
  121. return ParseServerAddress(server, 10000)
  122. }
  123. func ParseServersToGrpcAddresses(servers []string) (serverGrpcAddresses []string, err error) {
  124. for _, server := range servers {
  125. if serverGrpcAddress, parseErr := ParseServerToGrpcAddress(server); parseErr == nil {
  126. serverGrpcAddresses = append(serverGrpcAddresses, serverGrpcAddress)
  127. } else {
  128. return nil, parseErr
  129. }
  130. }
  131. return
  132. }
  133. func ParseServerAddress(server string, deltaPort int) (newServerAddress string, err error) {
  134. host, port, parseErr := hostAndPort(server)
  135. if parseErr != nil {
  136. return "", fmt.Errorf("server port parse error: %v", parseErr)
  137. }
  138. newPort := int(port) + deltaPort
  139. return util.JoinHostPort(host, newPort), nil
  140. }
  141. func hostAndPort(address string) (host string, port uint64, err error) {
  142. colonIndex := strings.LastIndex(address, ":")
  143. if colonIndex < 0 {
  144. return "", 0, fmt.Errorf("server should have hostname:port format: %v", address)
  145. }
  146. port, err = strconv.ParseUint(address[colonIndex+1:], 10, 64)
  147. if err != nil {
  148. return "", 0, fmt.Errorf("server port parse error: %v", err)
  149. }
  150. return address[:colonIndex], port, err
  151. }
  152. func ServerToGrpcAddress(server string) (serverGrpcAddress string) {
  153. host, port, parseErr := hostAndPort(server)
  154. if parseErr != nil {
  155. glog.Fatalf("server address %s parse error: %v", server, parseErr)
  156. }
  157. grpcPort := int(port) + 10000
  158. return util.JoinHostPort(host, grpcPort)
  159. }
  160. func GrpcAddressToServerAddress(grpcAddress string) (serverAddress string) {
  161. host, grpcPort, parseErr := hostAndPort(grpcAddress)
  162. if parseErr != nil {
  163. glog.Fatalf("server grpc address %s parse error: %v", grpcAddress, parseErr)
  164. }
  165. port := int(grpcPort) - 10000
  166. return util.JoinHostPort(host, port)
  167. }
  168. func WithMasterClient(master string, grpcDialOption grpc.DialOption, fn func(client master_pb.SeaweedClient) error) error {
  169. masterGrpcAddress, parseErr := ParseServerToGrpcAddress(master)
  170. if parseErr != nil {
  171. return fmt.Errorf("failed to parse master grpc %v: %v", master, parseErr)
  172. }
  173. return WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  174. client := master_pb.NewSeaweedClient(grpcConnection)
  175. return fn(client)
  176. }, masterGrpcAddress, grpcDialOption)
  177. }
  178. func WithOneOfGrpcMasterClients(masterGrpcAddresses []string, grpcDialOption grpc.DialOption, fn func(client master_pb.SeaweedClient) error) (err error) {
  179. for _, masterGrpcAddress := range masterGrpcAddresses {
  180. err = WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  181. client := master_pb.NewSeaweedClient(grpcConnection)
  182. return fn(client)
  183. }, masterGrpcAddress, grpcDialOption)
  184. if err == nil {
  185. return nil
  186. }
  187. }
  188. return err
  189. }
  190. func WithBrokerGrpcClient(brokerGrpcAddress string, grpcDialOption grpc.DialOption, fn func(client messaging_pb.SeaweedMessagingClient) error) error {
  191. return WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  192. client := messaging_pb.NewSeaweedMessagingClient(grpcConnection)
  193. return fn(client)
  194. }, brokerGrpcAddress, grpcDialOption)
  195. }
  196. func WithFilerClient(filer string, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) error {
  197. filerGrpcAddress, parseErr := ParseServerToGrpcAddress(filer)
  198. if parseErr != nil {
  199. return fmt.Errorf("failed to parse filer grpc %v: %v", filer, parseErr)
  200. }
  201. return WithGrpcFilerClient(filerGrpcAddress, grpcDialOption, fn)
  202. }
  203. func WithGrpcFilerClient(filerGrpcAddress string, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) error {
  204. return WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  205. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  206. return fn(client)
  207. }, filerGrpcAddress, grpcDialOption)
  208. }
  209. func WithOneOfGrpcFilerClients(filerGrpcAddresses []string, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) (err error) {
  210. for _, filerGrpcAddress := range filerGrpcAddresses {
  211. err = WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  212. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  213. return fn(client)
  214. }, filerGrpcAddress, grpcDialOption)
  215. if err == nil {
  216. return nil
  217. }
  218. }
  219. return err
  220. }