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.

87 lines
2.3 KiB

6 years ago
6 years ago
6 years ago
6 years ago
  1. package util
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. "sync"
  7. "time"
  8. "google.golang.org/grpc"
  9. "google.golang.org/grpc/keepalive"
  10. )
  11. var (
  12. // cache grpc connections
  13. grpcClients = make(map[string]*grpc.ClientConn)
  14. grpcClientsLock sync.Mutex
  15. )
  16. func NewGrpcServer() *grpc.Server {
  17. return grpc.NewServer(grpc.KeepaliveParams(keepalive.ServerParameters{
  18. Time: 10 * time.Second, // wait time before ping if no activity
  19. Timeout: 20 * time.Second, // ping timeout
  20. }), grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
  21. MinTime: 60 * time.Second, // min time a client should wait before sending a ping
  22. }))
  23. }
  24. func GrpcDial(address string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
  25. // opts = append(opts, grpc.WithBlock())
  26. // opts = append(opts, grpc.WithTimeout(time.Duration(5*time.Second)))
  27. opts = append(opts, grpc.WithInsecure())
  28. opts = append(opts, grpc.WithKeepaliveParams(keepalive.ClientParameters{
  29. Time: 30 * time.Second, // client ping server if no activity for this long
  30. Timeout: 20 * time.Second,
  31. }))
  32. return grpc.Dial(address, opts...)
  33. }
  34. func WithCachedGrpcClient(fn func(*grpc.ClientConn) error, address string, opts ...grpc.DialOption) error {
  35. grpcClientsLock.Lock()
  36. existingConnection, found := grpcClients[address]
  37. if found {
  38. grpcClientsLock.Unlock()
  39. return fn(existingConnection)
  40. }
  41. grpcConnection, err := GrpcDial(address, opts...)
  42. if err != nil {
  43. grpcClientsLock.Unlock()
  44. return fmt.Errorf("fail to dial %s: %v", address, err)
  45. }
  46. grpcClients[address] = grpcConnection
  47. grpcClientsLock.Unlock()
  48. err = fn(grpcConnection)
  49. if err != nil {
  50. grpcClientsLock.Lock()
  51. delete(grpcClients, address)
  52. grpcClientsLock.Unlock()
  53. }
  54. return err
  55. }
  56. func ParseServerToGrpcAddress(server string, optionalGrpcPort int) (serverGrpcAddress string, err error) {
  57. hostnameAndPort := strings.Split(server, ":")
  58. if len(hostnameAndPort) != 2 {
  59. return "", fmt.Errorf("The server should have hostname:port format: %v", hostnameAndPort)
  60. }
  61. filerPort, parseErr := strconv.ParseUint(hostnameAndPort[1], 10, 64)
  62. if parseErr != nil {
  63. return "", fmt.Errorf("The server port parse error: %v", parseErr)
  64. }
  65. filerGrpcPort := int(filerPort) + 10000
  66. if optionalGrpcPort != 0 {
  67. filerGrpcPort = optionalGrpcPort
  68. }
  69. return fmt.Sprintf("%s:%d", hostnameAndPort[0], filerGrpcPort), nil
  70. }