etcd.go 13 KB

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