serve.go 7.0 KB

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