grpc_proxy.go 13 KB

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