serve.go 5.8 KB

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