serve.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. // Copyright 2015 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. "io/ioutil"
  18. defaultLog "log"
  19. "net"
  20. "net/http"
  21. "strings"
  22. "time"
  23. "github.com/coreos/etcd/etcdserver"
  24. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  25. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  26. "github.com/coreos/etcd/pkg/transport"
  27. "github.com/cockroachdb/cmux"
  28. gw "github.com/grpc-ecosystem/grpc-gateway/runtime"
  29. "golang.org/x/net/context"
  30. "google.golang.org/grpc"
  31. "google.golang.org/grpc/credentials"
  32. )
  33. type serveCtx struct {
  34. l net.Listener
  35. host string
  36. secure bool
  37. insecure bool
  38. }
  39. // serve accepts incoming connections on the listener l,
  40. // creating a new service goroutine for each. The service goroutines
  41. // read requests and then call handler to reply to them.
  42. func serve(sctx *serveCtx, s *etcdserver.EtcdServer, tlscfg *tls.Config, handler http.Handler) error {
  43. logger := defaultLog.New(ioutil.Discard, "etcdhttp", 0)
  44. <-s.ReadyNotify()
  45. plog.Info("ready to serve client requests")
  46. m := cmux.New(sctx.l)
  47. if sctx.insecure {
  48. gs := v3rpc.Server(s, nil)
  49. grpcl := m.Match(cmux.HTTP2())
  50. go func() { plog.Fatal(gs.Serve(grpcl)) }()
  51. opts := []grpc.DialOption{
  52. grpc.WithInsecure(),
  53. }
  54. gwmux, err := registerGateway(sctx.l.Addr().String(), opts)
  55. if err != nil {
  56. return err
  57. }
  58. httpmux := http.NewServeMux()
  59. httpmux.Handle("/v3alpha/", gwmux)
  60. httpmux.Handle("/", handler)
  61. srvhttp := &http.Server{
  62. Handler: httpmux,
  63. ErrorLog: logger, // do not log user error
  64. }
  65. httpl := m.Match(cmux.HTTP1())
  66. go func() { plog.Fatal(srvhttp.Serve(httpl)) }()
  67. plog.Noticef("serving insecure client requests on %s, this is strongly discouraged!", sctx.host)
  68. }
  69. if sctx.secure {
  70. gs := v3rpc.Server(s, tlscfg)
  71. handler = grpcHandlerFunc(gs, handler)
  72. dtls := transport.ShallowCopyTLSConfig(tlscfg)
  73. // trust local server
  74. dtls.InsecureSkipVerify = true
  75. creds := credentials.NewTLS(dtls)
  76. opts := []grpc.DialOption{grpc.WithTransportCredentials(creds)}
  77. gwmux, err := registerGateway(sctx.l.Addr().String(), opts)
  78. if err != nil {
  79. return err
  80. }
  81. tlsl := tls.NewListener(m.Match(cmux.Any()), tlscfg)
  82. // TODO: add debug flag; enable logging when debug flag is set
  83. httpmux := http.NewServeMux()
  84. httpmux.Handle("/v3alpha/", gwmux)
  85. httpmux.Handle("/", handler)
  86. srv := &http.Server{
  87. Handler: httpmux,
  88. TLSConfig: tlscfg,
  89. ErrorLog: logger, // do not log user error
  90. }
  91. go func() { plog.Fatal(srv.Serve(tlsl)) }()
  92. plog.Infof("serving client requests on %s", sctx.host)
  93. }
  94. return m.Serve()
  95. }
  96. // grpcHandlerFunc returns an http.Handler that delegates to grpcServer on incoming gRPC
  97. // connections or otherHandler otherwise. Copied from cockroachdb.
  98. func grpcHandlerFunc(grpcServer *grpc.Server, otherHandler http.Handler) http.Handler {
  99. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  100. if r.ProtoMajor == 2 && strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
  101. grpcServer.ServeHTTP(w, r)
  102. } else {
  103. otherHandler.ServeHTTP(w, r)
  104. }
  105. })
  106. }
  107. func servePeerHTTP(l net.Listener, handler http.Handler) error {
  108. logger := defaultLog.New(ioutil.Discard, "etcdhttp", 0)
  109. // TODO: add debug flag; enable logging when debug flag is set
  110. srv := &http.Server{
  111. Handler: handler,
  112. ReadTimeout: 5 * time.Minute,
  113. ErrorLog: logger, // do not log user error
  114. }
  115. return srv.Serve(l)
  116. }
  117. func registerGateway(addr string, opts []grpc.DialOption) (*gw.ServeMux, error) {
  118. gwmux := gw.NewServeMux()
  119. err := pb.RegisterKVHandlerFromEndpoint(context.Background(), gwmux, addr, opts)
  120. if err != nil {
  121. return nil, err
  122. }
  123. err = pb.RegisterWatchHandlerFromEndpoint(context.Background(), gwmux, addr, opts)
  124. if err != nil {
  125. return nil, err
  126. }
  127. err = pb.RegisterLeaseHandlerFromEndpoint(context.Background(), gwmux, addr, opts)
  128. if err != nil {
  129. return nil, err
  130. }
  131. err = pb.RegisterClusterHandlerFromEndpoint(context.Background(), gwmux, addr, opts)
  132. if err != nil {
  133. return nil, err
  134. }
  135. err = pb.RegisterMaintenanceHandlerFromEndpoint(context.Background(), gwmux, addr, opts)
  136. if err != nil {
  137. return nil, err
  138. }
  139. err = pb.RegisterAuthHandlerFromEndpoint(context.Background(), gwmux, addr, opts)
  140. if err != nil {
  141. return nil, err
  142. }
  143. return gwmux, nil
  144. }