serve.go 6.8 KB

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