serve.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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 etcdmain
  15. import (
  16. "crypto/tls"
  17. "io/ioutil"
  18. defaultLog "log"
  19. "net"
  20. "net/http"
  21. "strings"
  22. "time"
  23. "github.com/coreos/etcd/etcdserver"
  24. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  25. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  26. "github.com/cockroachdb/cmux"
  27. gw "github.com/gengo/grpc-gateway/runtime"
  28. "golang.org/x/net/context"
  29. "google.golang.org/grpc"
  30. "google.golang.org/grpc/credentials"
  31. )
  32. type serveCtx struct {
  33. l net.Listener
  34. host string
  35. secure bool
  36. insecure bool
  37. }
  38. // serve accepts incoming connections on the listener l,
  39. // creating a new service goroutine for each. The service goroutines
  40. // read requests and then call handler to reply to them.
  41. func serve(sctx *serveCtx, s *etcdserver.EtcdServer, tlscfg *tls.Config, handler http.Handler) error {
  42. logger := defaultLog.New(ioutil.Discard, "etcdhttp", 0)
  43. <-s.ReadyNotify()
  44. plog.Info("ready to serve client requests")
  45. m := cmux.New(sctx.l)
  46. if sctx.insecure {
  47. gs := v3rpc.Server(s, nil)
  48. grpcl := m.Match(cmux.HTTP2())
  49. go func() { plog.Fatal(gs.Serve(grpcl)) }()
  50. opts := []grpc.DialOption{
  51. grpc.WithInsecure(),
  52. }
  53. gwmux, err := registerGateway(sctx.l.Addr().String(), opts)
  54. if err != nil {
  55. return err
  56. }
  57. httpmux := http.NewServeMux()
  58. httpmux.Handle("/v3alpha/", gwmux)
  59. httpmux.Handle("/", handler)
  60. srvhttp := &http.Server{
  61. Handler: httpmux,
  62. ErrorLog: logger, // do not log user error
  63. }
  64. httpl := m.Match(cmux.HTTP1())
  65. go func() { plog.Fatal(srvhttp.Serve(httpl)) }()
  66. plog.Noticef("serving insecure client requests on %s, this is strongly discouraged!", sctx.host)
  67. }
  68. if sctx.secure {
  69. gs := v3rpc.Server(s, tlscfg)
  70. handler = grpcHandlerFunc(gs, handler)
  71. dtls := *tlscfg
  72. // trust local server
  73. dtls.InsecureSkipVerify = true
  74. creds := credentials.NewTLS(&dtls)
  75. opts := []grpc.DialOption{grpc.WithTransportCredentials(creds)}
  76. gwmux, err := registerGateway(sctx.l.Addr().String(), opts)
  77. if err != nil {
  78. return err
  79. }
  80. tlsl := tls.NewListener(m.Match(cmux.Any()), tlscfg)
  81. // TODO: add debug flag; enable logging when debug flag is set
  82. httpmux := http.NewServeMux()
  83. httpmux.Handle("/v3alpha/", gwmux)
  84. httpmux.Handle("/", handler)
  85. srv := &http.Server{
  86. Handler: httpmux,
  87. TLSConfig: tlscfg,
  88. ErrorLog: logger, // do not log user error
  89. }
  90. go func() { plog.Fatal(srv.Serve(tlsl)) }()
  91. plog.Infof("serving client requests on %s", sctx.host)
  92. }
  93. return m.Serve()
  94. }
  95. // grpcHandlerFunc returns an http.Handler that delegates to grpcServer on incoming gRPC
  96. // connections or otherHandler otherwise. Copied from cockroachdb.
  97. func grpcHandlerFunc(grpcServer *grpc.Server, otherHandler http.Handler) http.Handler {
  98. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  99. if r.ProtoMajor == 2 && strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
  100. grpcServer.ServeHTTP(w, r)
  101. } else {
  102. otherHandler.ServeHTTP(w, r)
  103. }
  104. })
  105. }
  106. func servePeerHTTP(l net.Listener, handler http.Handler) error {
  107. logger := defaultLog.New(ioutil.Discard, "etcdhttp", 0)
  108. // TODO: add debug flag; enable logging when debug flag is set
  109. srv := &http.Server{
  110. Handler: handler,
  111. ReadTimeout: 5 * time.Minute,
  112. ErrorLog: logger, // do not log user error
  113. }
  114. return srv.Serve(l)
  115. }
  116. func registerGateway(addr string, opts []grpc.DialOption) (*gw.ServeMux, error) {
  117. gwmux := gw.NewServeMux()
  118. err := pb.RegisterKVHandlerFromEndpoint(context.Background(), gwmux, addr, opts)
  119. if err != nil {
  120. return nil, err
  121. }
  122. err = pb.RegisterWatchHandlerFromEndpoint(context.Background(), gwmux, addr, opts)
  123. if err != nil {
  124. return nil, err
  125. }
  126. err = pb.RegisterLeaseHandlerFromEndpoint(context.Background(), gwmux, addr, opts)
  127. if err != nil {
  128. return nil, err
  129. }
  130. err = pb.RegisterClusterHandlerFromEndpoint(context.Background(), gwmux, addr, opts)
  131. if err != nil {
  132. return nil, err
  133. }
  134. err = pb.RegisterMaintenanceHandlerFromEndpoint(context.Background(), gwmux, addr, opts)
  135. if err != nil {
  136. return nil, err
  137. }
  138. err = pb.RegisterAuthHandlerFromEndpoint(context.Background(), gwmux, addr, opts)
  139. if err != nil {
  140. return nil, err
  141. }
  142. return gwmux, nil
  143. }