etcd.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. "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. "google.golang.org/grpc"
  37. "google.golang.org/grpc/keepalive"
  38. )
  39. var plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "embed")
  40. const (
  41. // internal fd usage includes disk usage and transport usage.
  42. // To read/write snapshot, snap pkg needs 1. In normal case, wal pkg needs
  43. // at most 2 to read/lock/write WALs. One case that it needs to 2 is to
  44. // read all logs after some snapshot index, which locates at the end of
  45. // the second last and the head of the last. For purging, it needs to read
  46. // directory, so it needs 1. For fd monitor, it needs 1.
  47. // For transport, rafthttp builds two long-polling connections and at most
  48. // four temporary connections with each member. There are at most 9 members
  49. // in a cluster, so it should reserve 96.
  50. // For the safety, we set the total reserved number to 150.
  51. reservedInternalFDNum = 150
  52. )
  53. // Etcd contains a running etcd server and its listeners.
  54. type Etcd struct {
  55. Peers []*peerListener
  56. Clients []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. QuotaBackendBytes: cfg.QuotaBackendBytes,
  131. MaxRequestBytes: cfg.MaxRequestBytes,
  132. StrictReconfigCheck: cfg.StrictReconfigCheck,
  133. ClientCertAuthEnabled: cfg.ClientTLSInfo.ClientCertAuth,
  134. AuthToken: cfg.AuthToken,
  135. Debug: cfg.Debug,
  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 _, p := 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. l := p.Listener
  149. p.serve = func() error { return srv.Serve(l) }
  150. p.close = func(ctx context.Context) error {
  151. // gracefully shutdown http.Server
  152. // close open listeners, idle connections
  153. // until context cancel or time-out
  154. return srv.Shutdown(ctx)
  155. }
  156. }
  157. // buffer channel so goroutines on closed connections won't wait forever
  158. e.errc = make(chan error, len(e.Peers)+len(e.Clients)+2*len(e.sctxs))
  159. e.Server.Start()
  160. if err = e.serve(); err != nil {
  161. return
  162. }
  163. serving = true
  164. return
  165. }
  166. // Config returns the current configuration.
  167. func (e *Etcd) Config() Config {
  168. return e.cfg
  169. }
  170. func (e *Etcd) Close() {
  171. e.closeOnce.Do(func() { close(e.stopc) })
  172. timeout := 2 * time.Second
  173. if e.Server != nil {
  174. timeout = e.Server.Cfg.ReqTimeout()
  175. }
  176. for _, sctx := range e.sctxs {
  177. for gs := range sctx.grpcServerC {
  178. ch := make(chan struct{})
  179. go func() {
  180. defer close(ch)
  181. // close listeners to stop accepting new connections,
  182. // will block on any existing transports
  183. gs.GracefulStop()
  184. }()
  185. // wait until all pending RPCs are finished
  186. select {
  187. case <-ch:
  188. case <-time.After(timeout):
  189. // took too long, manually close open transports
  190. // e.g. watch streams
  191. gs.Stop()
  192. // concurrent GracefulStop should be interrupted
  193. <-ch
  194. }
  195. }
  196. }
  197. for _, sctx := range e.sctxs {
  198. sctx.cancel()
  199. }
  200. for i := range e.Clients {
  201. if e.Clients[i] != nil {
  202. e.Clients[i].Close()
  203. }
  204. }
  205. // close rafthttp transports
  206. if e.Server != nil {
  207. e.Server.Stop()
  208. }
  209. // close all idle connections in peer handler (wait up to 1-second)
  210. for i := range e.Peers {
  211. if e.Peers[i] != nil && e.Peers[i].close != nil {
  212. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  213. e.Peers[i].close(ctx)
  214. cancel()
  215. }
  216. }
  217. }
  218. func (e *Etcd) Err() <-chan error { return e.errc }
  219. func startPeerListeners(cfg *Config) (peers []*peerListener, err error) {
  220. if cfg.PeerAutoTLS && cfg.PeerTLSInfo.Empty() {
  221. phosts := make([]string, len(cfg.LPUrls))
  222. for i, u := range cfg.LPUrls {
  223. phosts[i] = u.Host
  224. }
  225. cfg.PeerTLSInfo, err = transport.SelfCert(filepath.Join(cfg.Dir, "fixtures", "peer"), phosts)
  226. if err != nil {
  227. plog.Fatalf("could not get certs (%v)", err)
  228. }
  229. } else if cfg.PeerAutoTLS {
  230. plog.Warningf("ignoring peer auto TLS since certs given")
  231. }
  232. if !cfg.PeerTLSInfo.Empty() {
  233. plog.Infof("peerTLS: %s", cfg.PeerTLSInfo)
  234. }
  235. peers = make([]*peerListener, len(cfg.LPUrls))
  236. defer func() {
  237. if err == nil {
  238. return
  239. }
  240. for i := range peers {
  241. if peers[i] != nil && peers[i].close != nil {
  242. plog.Info("stopping listening for peers on ", cfg.LPUrls[i].String())
  243. peers[i].close(context.Background())
  244. }
  245. }
  246. }()
  247. for i, u := range cfg.LPUrls {
  248. if u.Scheme == "http" {
  249. if !cfg.PeerTLSInfo.Empty() {
  250. plog.Warningf("The scheme of peer url %s is HTTP while peer key/cert files are presented. Ignored peer key/cert files.", u.String())
  251. }
  252. if cfg.PeerTLSInfo.ClientCertAuth {
  253. 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())
  254. }
  255. }
  256. peers[i] = &peerListener{close: func(context.Context) error { return nil }}
  257. peers[i].Listener, err = rafthttp.NewListener(u, &cfg.PeerTLSInfo)
  258. if err != nil {
  259. return nil, err
  260. }
  261. // once serve, overwrite with 'http.Server.Shutdown'
  262. peers[i].close = func(context.Context) error {
  263. return peers[i].Listener.Close()
  264. }
  265. plog.Info("listening for peers on ", u.String())
  266. }
  267. return peers, nil
  268. }
  269. func startClientListeners(cfg *Config) (sctxs map[string]*serveCtx, err error) {
  270. if cfg.ClientAutoTLS && cfg.ClientTLSInfo.Empty() {
  271. chosts := make([]string, len(cfg.LCUrls))
  272. for i, u := range cfg.LCUrls {
  273. chosts[i] = u.Host
  274. }
  275. cfg.ClientTLSInfo, err = transport.SelfCert(filepath.Join(cfg.Dir, "fixtures", "client"), chosts)
  276. if err != nil {
  277. plog.Fatalf("could not get certs (%v)", err)
  278. }
  279. } else if cfg.ClientAutoTLS {
  280. plog.Warningf("ignoring client auto TLS since certs given")
  281. }
  282. if cfg.EnablePprof {
  283. plog.Infof("pprof is enabled under %s", debugutil.HTTPPrefixPProf)
  284. }
  285. sctxs = make(map[string]*serveCtx)
  286. for _, u := range cfg.LCUrls {
  287. sctx := newServeCtx()
  288. if u.Scheme == "http" || u.Scheme == "unix" {
  289. if !cfg.ClientTLSInfo.Empty() {
  290. plog.Warningf("The scheme of client url %s is HTTP while peer key/cert files are presented. Ignored key/cert files.", u.String())
  291. }
  292. if cfg.ClientTLSInfo.ClientCertAuth {
  293. 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())
  294. }
  295. }
  296. if (u.Scheme == "https" || u.Scheme == "unixs") && cfg.ClientTLSInfo.Empty() {
  297. return nil, fmt.Errorf("TLS key/cert (--cert-file, --key-file) must be provided for client url %s with HTTPs scheme", u.String())
  298. }
  299. proto := "tcp"
  300. addr := u.Host
  301. if u.Scheme == "unix" || u.Scheme == "unixs" {
  302. proto = "unix"
  303. addr = u.Host + u.Path
  304. }
  305. sctx.secure = u.Scheme == "https" || u.Scheme == "unixs"
  306. sctx.insecure = !sctx.secure
  307. if oldctx := sctxs[addr]; oldctx != nil {
  308. oldctx.secure = oldctx.secure || sctx.secure
  309. oldctx.insecure = oldctx.insecure || sctx.insecure
  310. continue
  311. }
  312. if sctx.l, err = net.Listen(proto, addr); err != nil {
  313. return nil, err
  314. }
  315. // net.Listener will rewrite ipv4 0.0.0.0 to ipv6 [::], breaking
  316. // hosts that disable ipv6. So, use the address given by the user.
  317. sctx.addr = addr
  318. if fdLimit, fderr := runtimeutil.FDLimit(); fderr == nil {
  319. if fdLimit <= reservedInternalFDNum {
  320. 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)
  321. }
  322. sctx.l = transport.LimitListener(sctx.l, int(fdLimit-reservedInternalFDNum))
  323. }
  324. if proto == "tcp" {
  325. if sctx.l, err = transport.NewKeepAliveListener(sctx.l, "tcp", nil); err != nil {
  326. return nil, err
  327. }
  328. }
  329. plog.Info("listening for client requests on ", u.Host)
  330. defer func() {
  331. if err != nil {
  332. sctx.l.Close()
  333. plog.Info("stopping listening for client requests on ", u.Host)
  334. }
  335. }()
  336. for k := range cfg.UserHandlers {
  337. sctx.userHandlers[k] = cfg.UserHandlers[k]
  338. }
  339. sctx.serviceRegister = cfg.ServiceRegister
  340. if cfg.EnablePprof || cfg.Debug {
  341. sctx.registerPprof()
  342. }
  343. if cfg.Debug {
  344. sctx.registerTrace()
  345. }
  346. sctxs[addr] = sctx
  347. }
  348. return sctxs, nil
  349. }
  350. func (e *Etcd) serve() (err error) {
  351. var ctlscfg *tls.Config
  352. if !e.cfg.ClientTLSInfo.Empty() {
  353. plog.Infof("ClientTLS: %s", e.cfg.ClientTLSInfo)
  354. if ctlscfg, err = e.cfg.ClientTLSInfo.ServerConfig(); err != nil {
  355. return err
  356. }
  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. h = v2http.NewClientHandler(e.Server, e.Server.Cfg.ReqTimeout())
  371. } else {
  372. mux := http.NewServeMux()
  373. etcdhttp.HandleBasic(mux, e.Server)
  374. h = mux
  375. }
  376. h = http.Handler(&cors.CORSHandler{Handler: h, Info: e.cfg.CorsInfo})
  377. gopts := []grpc.ServerOption{}
  378. if e.cfg.GRPCKeepAliveMinTime > time.Duration(0) {
  379. gopts = append(gopts, grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
  380. MinTime: e.cfg.GRPCKeepAliveMinTime,
  381. PermitWithoutStream: false,
  382. }))
  383. }
  384. if e.cfg.GRPCKeepAliveInterval > time.Duration(0) &&
  385. e.cfg.GRPCKeepAliveTimeout > time.Duration(0) {
  386. gopts = append(gopts, grpc.KeepaliveParams(keepalive.ServerParameters{
  387. Time: e.cfg.GRPCKeepAliveInterval,
  388. Timeout: e.cfg.GRPCKeepAliveTimeout,
  389. }))
  390. }
  391. for _, sctx := range e.sctxs {
  392. go func(s *serveCtx) {
  393. e.errHandler(s.serve(e.Server, ctlscfg, h, e.errHandler, gopts...))
  394. }(sctx)
  395. }
  396. return nil
  397. }
  398. func (e *Etcd) errHandler(err error) {
  399. select {
  400. case <-e.stopc:
  401. return
  402. default:
  403. }
  404. select {
  405. case <-e.stopc:
  406. case e.errc <- err:
  407. }
  408. }