serve.go 7.0 KB

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