serve.go 7.0 KB

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