serve.go 8.1 KB

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