etcd.go 14 KB

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