grpc_proxy.go 12 KB

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