serve.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. "context"
  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/coreos/etcd/pkg/transport"
  34. gw "github.com/grpc-ecosystem/grpc-gateway/runtime"
  35. "github.com/soheilhy/cmux"
  36. "github.com/tmc/grpc-websocket-proxy/wsproxy"
  37. "golang.org/x/net/trace"
  38. "google.golang.org/grpc"
  39. "google.golang.org/grpc/credentials"
  40. )
  41. type serveCtx struct {
  42. l net.Listener
  43. addr string
  44. secure bool
  45. insecure bool
  46. ctx context.Context
  47. cancel context.CancelFunc
  48. userHandlers map[string]http.Handler
  49. serviceRegister func(*grpc.Server)
  50. grpcServerC chan *grpc.Server
  51. }
  52. func newServeCtx() *serveCtx {
  53. ctx, cancel := context.WithCancel(context.Background())
  54. return &serveCtx{ctx: ctx, cancel: cancel, userHandlers: make(map[string]http.Handler),
  55. grpcServerC: make(chan *grpc.Server, 2), // in case sctx.insecure,sctx.secure true
  56. }
  57. }
  58. // serve accepts incoming connections on the listener l,
  59. // creating a new service goroutine for each. The service goroutines
  60. // read requests and then call handler to reply to them.
  61. func (sctx *serveCtx) serve(
  62. s *etcdserver.EtcdServer,
  63. tlsinfo *transport.TLSInfo,
  64. handler http.Handler,
  65. errHandler func(error),
  66. gopts ...grpc.ServerOption) error {
  67. logger := defaultLog.New(ioutil.Discard, "etcdhttp", 0)
  68. <-s.ReadyNotify()
  69. plog.Info("ready to serve client requests")
  70. m := cmux.New(sctx.l)
  71. v3c := v3client.New(s)
  72. servElection := v3election.NewElectionServer(v3c)
  73. servLock := v3lock.NewLockServer(v3c)
  74. if sctx.insecure {
  75. gs := v3rpc.Server(s, nil, gopts...)
  76. sctx.grpcServerC <- gs
  77. v3electionpb.RegisterElectionServer(gs, servElection)
  78. v3lockpb.RegisterLockServer(gs, servLock)
  79. if sctx.serviceRegister != nil {
  80. sctx.serviceRegister(gs)
  81. }
  82. grpcl := m.Match(cmux.HTTP2())
  83. go func() { errHandler(gs.Serve(grpcl)) }()
  84. opts := []grpc.DialOption{
  85. grpc.WithInsecure(),
  86. }
  87. gwmux, err := sctx.registerGateway(opts)
  88. if err != nil {
  89. return err
  90. }
  91. httpmux := sctx.createMux(gwmux, handler)
  92. srvhttp := &http.Server{
  93. Handler: wrapMux(httpmux),
  94. ErrorLog: logger, // do not log user error
  95. }
  96. httpl := m.Match(cmux.HTTP1())
  97. go func() { errHandler(srvhttp.Serve(httpl)) }()
  98. plog.Noticef("serving insecure client requests on %s, this is strongly discouraged!", sctx.l.Addr().String())
  99. }
  100. if sctx.secure {
  101. tlscfg, tlsErr := tlsinfo.ServerConfig()
  102. if tlsErr != nil {
  103. return tlsErr
  104. }
  105. gs := v3rpc.Server(s, tlscfg, gopts...)
  106. sctx.grpcServerC <- gs
  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, lerr := transport.NewTLSListener(m.Match(cmux.Any()), tlsinfo)
  123. if lerr != nil {
  124. return lerr
  125. }
  126. // TODO: add debug flag; enable logging when debug flag is set
  127. httpmux := sctx.createMux(gwmux, handler)
  128. srv := &http.Server{
  129. Handler: wrapMux(httpmux),
  130. TLSConfig: tlscfg,
  131. ErrorLog: logger, // do not log user error
  132. }
  133. go func() { errHandler(srv.Serve(tlsl)) }()
  134. plog.Infof("serving client requests on %s", sctx.l.Addr().String())
  135. }
  136. close(sctx.grpcServerC)
  137. return m.Serve()
  138. }
  139. // grpcHandlerFunc returns an http.Handler that delegates to grpcServer on incoming gRPC
  140. // connections or otherHandler otherwise. Given in gRPC docs.
  141. func grpcHandlerFunc(grpcServer *grpc.Server, otherHandler http.Handler) http.Handler {
  142. if otherHandler == nil {
  143. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  144. grpcServer.ServeHTTP(w, r)
  145. })
  146. }
  147. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  148. if r.ProtoMajor == 2 && strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
  149. grpcServer.ServeHTTP(w, r)
  150. } else {
  151. otherHandler.ServeHTTP(w, r)
  152. }
  153. })
  154. }
  155. type registerHandlerFunc func(context.Context, *gw.ServeMux, *grpc.ClientConn) error
  156. func (sctx *serveCtx) registerGateway(opts []grpc.DialOption) (*gw.ServeMux, error) {
  157. ctx := sctx.ctx
  158. conn, err := grpc.DialContext(ctx, sctx.addr, opts...)
  159. if err != nil {
  160. return nil, err
  161. }
  162. gwmux := gw.NewServeMux()
  163. handlers := []registerHandlerFunc{
  164. etcdservergw.RegisterKVHandler,
  165. etcdservergw.RegisterWatchHandler,
  166. etcdservergw.RegisterLeaseHandler,
  167. etcdservergw.RegisterClusterHandler,
  168. etcdservergw.RegisterMaintenanceHandler,
  169. etcdservergw.RegisterAuthHandler,
  170. v3lockgw.RegisterLockHandler,
  171. v3electiongw.RegisterElectionHandler,
  172. }
  173. for _, h := range handlers {
  174. if err := h(ctx, gwmux, conn); err != nil {
  175. return nil, err
  176. }
  177. }
  178. go func() {
  179. <-ctx.Done()
  180. if cerr := conn.Close(); cerr != nil {
  181. plog.Warningf("failed to close conn to %s: %v", sctx.l.Addr().String(), cerr)
  182. }
  183. }()
  184. return gwmux, nil
  185. }
  186. func (sctx *serveCtx) createMux(gwmux *gw.ServeMux, handler http.Handler) *http.ServeMux {
  187. httpmux := http.NewServeMux()
  188. for path, h := range sctx.userHandlers {
  189. httpmux.Handle(path, h)
  190. }
  191. httpmux.Handle(
  192. "/v3beta/",
  193. wsproxy.WebsocketProxy(
  194. gwmux,
  195. wsproxy.WithRequestMutator(
  196. // Default to the POST method for streams
  197. func(incoming *http.Request, outgoing *http.Request) *http.Request {
  198. outgoing.Method = "POST"
  199. return outgoing
  200. },
  201. ),
  202. ),
  203. )
  204. if handler != nil {
  205. httpmux.Handle("/", handler)
  206. }
  207. return httpmux
  208. }
  209. // wraps HTTP multiplexer to mute requests to /v3alpha
  210. // TODO: deprecate this in 3.4 release
  211. func wrapMux(mux *http.ServeMux) http.Handler { return &v3alphaMutator{mux: mux} }
  212. type v3alphaMutator struct {
  213. mux *http.ServeMux
  214. }
  215. func (m *v3alphaMutator) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  216. if req != nil && req.URL != nil && strings.HasPrefix(req.URL.Path, "/v3alpha/") {
  217. req.URL.Path = strings.Replace(req.URL.Path, "/v3alpha/", "/v3beta/", 1)
  218. }
  219. m.mux.ServeHTTP(rw, req)
  220. }
  221. func (sctx *serveCtx) registerUserHandler(s string, h http.Handler) {
  222. if sctx.userHandlers[s] != nil {
  223. plog.Warningf("path %s already registered by user handler", s)
  224. return
  225. }
  226. sctx.userHandlers[s] = h
  227. }
  228. func (sctx *serveCtx) registerPprof() {
  229. for p, h := range debugutil.PProfHandlers() {
  230. sctx.registerUserHandler(p, h)
  231. }
  232. }
  233. func (sctx *serveCtx) registerTrace() {
  234. reqf := func(w http.ResponseWriter, r *http.Request) { trace.Render(w, r, true) }
  235. sctx.registerUserHandler("/debug/requests", http.HandlerFunc(reqf))
  236. evf := func(w http.ResponseWriter, r *http.Request) { trace.RenderEvents(w, r, true) }
  237. sctx.registerUserHandler("/debug/events", http.HandlerFunc(evf))
  238. }