etcd.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. }
  136. if e.Server, err = etcdserver.NewServer(srvcfg); err != nil {
  137. return
  138. }
  139. // configure peer handlers after rafthttp.Transport started
  140. ph := etcdhttp.NewPeerHandler(e.Server)
  141. for _, p := range e.Peers {
  142. srv := &http.Server{
  143. Handler: ph,
  144. ReadTimeout: 5 * time.Minute,
  145. ErrorLog: defaultLog.New(ioutil.Discard, "", 0), // do not log user error
  146. }
  147. l := p.Listener
  148. p.serve = func() error { return srv.Serve(l) }
  149. p.close = func(ctx context.Context) error {
  150. // gracefully shutdown http.Server
  151. // close open listeners, idle connections
  152. // until context cancel or time-out
  153. return srv.Shutdown(ctx)
  154. }
  155. }
  156. // buffer channel so goroutines on closed connections won't wait forever
  157. e.errc = make(chan error, len(e.Peers)+len(e.Clients)+2*len(e.sctxs))
  158. e.Server.Start()
  159. if err = e.serve(); err != nil {
  160. return
  161. }
  162. serving = true
  163. return
  164. }
  165. // Config returns the current configuration.
  166. func (e *Etcd) Config() Config {
  167. return e.cfg
  168. }
  169. func (e *Etcd) Close() {
  170. e.closeOnce.Do(func() { close(e.stopc) })
  171. timeout := 2 * time.Second
  172. if e.Server != nil {
  173. timeout = e.Server.Cfg.ReqTimeout()
  174. }
  175. for _, sctx := range e.sctxs {
  176. for gs := range sctx.grpcServerC {
  177. ch := make(chan struct{})
  178. go func() {
  179. defer close(ch)
  180. // close listeners to stop accepting new connections,
  181. // will block on any existing transports
  182. gs.GracefulStop()
  183. }()
  184. // wait until all pending RPCs are finished
  185. select {
  186. case <-ch:
  187. case <-time.After(timeout):
  188. // took too long, manually close open transports
  189. // e.g. watch streams
  190. gs.Stop()
  191. // concurrent GracefulStop should be interrupted
  192. <-ch
  193. }
  194. }
  195. }
  196. for _, sctx := range e.sctxs {
  197. sctx.cancel()
  198. }
  199. for i := range e.Clients {
  200. if e.Clients[i] != nil {
  201. e.Clients[i].Close()
  202. }
  203. }
  204. // close rafthttp transports
  205. if e.Server != nil {
  206. e.Server.Stop()
  207. }
  208. // close all idle connections in peer handler (wait up to 1-second)
  209. for i := range e.Peers {
  210. if e.Peers[i] != nil && e.Peers[i].close != nil {
  211. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  212. e.Peers[i].close(ctx)
  213. cancel()
  214. }
  215. }
  216. }
  217. func (e *Etcd) Err() <-chan error { return e.errc }
  218. func startPeerListeners(cfg *Config) (peers []*peerListener, err error) {
  219. if cfg.PeerAutoTLS && cfg.PeerTLSInfo.Empty() {
  220. phosts := make([]string, len(cfg.LPUrls))
  221. for i, u := range cfg.LPUrls {
  222. phosts[i] = u.Host
  223. }
  224. cfg.PeerTLSInfo, err = transport.SelfCert(filepath.Join(cfg.Dir, "fixtures", "peer"), phosts)
  225. if err != nil {
  226. plog.Fatalf("could not get certs (%v)", err)
  227. }
  228. } else if cfg.PeerAutoTLS {
  229. plog.Warningf("ignoring peer auto TLS since certs given")
  230. }
  231. if !cfg.PeerTLSInfo.Empty() {
  232. plog.Infof("peerTLS: %s", cfg.PeerTLSInfo)
  233. }
  234. peers = make([]*peerListener, len(cfg.LPUrls))
  235. defer func() {
  236. if err == nil {
  237. return
  238. }
  239. for i := range peers {
  240. if peers[i] != nil && peers[i].close != nil {
  241. plog.Info("stopping listening for peers on ", cfg.LPUrls[i].String())
  242. peers[i].close(context.Background())
  243. }
  244. }
  245. }()
  246. for i, u := range cfg.LPUrls {
  247. if u.Scheme == "http" {
  248. if !cfg.PeerTLSInfo.Empty() {
  249. plog.Warningf("The scheme of peer url %s is HTTP while peer key/cert files are presented. Ignored peer key/cert files.", u.String())
  250. }
  251. if cfg.PeerTLSInfo.ClientCertAuth {
  252. 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())
  253. }
  254. }
  255. peers[i] = &peerListener{close: func(context.Context) error { return nil }}
  256. peers[i].Listener, err = rafthttp.NewListener(u, &cfg.PeerTLSInfo)
  257. if err != nil {
  258. return nil, err
  259. }
  260. // once serve, overwrite with 'http.Server.Shutdown'
  261. peers[i].close = func(context.Context) error {
  262. return peers[i].Listener.Close()
  263. }
  264. plog.Info("listening for peers on ", u.String())
  265. }
  266. return peers, nil
  267. }
  268. func startClientListeners(cfg *Config) (sctxs map[string]*serveCtx, err error) {
  269. if cfg.ClientAutoTLS && cfg.ClientTLSInfo.Empty() {
  270. chosts := make([]string, len(cfg.LCUrls))
  271. for i, u := range cfg.LCUrls {
  272. chosts[i] = u.Host
  273. }
  274. cfg.ClientTLSInfo, err = transport.SelfCert(filepath.Join(cfg.Dir, "fixtures", "client"), chosts)
  275. if err != nil {
  276. plog.Fatalf("could not get certs (%v)", err)
  277. }
  278. } else if cfg.ClientAutoTLS {
  279. plog.Warningf("ignoring client auto TLS since certs given")
  280. }
  281. if cfg.EnablePprof {
  282. plog.Infof("pprof is enabled under %s", debugutil.HTTPPrefixPProf)
  283. }
  284. sctxs = make(map[string]*serveCtx)
  285. for _, u := range cfg.LCUrls {
  286. sctx := newServeCtx()
  287. if u.Scheme == "http" || u.Scheme == "unix" {
  288. if !cfg.ClientTLSInfo.Empty() {
  289. plog.Warningf("The scheme of client url %s is HTTP while peer key/cert files are presented. Ignored key/cert files.", u.String())
  290. }
  291. if cfg.ClientTLSInfo.ClientCertAuth {
  292. 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())
  293. }
  294. }
  295. if (u.Scheme == "https" || u.Scheme == "unixs") && cfg.ClientTLSInfo.Empty() {
  296. return nil, fmt.Errorf("TLS key/cert (--cert-file, --key-file) must be provided for client url %s with HTTPs scheme", u.String())
  297. }
  298. proto := "tcp"
  299. addr := u.Host
  300. if u.Scheme == "unix" || u.Scheme == "unixs" {
  301. proto = "unix"
  302. addr = u.Host + u.Path
  303. }
  304. sctx.secure = u.Scheme == "https" || u.Scheme == "unixs"
  305. sctx.insecure = !sctx.secure
  306. if oldctx := sctxs[addr]; oldctx != nil {
  307. oldctx.secure = oldctx.secure || sctx.secure
  308. oldctx.insecure = oldctx.insecure || sctx.insecure
  309. continue
  310. }
  311. if sctx.l, err = net.Listen(proto, addr); err != nil {
  312. return nil, err
  313. }
  314. // net.Listener will rewrite ipv4 0.0.0.0 to ipv6 [::], breaking
  315. // hosts that disable ipv6. So, use the address given by the user.
  316. sctx.addr = addr
  317. if fdLimit, fderr := runtimeutil.FDLimit(); fderr == nil {
  318. if fdLimit <= reservedInternalFDNum {
  319. 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)
  320. }
  321. sctx.l = transport.LimitListener(sctx.l, int(fdLimit-reservedInternalFDNum))
  322. }
  323. if proto == "tcp" {
  324. if sctx.l, err = transport.NewKeepAliveListener(sctx.l, "tcp", nil); err != nil {
  325. return nil, err
  326. }
  327. }
  328. plog.Info("listening for client requests on ", u.Host)
  329. defer func() {
  330. if err != nil {
  331. sctx.l.Close()
  332. plog.Info("stopping listening for client requests on ", u.Host)
  333. }
  334. }()
  335. for k := range cfg.UserHandlers {
  336. sctx.userHandlers[k] = cfg.UserHandlers[k]
  337. }
  338. sctx.serviceRegister = cfg.ServiceRegister
  339. if cfg.EnablePprof || cfg.Debug {
  340. sctx.registerPprof()
  341. }
  342. if cfg.Debug {
  343. sctx.registerTrace()
  344. }
  345. sctxs[addr] = sctx
  346. }
  347. return sctxs, nil
  348. }
  349. func (e *Etcd) serve() (err error) {
  350. var ctlscfg *tls.Config
  351. if !e.cfg.ClientTLSInfo.Empty() {
  352. plog.Infof("ClientTLS: %s", e.cfg.ClientTLSInfo)
  353. if ctlscfg, err = e.cfg.ClientTLSInfo.ServerConfig(); err != nil {
  354. return err
  355. }
  356. }
  357. if e.cfg.CorsInfo.String() != "" {
  358. plog.Infof("cors = %s", e.cfg.CorsInfo)
  359. }
  360. // Start the peer server in a goroutine
  361. for _, pl := range e.Peers {
  362. go func(l *peerListener) {
  363. e.errHandler(l.serve())
  364. }(pl)
  365. }
  366. // Start a client server goroutine for each listen address
  367. var h http.Handler
  368. if e.Config().EnableV2 {
  369. h = v2http.NewClientHandler(e.Server, e.Server.Cfg.ReqTimeout())
  370. } else {
  371. mux := http.NewServeMux()
  372. etcdhttp.HandleBasic(mux, e.Server)
  373. h = mux
  374. }
  375. h = http.Handler(&cors.CORSHandler{Handler: h, Info: e.cfg.CorsInfo})
  376. gopts := []grpc.ServerOption{}
  377. if e.cfg.GRPCKeepAliveMinTime > time.Duration(0) {
  378. gopts = append(gopts, grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
  379. MinTime: e.cfg.GRPCKeepAliveMinTime,
  380. PermitWithoutStream: false,
  381. }))
  382. }
  383. if e.cfg.GRPCKeepAliveInterval > time.Duration(0) &&
  384. e.cfg.GRPCKeepAliveTimeout > time.Duration(0) {
  385. gopts = append(gopts, grpc.KeepaliveParams(keepalive.ServerParameters{
  386. Time: e.cfg.GRPCKeepAliveInterval,
  387. Timeout: e.cfg.GRPCKeepAliveTimeout,
  388. }))
  389. }
  390. for _, sctx := range e.sctxs {
  391. go func(s *serveCtx) {
  392. e.errHandler(s.serve(e.Server, ctlscfg, h, e.errHandler, gopts...))
  393. }(sctx)
  394. }
  395. return nil
  396. }
  397. func (e *Etcd) errHandler(err error) {
  398. select {
  399. case <-e.stopc:
  400. return
  401. default:
  402. }
  403. select {
  404. case <-e.stopc:
  405. case e.errc <- err:
  406. }
  407. }