serve.go 6.2 KB

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