grpc_proxy.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. // Copyright 2016 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package etcdmain
  15. import (
  16. "crypto/tls"
  17. "fmt"
  18. "net"
  19. "net/http"
  20. "os"
  21. "time"
  22. "github.com/coreos/etcd/clientv3"
  23. "github.com/coreos/etcd/clientv3/namespace"
  24. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  25. "github.com/coreos/etcd/pkg/debugutil"
  26. "github.com/coreos/etcd/pkg/transport"
  27. "github.com/coreos/etcd/proxy/grpcproxy"
  28. "github.com/cockroachdb/cmux"
  29. grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
  30. "github.com/prometheus/client_golang/prometheus"
  31. "github.com/spf13/cobra"
  32. "google.golang.org/grpc"
  33. )
  34. var (
  35. grpcProxyListenAddr string
  36. grpcProxyEndpoints []string
  37. grpcProxyCert string
  38. grpcProxyKey string
  39. grpcProxyCA string
  40. grpcProxyAdvertiseClientURL string
  41. grpcProxyResolverPrefix string
  42. grpcProxyResolverTTL int
  43. grpcProxyNamespace string
  44. grpcProxyEnablePprof bool
  45. )
  46. func init() {
  47. rootCmd.AddCommand(newGRPCProxyCommand())
  48. }
  49. // newGRPCProxyCommand returns the cobra command for "grpc-proxy".
  50. func newGRPCProxyCommand() *cobra.Command {
  51. lpc := &cobra.Command{
  52. Use: "grpc-proxy <subcommand>",
  53. Short: "grpc-proxy related command",
  54. }
  55. lpc.AddCommand(newGRPCProxyStartCommand())
  56. return lpc
  57. }
  58. func newGRPCProxyStartCommand() *cobra.Command {
  59. cmd := cobra.Command{
  60. Use: "start",
  61. Short: "start the grpc proxy",
  62. Run: startGRPCProxy,
  63. }
  64. cmd.Flags().StringVar(&grpcProxyListenAddr, "listen-addr", "127.0.0.1:23790", "listen address")
  65. cmd.Flags().StringSliceVar(&grpcProxyEndpoints, "endpoints", []string{"127.0.0.1:2379"}, "comma separated etcd cluster endpoints")
  66. cmd.Flags().StringVar(&grpcProxyCert, "cert", "", "identify secure connections with etcd servers using this TLS certificate file")
  67. cmd.Flags().StringVar(&grpcProxyKey, "key", "", "identify secure connections with etcd servers using this TLS key file")
  68. cmd.Flags().StringVar(&grpcProxyCA, "cacert", "", "verify certificates of TLS-enabled secure etcd servers using this CA bundle")
  69. cmd.Flags().StringVar(&grpcProxyAdvertiseClientURL, "advertise-client-url", "127.0.0.1:23790", "advertise address to register (must be reachable by client)")
  70. cmd.Flags().StringVar(&grpcProxyResolverPrefix, "resolver-prefix", "", "prefix to use for registering proxy (must be shared with other grpc-proxy members)")
  71. cmd.Flags().IntVar(&grpcProxyResolverTTL, "resolver-ttl", 0, "specify TTL, in seconds, when registering proxy endpoints")
  72. cmd.Flags().StringVar(&grpcProxyNamespace, "namespace", "", "string to prefix to all keys for namespacing requests")
  73. cmd.Flags().BoolVar(&grpcProxyEnablePprof, "enable-pprof", false, `Enable runtime profiling data via HTTP server. Address is at client URL + "/debug/pprof/"`)
  74. return &cmd
  75. }
  76. func startGRPCProxy(cmd *cobra.Command, args []string) {
  77. if grpcProxyResolverPrefix != "" && grpcProxyResolverTTL < 1 {
  78. fmt.Fprintln(os.Stderr, fmt.Errorf("invalid resolver-ttl %d", grpcProxyResolverTTL))
  79. os.Exit(1)
  80. }
  81. if grpcProxyResolverPrefix == "" && grpcProxyResolverTTL > 0 {
  82. fmt.Fprintln(os.Stderr, fmt.Errorf("invalid resolver-prefix %q", grpcProxyResolverPrefix))
  83. os.Exit(1)
  84. }
  85. if grpcProxyResolverPrefix != "" && grpcProxyResolverTTL > 0 && grpcProxyAdvertiseClientURL == "" {
  86. fmt.Fprintln(os.Stderr, fmt.Errorf("invalid advertise-client-url %q", grpcProxyAdvertiseClientURL))
  87. os.Exit(1)
  88. }
  89. l, err := net.Listen("tcp", grpcProxyListenAddr)
  90. if err != nil {
  91. fmt.Fprintln(os.Stderr, err)
  92. os.Exit(1)
  93. }
  94. if l, err = transport.NewKeepAliveListener(l, "tcp", nil); err != nil {
  95. fmt.Fprintln(os.Stderr, err)
  96. os.Exit(1)
  97. }
  98. plog.Infof("listening for grpc-proxy client requests on %s", grpcProxyListenAddr)
  99. defer func() {
  100. l.Close()
  101. plog.Infof("stopping listening for grpc-proxy client requests on %s", grpcProxyListenAddr)
  102. }()
  103. m := cmux.New(l)
  104. cfg, err := newClientCfg()
  105. if err != nil {
  106. fmt.Fprintln(os.Stderr, err)
  107. os.Exit(1)
  108. }
  109. client, err := clientv3.New(*cfg)
  110. if err != nil {
  111. fmt.Fprintln(os.Stderr, err)
  112. os.Exit(1)
  113. }
  114. if len(grpcProxyNamespace) > 0 {
  115. client.KV = namespace.NewKV(client.KV, grpcProxyNamespace)
  116. client.Watcher = namespace.NewWatcher(client.Watcher, grpcProxyNamespace)
  117. client.Lease = namespace.NewLease(client.Lease, grpcProxyNamespace)
  118. }
  119. kvp, _ := grpcproxy.NewKvProxy(client)
  120. watchp, _ := grpcproxy.NewWatchProxy(client)
  121. if grpcProxyResolverPrefix != "" {
  122. grpcproxy.Register(client, grpcProxyResolverPrefix, grpcProxyAdvertiseClientURL, grpcProxyResolverTTL)
  123. }
  124. clusterp, _ := grpcproxy.NewClusterProxy(client, grpcProxyAdvertiseClientURL, grpcProxyResolverPrefix)
  125. leasep, _ := grpcproxy.NewLeaseProxy(client)
  126. mainp := grpcproxy.NewMaintenanceProxy(client)
  127. authp := grpcproxy.NewAuthProxy(client)
  128. server := grpc.NewServer(
  129. grpc.StreamInterceptor(grpc_prometheus.StreamServerInterceptor),
  130. grpc.UnaryInterceptor(grpc_prometheus.UnaryServerInterceptor),
  131. )
  132. pb.RegisterKVServer(server, kvp)
  133. pb.RegisterWatchServer(server, watchp)
  134. pb.RegisterClusterServer(server, clusterp)
  135. pb.RegisterLeaseServer(server, leasep)
  136. pb.RegisterMaintenanceServer(server, mainp)
  137. pb.RegisterAuthServer(server, authp)
  138. errc := make(chan error)
  139. grpcl := m.Match(cmux.HTTP2())
  140. go func() { errc <- server.Serve(grpcl) }()
  141. httpmux := http.NewServeMux()
  142. httpmux.HandleFunc("/", http.NotFound)
  143. httpmux.Handle("/metrics", prometheus.Handler())
  144. if grpcProxyEnablePprof {
  145. for p, h := range debugutil.PProfHandlers() {
  146. httpmux.Handle(p, h)
  147. }
  148. plog.Infof("pprof is enabled under %s", debugutil.HTTPPrefixPProf)
  149. }
  150. srvhttp := &http.Server{
  151. Handler: httpmux,
  152. }
  153. var httpl net.Listener
  154. if cfg.TLS != nil {
  155. srvhttp.TLSConfig = cfg.TLS
  156. httpl = tls.NewListener(m.Match(cmux.Any()), cfg.TLS)
  157. } else {
  158. httpl = m.Match(cmux.HTTP1())
  159. }
  160. go func() { errc <- srvhttp.Serve(httpl) }()
  161. go func() { errc <- m.Serve() }()
  162. // grpc-proxy is initialized, ready to serve
  163. notifySystemd()
  164. fmt.Fprintln(os.Stderr, <-errc)
  165. os.Exit(1)
  166. }
  167. func newClientCfg() (*clientv3.Config, error) {
  168. // set tls if any one tls option set
  169. var cfgtls *transport.TLSInfo
  170. tlsinfo := transport.TLSInfo{}
  171. if grpcProxyCert != "" {
  172. tlsinfo.CertFile = grpcProxyCert
  173. cfgtls = &tlsinfo
  174. }
  175. if grpcProxyKey != "" {
  176. tlsinfo.KeyFile = grpcProxyKey
  177. cfgtls = &tlsinfo
  178. }
  179. if grpcProxyCA != "" {
  180. tlsinfo.CAFile = grpcProxyCA
  181. cfgtls = &tlsinfo
  182. }
  183. cfg := clientv3.Config{
  184. Endpoints: grpcProxyEndpoints,
  185. DialTimeout: 5 * time.Second,
  186. }
  187. if cfgtls != nil {
  188. clientTLS, err := cfgtls.ClientConfig()
  189. if err != nil {
  190. return nil, err
  191. }
  192. cfg.TLS = clientTLS
  193. }
  194. // TODO: support insecure tls
  195. return &cfg, nil
  196. }