client.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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. NonBlock bool
  33. Timeout time.Duration
  34. Secure bool
  35. Retry bool
  36. DialOptions []grpc.DialOption
  37. }
  38. // ClientOption defines the method to customize a ClientOptions.
  39. ClientOption func(options *ClientOptions)
  40. client struct {
  41. conn *grpc.ClientConn
  42. }
  43. )
  44. // NewClient returns a Client.
  45. func NewClient(target string, opts ...ClientOption) (Client, error) {
  46. var cli client
  47. opts = append([]ClientOption{WithDialOption(grpc.WithBalancerName(p2c.Name))}, opts...)
  48. if err := cli.dial(target, opts...); err != nil {
  49. return nil, err
  50. }
  51. return &cli, nil
  52. }
  53. func (c *client) Conn() *grpc.ClientConn {
  54. return c.conn
  55. }
  56. func (c *client) buildDialOptions(opts ...ClientOption) []grpc.DialOption {
  57. var cliOpts ClientOptions
  58. for _, opt := range opts {
  59. opt(&cliOpts)
  60. }
  61. var options []grpc.DialOption
  62. if !cliOpts.Secure {
  63. options = append([]grpc.DialOption(nil), grpc.WithInsecure())
  64. }
  65. if !cliOpts.NonBlock {
  66. options = append(options, grpc.WithBlock())
  67. }
  68. options = append(options,
  69. WithUnaryClientInterceptors(
  70. clientinterceptors.UnaryTracingInterceptor,
  71. clientinterceptors.DurationInterceptor,
  72. clientinterceptors.PrometheusInterceptor,
  73. clientinterceptors.BreakerInterceptor,
  74. clientinterceptors.TimeoutInterceptor(cliOpts.Timeout),
  75. clientinterceptors.RetryInterceptor(cliOpts.Retry),
  76. ),
  77. WithStreamClientInterceptors(
  78. clientinterceptors.StreamTracingInterceptor,
  79. ),
  80. )
  81. return append(options, cliOpts.DialOptions...)
  82. }
  83. func (c *client) dial(server string, opts ...ClientOption) error {
  84. options := c.buildDialOptions(opts...)
  85. timeCtx, cancel := context.WithTimeout(context.Background(), dialTimeout)
  86. defer cancel()
  87. conn, err := grpc.DialContext(timeCtx, server, options...)
  88. if err != nil {
  89. service := server
  90. if errors.Is(err, context.DeadlineExceeded) {
  91. pos := strings.LastIndexByte(server, separator)
  92. // len(server) - 1 is the index of last char
  93. if 0 < pos && pos < len(server)-1 {
  94. service = server[pos+1:]
  95. }
  96. }
  97. return fmt.Errorf("rpc dial: %s, error: %s, make sure rpc service %q is already started",
  98. server, err.Error(), service)
  99. }
  100. c.conn = conn
  101. return nil
  102. }
  103. // WithDialOption returns a func to customize a ClientOptions with given dial option.
  104. func WithDialOption(opt grpc.DialOption) ClientOption {
  105. return func(options *ClientOptions) {
  106. options.DialOptions = append(options.DialOptions, opt)
  107. }
  108. }
  109. // WithNonBlock sets the dialing to be nonblock.
  110. func WithNonBlock() ClientOption {
  111. return func(options *ClientOptions) {
  112. options.NonBlock = true
  113. }
  114. }
  115. // WithTimeout returns a func to customize a ClientOptions with given timeout.
  116. func WithTimeout(timeout time.Duration) ClientOption {
  117. return func(options *ClientOptions) {
  118. options.Timeout = timeout
  119. }
  120. }
  121. // WithRetry returns a func to customize a ClientOptions with auto retry.
  122. func WithRetry() ClientOption {
  123. return func(options *ClientOptions) {
  124. options.Retry = true
  125. }
  126. }
  127. // WithUnaryClientInterceptor returns a func to customize a ClientOptions with given interceptor.
  128. func WithUnaryClientInterceptor(interceptor grpc.UnaryClientInterceptor) ClientOption {
  129. return func(options *ClientOptions) {
  130. options.DialOptions = append(options.DialOptions, WithUnaryClientInterceptors(interceptor))
  131. }
  132. }
  133. // WithTlsClientFromUnilateral return a func to customize a ClientOptions Verify with Unilateralism authentication.
  134. func WithTlsClientFromUnilateral(crt, domainName string) ClientOption {
  135. return func(options *ClientOptions) {
  136. c, err := credentials.NewClientTLSFromFile(crt, domainName)
  137. if err != nil {
  138. log.Fatalf("credentials.NewClientTLSFromFile err: %v", err)
  139. }
  140. options.Secure = true
  141. options.DialOptions = append(options.DialOptions, grpc.WithTransportCredentials(c))
  142. }
  143. }
  144. // WithTlsClientFromMutual return a func to customize a ClientOptions Verify with mutual authentication.
  145. func WithTlsClientFromMutual(crtFile, keyFile, caFile string) ClientOption {
  146. return func(options *ClientOptions) {
  147. cert, err := tls.LoadX509KeyPair(crtFile, keyFile)
  148. if err != nil {
  149. log.Fatalf("tls.LoadX509KeyPair err: %v", err)
  150. }
  151. certPool := x509.NewCertPool()
  152. ca, err := ioutil.ReadFile(caFile)
  153. if err != nil {
  154. log.Fatalf("credentials: failed to ReadFile CA certificates err: %v", err)
  155. }
  156. if !certPool.AppendCertsFromPEM(ca) {
  157. log.Fatalf("credentials: failed to append certificates err: %v", err)
  158. }
  159. config := &tls.Config{
  160. Certificates: []tls.Certificate{cert},
  161. RootCAs: certPool,
  162. }
  163. options.Secure = true
  164. options.DialOptions = append(options.DialOptions,
  165. grpc.WithTransportCredentials(credentials.NewTLS(config)))
  166. }
  167. }