etcd.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. // Copyright 2016 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. "crypto/tls"
  18. "fmt"
  19. "io/ioutil"
  20. defaultLog "log"
  21. "net"
  22. "net/http"
  23. "net/url"
  24. "sync"
  25. "time"
  26. "github.com/coreos/etcd/etcdserver"
  27. "github.com/coreos/etcd/etcdserver/api/etcdhttp"
  28. "github.com/coreos/etcd/etcdserver/api/v2http"
  29. "github.com/coreos/etcd/etcdserver/api/v2v3"
  30. "github.com/coreos/etcd/etcdserver/api/v3client"
  31. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  32. "github.com/coreos/etcd/pkg/cors"
  33. "github.com/coreos/etcd/pkg/debugutil"
  34. runtimeutil "github.com/coreos/etcd/pkg/runtime"
  35. "github.com/coreos/etcd/pkg/transport"
  36. "github.com/coreos/etcd/pkg/types"
  37. "github.com/coreos/etcd/rafthttp"
  38. "github.com/coreos/pkg/capnslog"
  39. "github.com/soheilhy/cmux"
  40. "google.golang.org/grpc"
  41. )
  42. var plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "embed")
  43. const (
  44. // internal fd usage includes disk usage and transport usage.
  45. // To read/write snapshot, snap pkg needs 1. In normal case, wal pkg needs
  46. // at most 2 to read/lock/write WALs. One case that it needs to 2 is to
  47. // read all logs after some snapshot index, which locates at the end of
  48. // the second last and the head of the last. For purging, it needs to read
  49. // directory, so it needs 1. For fd monitor, it needs 1.
  50. // For transport, rafthttp builds two long-polling connections and at most
  51. // four temporary connections with each member. There are at most 9 members
  52. // in a cluster, so it should reserve 96.
  53. // For the safety, we set the total reserved number to 150.
  54. reservedInternalFDNum = 150
  55. )
  56. // Etcd contains a running etcd server and its listeners.
  57. type Etcd struct {
  58. Peers []*peerListener
  59. Clients []net.Listener
  60. metricsListeners []net.Listener
  61. Server *etcdserver.EtcdServer
  62. cfg Config
  63. stopc chan struct{}
  64. errc chan error
  65. sctxs map[string]*serveCtx
  66. closeOnce sync.Once
  67. }
  68. type peerListener struct {
  69. net.Listener
  70. serve func() error
  71. close func(context.Context) error
  72. }
  73. // StartEtcd launches the etcd server and HTTP handlers for client/server communication.
  74. // The returned Etcd.Server is not guaranteed to have joined the cluster. Wait
  75. // on the Etcd.Server.ReadyNotify() channel to know when it completes and is ready for use.
  76. func StartEtcd(inCfg *Config) (e *Etcd, err error) {
  77. if err = inCfg.Validate(); err != nil {
  78. return nil, err
  79. }
  80. serving := false
  81. e = &Etcd{cfg: *inCfg, stopc: make(chan struct{})}
  82. cfg := &e.cfg
  83. defer func() {
  84. if e == nil || err == nil {
  85. return
  86. }
  87. if !serving {
  88. // errored before starting gRPC server for serveCtx.grpcServerC
  89. for _, sctx := range e.sctxs {
  90. close(sctx.grpcServerC)
  91. }
  92. }
  93. e.Close()
  94. e = nil
  95. }()
  96. if e.Peers, err = startPeerListeners(cfg); err != nil {
  97. return
  98. }
  99. if e.sctxs, err = startClientListeners(cfg); err != nil {
  100. return
  101. }
  102. for _, sctx := range e.sctxs {
  103. e.Clients = append(e.Clients, sctx.l)
  104. }
  105. var (
  106. urlsmap types.URLsMap
  107. token string
  108. )
  109. if !isMemberInitialized(cfg) {
  110. urlsmap, token, err = cfg.PeerURLsMapAndToken("etcd")
  111. if err != nil {
  112. return e, fmt.Errorf("error setting up initial cluster: %v", err)
  113. }
  114. }
  115. srvcfg := etcdserver.ServerConfig{
  116. Name: cfg.Name,
  117. ClientURLs: cfg.ACUrls,
  118. PeerURLs: cfg.APUrls,
  119. DataDir: cfg.Dir,
  120. DedicatedWALDir: cfg.WalDir,
  121. SnapCount: cfg.SnapCount,
  122. MaxSnapFiles: cfg.MaxSnapFiles,
  123. MaxWALFiles: cfg.MaxWalFiles,
  124. InitialPeerURLsMap: urlsmap,
  125. InitialClusterToken: token,
  126. DiscoveryURL: cfg.Durl,
  127. DiscoveryProxy: cfg.Dproxy,
  128. NewCluster: cfg.IsNewCluster(),
  129. ForceNewCluster: cfg.ForceNewCluster,
  130. PeerTLSInfo: cfg.PeerTLSInfo,
  131. TickMs: cfg.TickMs,
  132. ElectionTicks: cfg.ElectionTicks(),
  133. AutoCompactionRetention: cfg.AutoCompactionRetention,
  134. AutoCompactionMode: cfg.AutoCompactionMode,
  135. QuotaBackendBytes: cfg.QuotaBackendBytes,
  136. MaxTxnOps: cfg.MaxTxnOps,
  137. MaxRequestBytes: cfg.MaxRequestBytes,
  138. StrictReconfigCheck: cfg.StrictReconfigCheck,
  139. ClientCertAuthEnabled: cfg.ClientTLSInfo.ClientCertAuth,
  140. AuthToken: cfg.AuthToken,
  141. CorruptCheckTime: cfg.ExperimentalCorruptCheckTime,
  142. }
  143. if e.Server, err = etcdserver.NewServer(srvcfg); err != nil {
  144. return
  145. }
  146. // buffer channel so goroutines on closed connections won't wait forever
  147. e.errc = make(chan error, len(e.Peers)+len(e.Clients)+2*len(e.sctxs))
  148. e.Server.Start()
  149. // configure peer handlers after rafthttp.Transport started
  150. ph := etcdhttp.NewPeerHandler(e.Server)
  151. var peerTLScfg *tls.Config
  152. if !cfg.PeerTLSInfo.Empty() {
  153. if peerTLScfg, err = cfg.PeerTLSInfo.ServerConfig(); err != nil {
  154. return
  155. }
  156. }
  157. for _, p := range e.Peers {
  158. gs := v3rpc.Server(e.Server, peerTLScfg)
  159. m := cmux.New(p.Listener)
  160. go gs.Serve(m.Match(cmux.HTTP2()))
  161. srv := &http.Server{
  162. Handler: grpcHandlerFunc(gs, ph),
  163. ReadTimeout: 5 * time.Minute,
  164. ErrorLog: defaultLog.New(ioutil.Discard, "", 0), // do not log user error
  165. }
  166. go srv.Serve(m.Match(cmux.Any()))
  167. p.serve = func() error { return m.Serve() }
  168. p.close = func(ctx context.Context) error {
  169. // gracefully shutdown http.Server
  170. // close open listeners, idle connections
  171. // until context cancel or time-out
  172. e.stopGRPCServer(gs)
  173. return srv.Shutdown(ctx)
  174. }
  175. }
  176. if err = e.serve(); err != nil {
  177. return
  178. }
  179. serving = true
  180. return
  181. }
  182. // Config returns the current configuration.
  183. func (e *Etcd) Config() Config {
  184. return e.cfg
  185. }
  186. func (e *Etcd) Close() {
  187. e.closeOnce.Do(func() { close(e.stopc) })
  188. for _, sctx := range e.sctxs {
  189. for gs := range sctx.grpcServerC {
  190. e.stopGRPCServer(gs)
  191. }
  192. }
  193. for _, sctx := range e.sctxs {
  194. sctx.cancel()
  195. }
  196. for i := range e.Clients {
  197. if e.Clients[i] != nil {
  198. e.Clients[i].Close()
  199. }
  200. }
  201. for i := range e.metricsListeners {
  202. e.metricsListeners[i].Close()
  203. }
  204. // close rafthttp transports
  205. if e.Server != nil {
  206. e.Server.Stop()
  207. }
  208. // close all idle connections in peer handler (wait up to 1-second)
  209. for i := range e.Peers {
  210. if e.Peers[i] != nil && e.Peers[i].close != nil {
  211. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  212. e.Peers[i].close(ctx)
  213. cancel()
  214. }
  215. }
  216. }
  217. func (e *Etcd) stopGRPCServer(gs *grpc.Server) {
  218. timeout := 2 * time.Second
  219. if e.Server != nil {
  220. timeout = e.Server.Cfg.ReqTimeout()
  221. }
  222. ch := make(chan struct{})
  223. go func() {
  224. defer close(ch)
  225. // close listeners to stop accepting new connections,
  226. // will block on any existing transports
  227. gs.GracefulStop()
  228. }()
  229. // wait until all pending RPCs are finished
  230. select {
  231. case <-ch:
  232. case <-time.After(timeout):
  233. // took too long, manually close open transports
  234. // e.g. watch streams
  235. gs.Stop()
  236. // concurrent GracefulStop should be interrupted
  237. <-ch
  238. }
  239. }
  240. func (e *Etcd) Err() <-chan error { return e.errc }
  241. func startPeerListeners(cfg *Config) (peers []*peerListener, err error) {
  242. if err = cfg.PeerSelfCert(); err != nil {
  243. plog.Fatalf("could not get certs (%v)", err)
  244. }
  245. if !cfg.PeerTLSInfo.Empty() {
  246. plog.Infof("peerTLS: %s", cfg.PeerTLSInfo)
  247. }
  248. peers = make([]*peerListener, len(cfg.LPUrls))
  249. defer func() {
  250. if err == nil {
  251. return
  252. }
  253. for i := range peers {
  254. if peers[i] != nil && peers[i].close != nil {
  255. plog.Info("stopping listening for peers on ", cfg.LPUrls[i].String())
  256. peers[i].close(context.Background())
  257. }
  258. }
  259. }()
  260. for i, u := range cfg.LPUrls {
  261. if u.Scheme == "http" {
  262. if !cfg.PeerTLSInfo.Empty() {
  263. plog.Warningf("The scheme of peer url %s is HTTP while peer key/cert files are presented. Ignored peer key/cert files.", u.String())
  264. }
  265. if cfg.PeerTLSInfo.ClientCertAuth {
  266. plog.Warningf("The scheme of peer url %s is HTTP while client cert auth (--peer-client-cert-auth) is enabled. Ignored client cert auth for this url.", u.String())
  267. }
  268. }
  269. peers[i] = &peerListener{close: func(context.Context) error { return nil }}
  270. peers[i].Listener, err = rafthttp.NewListener(u, &cfg.PeerTLSInfo)
  271. if err != nil {
  272. return nil, err
  273. }
  274. // once serve, overwrite with 'http.Server.Shutdown'
  275. peers[i].close = func(context.Context) error {
  276. return peers[i].Listener.Close()
  277. }
  278. plog.Info("listening for peers on ", u.String())
  279. }
  280. return peers, nil
  281. }
  282. func startClientListeners(cfg *Config) (sctxs map[string]*serveCtx, err error) {
  283. if err = cfg.ClientSelfCert(); err != nil {
  284. plog.Fatalf("could not get certs (%v)", err)
  285. }
  286. if cfg.EnablePprof {
  287. plog.Infof("pprof is enabled under %s", debugutil.HTTPPrefixPProf)
  288. }
  289. sctxs = make(map[string]*serveCtx)
  290. for _, u := range cfg.LCUrls {
  291. sctx := newServeCtx()
  292. if u.Scheme == "http" || u.Scheme == "unix" {
  293. if !cfg.ClientTLSInfo.Empty() {
  294. plog.Warningf("The scheme of client url %s is HTTP while peer key/cert files are presented. Ignored key/cert files.", u.String())
  295. }
  296. if cfg.ClientTLSInfo.ClientCertAuth {
  297. plog.Warningf("The scheme of client url %s is HTTP while client cert auth (--client-cert-auth) is enabled. Ignored client cert auth for this url.", u.String())
  298. }
  299. }
  300. if (u.Scheme == "https" || u.Scheme == "unixs") && cfg.ClientTLSInfo.Empty() {
  301. return nil, fmt.Errorf("TLS key/cert (--cert-file, --key-file) must be provided for client url %s with HTTPs scheme", u.String())
  302. }
  303. proto := "tcp"
  304. addr := u.Host
  305. if u.Scheme == "unix" || u.Scheme == "unixs" {
  306. proto = "unix"
  307. addr = u.Host + u.Path
  308. }
  309. sctx.secure = u.Scheme == "https" || u.Scheme == "unixs"
  310. sctx.insecure = !sctx.secure
  311. if oldctx := sctxs[addr]; oldctx != nil {
  312. oldctx.secure = oldctx.secure || sctx.secure
  313. oldctx.insecure = oldctx.insecure || sctx.insecure
  314. continue
  315. }
  316. if sctx.l, err = net.Listen(proto, addr); err != nil {
  317. return nil, err
  318. }
  319. // net.Listener will rewrite ipv4 0.0.0.0 to ipv6 [::], breaking
  320. // hosts that disable ipv6. So, use the address given by the user.
  321. sctx.addr = addr
  322. if fdLimit, fderr := runtimeutil.FDLimit(); fderr == nil {
  323. if fdLimit <= reservedInternalFDNum {
  324. plog.Fatalf("file descriptor limit[%d] of etcd process is too low, and should be set higher than %d to ensure internal usage", fdLimit, reservedInternalFDNum)
  325. }
  326. sctx.l = transport.LimitListener(sctx.l, int(fdLimit-reservedInternalFDNum))
  327. }
  328. if proto == "tcp" {
  329. if sctx.l, err = transport.NewKeepAliveListener(sctx.l, "tcp", nil); err != nil {
  330. return nil, err
  331. }
  332. }
  333. plog.Info("listening for client requests on ", u.Host)
  334. defer func() {
  335. if err != nil {
  336. sctx.l.Close()
  337. plog.Info("stopping listening for client requests on ", u.Host)
  338. }
  339. }()
  340. for k := range cfg.UserHandlers {
  341. sctx.userHandlers[k] = cfg.UserHandlers[k]
  342. }
  343. sctx.serviceRegister = cfg.ServiceRegister
  344. if cfg.EnablePprof || cfg.Debug {
  345. sctx.registerPprof()
  346. }
  347. if cfg.Debug {
  348. sctx.registerTrace()
  349. }
  350. sctxs[addr] = sctx
  351. }
  352. return sctxs, nil
  353. }
  354. func (e *Etcd) serve() (err error) {
  355. if !e.cfg.ClientTLSInfo.Empty() {
  356. plog.Infof("ClientTLS: %s", e.cfg.ClientTLSInfo)
  357. }
  358. if e.cfg.CorsInfo.String() != "" {
  359. plog.Infof("cors = %s", e.cfg.CorsInfo)
  360. }
  361. // Start the peer server in a goroutine
  362. for _, pl := range e.Peers {
  363. go func(l *peerListener) {
  364. e.errHandler(l.serve())
  365. }(pl)
  366. }
  367. // Start a client server goroutine for each listen address
  368. var h http.Handler
  369. if e.Config().EnableV2 {
  370. if len(e.Config().ExperimentalEnableV2V3) > 0 {
  371. srv := v2v3.NewServer(v3client.New(e.Server), e.cfg.ExperimentalEnableV2V3)
  372. h = v2http.NewClientHandler(srv, e.Server.Cfg.ReqTimeout())
  373. } else {
  374. h = v2http.NewClientHandler(e.Server, e.Server.Cfg.ReqTimeout())
  375. }
  376. } else {
  377. mux := http.NewServeMux()
  378. etcdhttp.HandleBasic(mux, e.Server)
  379. h = mux
  380. }
  381. h = http.Handler(&cors.CORSHandler{Handler: h, Info: e.cfg.CorsInfo})
  382. for _, sctx := range e.sctxs {
  383. go func(s *serveCtx) {
  384. e.errHandler(s.serve(e.Server, &e.cfg.ClientTLSInfo, h, e.errHandler))
  385. }(sctx)
  386. }
  387. if len(e.cfg.ListenMetricsUrls) > 0 {
  388. metricsMux := http.NewServeMux()
  389. etcdhttp.HandleMetricsHealth(metricsMux, e.Server)
  390. for _, murl := range e.cfg.ListenMetricsUrls {
  391. tlsInfo := &e.cfg.ClientTLSInfo
  392. if murl.Scheme == "http" {
  393. tlsInfo = nil
  394. }
  395. ml, err := transport.NewListener(murl.Host, murl.Scheme, tlsInfo)
  396. if err != nil {
  397. return err
  398. }
  399. e.metricsListeners = append(e.metricsListeners, ml)
  400. go func(u url.URL, ln net.Listener) {
  401. plog.Info("listening for metrics on ", u.String())
  402. e.errHandler(http.Serve(ln, metricsMux))
  403. }(murl, ml)
  404. }
  405. }
  406. return nil
  407. }
  408. func (e *Etcd) errHandler(err error) {
  409. select {
  410. case <-e.stopc:
  411. return
  412. default:
  413. }
  414. select {
  415. case <-e.stopc:
  416. case e.errc <- err:
  417. }
  418. }