client.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. package internal
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "crypto/x509"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "log"
  10. "strings"
  11. "time"
  12. "github.com/tal-tech/go-zero/zrpc/internal/balancer/p2c"
  13. "github.com/tal-tech/go-zero/zrpc/internal/clientinterceptors"
  14. "github.com/tal-tech/go-zero/zrpc/internal/resolver"
  15. "google.golang.org/grpc"
  16. "google.golang.org/grpc/credentials"
  17. )
  18. const (
  19. dialTimeout = time.Second * 3
  20. separator = '/'
  21. )
  22. func init() {
  23. resolver.RegisterResolver()
  24. }
  25. type (
  26. // Client interface wraps the Conn method.
  27. Client interface {
  28. Conn() *grpc.ClientConn
  29. }
  30. // A ClientOptions is a client options.
  31. ClientOptions struct {
  32. Timeout time.Duration
  33. Secure bool
  34. Retry bool
  35. DialOptions []grpc.DialOption
  36. }
  37. // ClientOption defines the method to customize a ClientOptions.
  38. ClientOption func(options *ClientOptions)
  39. client struct {
  40. conn *grpc.ClientConn
  41. }
  42. )
  43. // NewClient returns a Client.
  44. func NewClient(target string, opts ...ClientOption) (Client, error) {
  45. var cli client
  46. opts = append([]ClientOption{WithDialOption(grpc.WithBalancerName(p2c.Name))}, opts...)
  47. if err := cli.dial(target, opts...); err != nil {
  48. return nil, err
  49. }
  50. return &cli, nil
  51. }
  52. func (c *client) Conn() *grpc.ClientConn {
  53. return c.conn
  54. }
  55. func (c *client) buildDialOptions(opts ...ClientOption) []grpc.DialOption {
  56. var cliOpts ClientOptions
  57. for _, opt := range opts {
  58. opt(&cliOpts)
  59. }
  60. var options []grpc.DialOption
  61. if !cliOpts.Secure {
  62. options = append([]grpc.DialOption(nil), grpc.WithInsecure())
  63. }
  64. options = append(options,
  65. grpc.WithBlock(),
  66. WithUnaryClientInterceptors(
  67. clientinterceptors.UnaryTracingInterceptor,
  68. clientinterceptors.DurationInterceptor,
  69. clientinterceptors.PrometheusInterceptor,
  70. clientinterceptors.BreakerInterceptor,
  71. clientinterceptors.TimeoutInterceptor(cliOpts.Timeout),
  72. clientinterceptors.RetryInterceptor(cliOpts.Retry),
  73. ),
  74. WithStreamClientInterceptors(
  75. clientinterceptors.StreamTracingInterceptor,
  76. ),
  77. )
  78. return append(options, cliOpts.DialOptions...)
  79. }
  80. func (c *client) dial(server string, opts ...ClientOption) error {
  81. options := c.buildDialOptions(opts...)
  82. timeCtx, cancel := context.WithTimeout(context.Background(), dialTimeout)
  83. defer cancel()
  84. conn, err := grpc.DialContext(timeCtx, server, options...)
  85. if err != nil {
  86. service := server
  87. if errors.Is(err, context.DeadlineExceeded) {
  88. pos := strings.LastIndexByte(server, separator)
  89. // len(server) - 1 is the index of last char
  90. if 0 < pos && pos < len(server)-1 {
  91. service = server[pos+1:]
  92. }
  93. }
  94. return fmt.Errorf("rpc dial: %s, error: %s, make sure rpc service %q is already started",
  95. server, err.Error(), service)
  96. }
  97. c.conn = conn
  98. return nil
  99. }
  100. // WithDialOption returns a func to customize a ClientOptions with given dial option.
  101. func WithDialOption(opt grpc.DialOption) ClientOption {
  102. return func(options *ClientOptions) {
  103. options.DialOptions = append(options.DialOptions, opt)
  104. }
  105. }
  106. // WithTimeout returns a func to customize a ClientOptions with given timeout.
  107. func WithTimeout(timeout time.Duration) ClientOption {
  108. return func(options *ClientOptions) {
  109. options.Timeout = timeout
  110. }
  111. }
  112. // WithRetry returns a func to customize a ClientOptions with auto retry.
  113. func WithRetry() ClientOption {
  114. return func(options *ClientOptions) {
  115. options.Retry = true
  116. }
  117. }
  118. // WithUnaryClientInterceptor returns a func to customize a ClientOptions with given interceptor.
  119. func WithUnaryClientInterceptor(interceptor grpc.UnaryClientInterceptor) ClientOption {
  120. return func(options *ClientOptions) {
  121. options.DialOptions = append(options.DialOptions, WithUnaryClientInterceptors(interceptor))
  122. }
  123. }
  124. // WithTlsClientFromUnilateral return a func to customize a ClientOptions Verify with Unilateralism authentication.
  125. func WithTlsClientFromUnilateral(crt, domainName string) ClientOption {
  126. return func(options *ClientOptions) {
  127. c, err := credentials.NewClientTLSFromFile(crt, domainName)
  128. if err != nil {
  129. log.Fatalf("credentials.NewClientTLSFromFile err: %v", err)
  130. }
  131. options.Secure = true
  132. options.DialOptions = append(options.DialOptions, grpc.WithTransportCredentials(c))
  133. }
  134. }
  135. // WithTlsClientFromMutual return a func to customize a ClientOptions Verify with mutual authentication.
  136. func WithTlsClientFromMutual(crtFile, keyFile, caFile string) ClientOption {
  137. return func(options *ClientOptions) {
  138. cert, err := tls.LoadX509KeyPair(crtFile, keyFile)
  139. if err != nil {
  140. log.Fatalf("tls.LoadX509KeyPair err: %v", err)
  141. }
  142. certPool := x509.NewCertPool()
  143. ca, err := ioutil.ReadFile(caFile)
  144. if err != nil {
  145. log.Fatalf("credentials: failed to ReadFile CA certificates err: %v", err)
  146. }
  147. if !certPool.AppendCertsFromPEM(ca) {
  148. log.Fatalf("credentials: failed to append certificates err: %v", err)
  149. }
  150. config := &tls.Config{
  151. Certificates: []tls.Certificate{cert},
  152. RootCAs: certPool,
  153. }
  154. options.Secure = true
  155. options.DialOptions = append(options.DialOptions,
  156. grpc.WithTransportCredentials(credentials.NewTLS(config)))
  157. }
  158. }