etcd.go 10 KB

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