serve.go 6.8 KB

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