serve.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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. if otherHandler == nil {
  104. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  105. grpcServer.ServeHTTP(w, r)
  106. })
  107. }
  108. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  109. if r.ProtoMajor == 2 && strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
  110. grpcServer.ServeHTTP(w, r)
  111. } else {
  112. otherHandler.ServeHTTP(w, r)
  113. }
  114. })
  115. }
  116. func servePeerHTTP(l net.Listener, handler http.Handler) error {
  117. logger := defaultLog.New(ioutil.Discard, "etcdhttp", 0)
  118. // TODO: add debug flag; enable logging when debug flag is set
  119. srv := &http.Server{
  120. Handler: handler,
  121. ReadTimeout: 5 * time.Minute,
  122. ErrorLog: logger, // do not log user error
  123. }
  124. return srv.Serve(l)
  125. }
  126. func (sctx *serveCtx) registerGateway(opts []grpc.DialOption) (*gw.ServeMux, error) {
  127. ctx := sctx.ctx
  128. addr := sctx.l.Addr().String()
  129. gwmux := gw.NewServeMux()
  130. err := pb.RegisterKVHandlerFromEndpoint(ctx, gwmux, addr, opts)
  131. if err != nil {
  132. return nil, err
  133. }
  134. err = pb.RegisterWatchHandlerFromEndpoint(ctx, gwmux, addr, opts)
  135. if err != nil {
  136. return nil, err
  137. }
  138. err = pb.RegisterLeaseHandlerFromEndpoint(ctx, gwmux, addr, opts)
  139. if err != nil {
  140. return nil, err
  141. }
  142. err = pb.RegisterClusterHandlerFromEndpoint(ctx, gwmux, addr, opts)
  143. if err != nil {
  144. return nil, err
  145. }
  146. err = pb.RegisterMaintenanceHandlerFromEndpoint(ctx, gwmux, addr, opts)
  147. if err != nil {
  148. return nil, err
  149. }
  150. err = pb.RegisterAuthHandlerFromEndpoint(ctx, gwmux, addr, opts)
  151. if err != nil {
  152. return nil, err
  153. }
  154. return gwmux, nil
  155. }
  156. func (sctx *serveCtx) createMux(gwmux *gw.ServeMux, handler http.Handler) *http.ServeMux {
  157. httpmux := http.NewServeMux()
  158. for path, h := range sctx.userHandlers {
  159. httpmux.Handle(path, h)
  160. }
  161. httpmux.Handle("/v3alpha/", gwmux)
  162. if handler != nil {
  163. httpmux.Handle("/", handler)
  164. }
  165. return httpmux
  166. }
  167. func (sctx *serveCtx) registerPprof() {
  168. f := func(s string, h http.Handler) {
  169. if sctx.userHandlers[s] != nil {
  170. plog.Warningf("path %s already registered by user handler", s)
  171. return
  172. }
  173. sctx.userHandlers[s] = h
  174. }
  175. f(pprofPrefix+"/", http.HandlerFunc(pprof.Index))
  176. f(pprofPrefix+"/profile", http.HandlerFunc(pprof.Profile))
  177. f(pprofPrefix+"/symbol", http.HandlerFunc(pprof.Symbol))
  178. f(pprofPrefix+"/cmdline", http.HandlerFunc(pprof.Cmdline))
  179. f(pprofPrefix+"/trace", http.HandlerFunc(pprof.Trace))
  180. f(pprofPrefix+"/heap", pprof.Handler("heap"))
  181. f(pprofPrefix+"/goroutine", pprof.Handler("goroutine"))
  182. f(pprofPrefix+"/threadcreate", pprof.Handler("threadcreate"))
  183. f(pprofPrefix+"/block", pprof.Handler("block"))
  184. }