grpc_proxy.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. "math"
  19. "net"
  20. "net/http"
  21. "net/url"
  22. "os"
  23. "path/filepath"
  24. "time"
  25. "github.com/coreos/etcd/clientv3"
  26. "github.com/coreos/etcd/clientv3/namespace"
  27. "github.com/coreos/etcd/etcdserver/api/v3election/v3electionpb"
  28. "github.com/coreos/etcd/etcdserver/api/v3lock/v3lockpb"
  29. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  30. "github.com/coreos/etcd/pkg/debugutil"
  31. "github.com/coreos/etcd/pkg/transport"
  32. "github.com/coreos/etcd/proxy/grpcproxy"
  33. "github.com/cockroachdb/cmux"
  34. grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
  35. "github.com/prometheus/client_golang/prometheus"
  36. "github.com/spf13/cobra"
  37. "google.golang.org/grpc"
  38. )
  39. var (
  40. grpcProxyListenAddr string
  41. grpcProxyMetricsListenAddr string
  42. grpcProxyEndpoints []string
  43. grpcProxyDNSCluster string
  44. grpcProxyInsecureDiscovery bool
  45. grpcProxyDataDir string
  46. // tls for connecting to etcd
  47. grpcProxyCA string
  48. grpcProxyCert string
  49. grpcProxyKey string
  50. grpcProxyInsecureSkipTLSVerify bool
  51. // tls for clients connecting to proxy
  52. grpcProxyListenCA string
  53. grpcProxyListenCert string
  54. grpcProxyListenKey string
  55. grpcProxyListenAutoTLS bool
  56. grpcProxyAdvertiseClientURL string
  57. grpcProxyResolverPrefix string
  58. grpcProxyResolverTTL int
  59. grpcProxyNamespace string
  60. grpcProxyEnablePprof bool
  61. )
  62. func init() {
  63. rootCmd.AddCommand(newGRPCProxyCommand())
  64. }
  65. // newGRPCProxyCommand returns the cobra command for "grpc-proxy".
  66. func newGRPCProxyCommand() *cobra.Command {
  67. lpc := &cobra.Command{
  68. Use: "grpc-proxy <subcommand>",
  69. Short: "grpc-proxy related command",
  70. }
  71. lpc.AddCommand(newGRPCProxyStartCommand())
  72. return lpc
  73. }
  74. func newGRPCProxyStartCommand() *cobra.Command {
  75. cmd := cobra.Command{
  76. Use: "start",
  77. Short: "start the grpc proxy",
  78. Run: startGRPCProxy,
  79. }
  80. cmd.Flags().StringVar(&grpcProxyListenAddr, "listen-addr", "127.0.0.1:23790", "listen address")
  81. cmd.Flags().StringVar(&grpcProxyDNSCluster, "discovery-srv", "", "DNS domain used to bootstrap initial cluster")
  82. cmd.Flags().StringVar(&grpcProxyMetricsListenAddr, "metrics-addr", "", "listen for /metrics requests on an additional interface")
  83. cmd.Flags().BoolVar(&grpcProxyInsecureDiscovery, "insecure-discovery", false, "accept insecure SRV records")
  84. cmd.Flags().StringSliceVar(&grpcProxyEndpoints, "endpoints", []string{"127.0.0.1:2379"}, "comma separated etcd cluster endpoints")
  85. cmd.Flags().StringVar(&grpcProxyAdvertiseClientURL, "advertise-client-url", "127.0.0.1:23790", "advertise address to register (must be reachable by client)")
  86. cmd.Flags().StringVar(&grpcProxyResolverPrefix, "resolver-prefix", "", "prefix to use for registering proxy (must be shared with other grpc-proxy members)")
  87. cmd.Flags().IntVar(&grpcProxyResolverTTL, "resolver-ttl", 0, "specify TTL, in seconds, when registering proxy endpoints")
  88. cmd.Flags().StringVar(&grpcProxyNamespace, "namespace", "", "string to prefix to all keys for namespacing requests")
  89. cmd.Flags().BoolVar(&grpcProxyEnablePprof, "enable-pprof", false, `Enable runtime profiling data via HTTP server. Address is at client URL + "/debug/pprof/"`)
  90. cmd.Flags().StringVar(&grpcProxyDataDir, "data-dir", "default.proxy", "Data directory for persistent data")
  91. // client TLS for connecting to server
  92. cmd.Flags().StringVar(&grpcProxyCert, "cert", "", "identify secure connections with etcd servers using this TLS certificate file")
  93. cmd.Flags().StringVar(&grpcProxyKey, "key", "", "identify secure connections with etcd servers using this TLS key file")
  94. cmd.Flags().StringVar(&grpcProxyCA, "cacert", "", "verify certificates of TLS-enabled secure etcd servers using this CA bundle")
  95. cmd.Flags().BoolVar(&grpcProxyInsecureSkipTLSVerify, "insecure-skip-tls-verify", false, "skip authentication of etcd server TLS certificates")
  96. // client TLS for connecting to proxy
  97. cmd.Flags().StringVar(&grpcProxyListenCert, "cert-file", "", "identify secure connections to the proxy using this TLS certificate file")
  98. cmd.Flags().StringVar(&grpcProxyListenKey, "key-file", "", "identify secure connections to the proxy using this TLS key file")
  99. cmd.Flags().StringVar(&grpcProxyListenCA, "trusted-ca-file", "", "verify certificates of TLS-enabled secure proxy using this CA bundle")
  100. cmd.Flags().BoolVar(&grpcProxyListenAutoTLS, "auto-tls", false, "proxy TLS using generated certificates")
  101. return &cmd
  102. }
  103. func startGRPCProxy(cmd *cobra.Command, args []string) {
  104. checkArgs()
  105. tlsinfo := newTLS(grpcProxyListenCA, grpcProxyListenCert, grpcProxyListenKey)
  106. if tlsinfo == nil && grpcProxyListenAutoTLS {
  107. host := []string{"https://" + grpcProxyListenAddr}
  108. dir := filepath.Join(grpcProxyDataDir, "fixtures", "proxy")
  109. autoTLS, err := transport.SelfCert(dir, host)
  110. if err != nil {
  111. plog.Fatal(err)
  112. }
  113. tlsinfo = &autoTLS
  114. }
  115. if tlsinfo != nil {
  116. plog.Infof("ServerTLS: %s", tlsinfo)
  117. }
  118. m := mustListenCMux(tlsinfo)
  119. grpcl := m.Match(cmux.HTTP2())
  120. defer func() {
  121. grpcl.Close()
  122. plog.Infof("stopping listening for grpc-proxy client requests on %s", grpcProxyListenAddr)
  123. }()
  124. client := mustNewClient()
  125. srvhttp, httpl := mustHTTPListener(m, tlsinfo)
  126. errc := make(chan error)
  127. go func() { errc <- newGRPCProxyServer(client).Serve(grpcl) }()
  128. go func() { errc <- srvhttp.Serve(httpl) }()
  129. go func() { errc <- m.Serve() }()
  130. if len(grpcProxyMetricsListenAddr) > 0 {
  131. mhttpl := mustMetricsListener(tlsinfo)
  132. go func() {
  133. mux := http.NewServeMux()
  134. mux.Handle("/metrics", prometheus.Handler())
  135. plog.Fatal(http.Serve(mhttpl, mux))
  136. }()
  137. }
  138. // grpc-proxy is initialized, ready to serve
  139. notifySystemd()
  140. fmt.Fprintln(os.Stderr, <-errc)
  141. os.Exit(1)
  142. }
  143. func checkArgs() {
  144. if grpcProxyResolverPrefix != "" && grpcProxyResolverTTL < 1 {
  145. fmt.Fprintln(os.Stderr, fmt.Errorf("invalid resolver-ttl %d", grpcProxyResolverTTL))
  146. os.Exit(1)
  147. }
  148. if grpcProxyResolverPrefix == "" && grpcProxyResolverTTL > 0 {
  149. fmt.Fprintln(os.Stderr, fmt.Errorf("invalid resolver-prefix %q", grpcProxyResolverPrefix))
  150. os.Exit(1)
  151. }
  152. if grpcProxyResolverPrefix != "" && grpcProxyResolverTTL > 0 && grpcProxyAdvertiseClientURL == "" {
  153. fmt.Fprintln(os.Stderr, fmt.Errorf("invalid advertise-client-url %q", grpcProxyAdvertiseClientURL))
  154. os.Exit(1)
  155. }
  156. }
  157. func mustNewClient() *clientv3.Client {
  158. srvs := discoverEndpoints(grpcProxyDNSCluster, grpcProxyCA, grpcProxyInsecureDiscovery)
  159. eps := srvs.Endpoints
  160. if len(eps) == 0 {
  161. eps = grpcProxyEndpoints
  162. }
  163. cfg, err := newClientCfg(eps)
  164. if err != nil {
  165. fmt.Fprintln(os.Stderr, err)
  166. os.Exit(1)
  167. }
  168. client, err := clientv3.New(*cfg)
  169. if err != nil {
  170. fmt.Fprintln(os.Stderr, err)
  171. os.Exit(1)
  172. }
  173. return client
  174. }
  175. func newClientCfg(eps []string) (*clientv3.Config, error) {
  176. // set tls if any one tls option set
  177. cfg := clientv3.Config{
  178. Endpoints: eps,
  179. DialTimeout: 5 * time.Second,
  180. }
  181. tls := newTLS(grpcProxyCA, grpcProxyCert, grpcProxyKey)
  182. if tls == nil && grpcProxyInsecureSkipTLSVerify {
  183. tls = &transport.TLSInfo{}
  184. }
  185. if tls != nil {
  186. clientTLS, err := tls.ClientConfig()
  187. if err != nil {
  188. return nil, err
  189. }
  190. clientTLS.InsecureSkipVerify = grpcProxyInsecureSkipTLSVerify
  191. cfg.TLS = clientTLS
  192. plog.Infof("ClientTLS: %s", tls)
  193. }
  194. return &cfg, nil
  195. }
  196. func newTLS(ca, cert, key string) *transport.TLSInfo {
  197. if ca == "" && cert == "" && key == "" {
  198. return nil
  199. }
  200. return &transport.TLSInfo{CAFile: ca, CertFile: cert, KeyFile: key}
  201. }
  202. func mustListenCMux(tlsinfo *transport.TLSInfo) cmux.CMux {
  203. l, err := net.Listen("tcp", grpcProxyListenAddr)
  204. if err != nil {
  205. fmt.Fprintln(os.Stderr, err)
  206. os.Exit(1)
  207. }
  208. var tlscfg *tls.Config
  209. scheme := "http"
  210. if tlsinfo != nil {
  211. if tlscfg, err = tlsinfo.ServerConfig(); err != nil {
  212. plog.Fatal(err)
  213. }
  214. scheme = "https"
  215. }
  216. if l, err = transport.NewKeepAliveListener(l, scheme, tlscfg); err != nil {
  217. fmt.Fprintln(os.Stderr, err)
  218. os.Exit(1)
  219. }
  220. plog.Infof("listening for grpc-proxy client requests on %s", grpcProxyListenAddr)
  221. return cmux.New(l)
  222. }
  223. func newGRPCProxyServer(client *clientv3.Client) *grpc.Server {
  224. if len(grpcProxyNamespace) > 0 {
  225. client.KV = namespace.NewKV(client.KV, grpcProxyNamespace)
  226. client.Watcher = namespace.NewWatcher(client.Watcher, grpcProxyNamespace)
  227. client.Lease = namespace.NewLease(client.Lease, grpcProxyNamespace)
  228. }
  229. kvp, _ := grpcproxy.NewKvProxy(client)
  230. watchp, _ := grpcproxy.NewWatchProxy(client)
  231. if grpcProxyResolverPrefix != "" {
  232. grpcproxy.Register(client, grpcProxyResolverPrefix, grpcProxyAdvertiseClientURL, grpcProxyResolverTTL)
  233. }
  234. clusterp, _ := grpcproxy.NewClusterProxy(client, grpcProxyAdvertiseClientURL, grpcProxyResolverPrefix)
  235. leasep, _ := grpcproxy.NewLeaseProxy(client)
  236. mainp := grpcproxy.NewMaintenanceProxy(client)
  237. authp := grpcproxy.NewAuthProxy(client)
  238. electionp := grpcproxy.NewElectionProxy(client)
  239. lockp := grpcproxy.NewLockProxy(client)
  240. server := grpc.NewServer(
  241. grpc.StreamInterceptor(grpc_prometheus.StreamServerInterceptor),
  242. grpc.UnaryInterceptor(grpc_prometheus.UnaryServerInterceptor),
  243. grpc.MaxConcurrentStreams(math.MaxUint32),
  244. )
  245. pb.RegisterKVServer(server, kvp)
  246. pb.RegisterWatchServer(server, watchp)
  247. pb.RegisterClusterServer(server, clusterp)
  248. pb.RegisterLeaseServer(server, leasep)
  249. pb.RegisterMaintenanceServer(server, mainp)
  250. pb.RegisterAuthServer(server, authp)
  251. v3electionpb.RegisterElectionServer(server, electionp)
  252. v3lockpb.RegisterLockServer(server, lockp)
  253. return server
  254. }
  255. func mustHTTPListener(m cmux.CMux, tlsinfo *transport.TLSInfo) (*http.Server, net.Listener) {
  256. httpmux := http.NewServeMux()
  257. httpmux.HandleFunc("/", http.NotFound)
  258. httpmux.Handle("/metrics", prometheus.Handler())
  259. if grpcProxyEnablePprof {
  260. for p, h := range debugutil.PProfHandlers() {
  261. httpmux.Handle(p, h)
  262. }
  263. plog.Infof("pprof is enabled under %s", debugutil.HTTPPrefixPProf)
  264. }
  265. srvhttp := &http.Server{Handler: httpmux}
  266. if tlsinfo == nil {
  267. return srvhttp, m.Match(cmux.HTTP1())
  268. }
  269. srvTLS, err := tlsinfo.ServerConfig()
  270. if err != nil {
  271. plog.Fatalf("could not setup TLS (%v)", err)
  272. }
  273. srvhttp.TLSConfig = srvTLS
  274. return srvhttp, m.Match(cmux.Any())
  275. }
  276. func mustMetricsListener(tlsinfo *transport.TLSInfo) net.Listener {
  277. murl, err := url.Parse(grpcProxyMetricsListenAddr)
  278. if err != nil {
  279. fmt.Fprintf(os.Stderr, "cannot parse %q", grpcProxyMetricsListenAddr)
  280. os.Exit(1)
  281. }
  282. ml, err := transport.NewListener(murl.Host, murl.Scheme, tlsinfo)
  283. if err != nil {
  284. fmt.Fprintln(os.Stderr, err)
  285. os.Exit(1)
  286. }
  287. plog.Info("grpc-proxy: listening for metrics on ", murl.String())
  288. return ml
  289. }