etcd.go 12 KB

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