serve.go 7.1 KB

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