etcd.go 15 KB

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