etcd.go 11 KB

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