etcd.go 12 KB

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