serve.go 7.9 KB

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