etcd.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. // Copyright 2015 CoreOS, Inc.
  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. // TODO: support arm64
  15. // +build amd64
  16. package etcdmain
  17. import (
  18. "encoding/json"
  19. "fmt"
  20. "io/ioutil"
  21. "net"
  22. "net/http"
  23. _ "net/http/pprof"
  24. "os"
  25. "path"
  26. "reflect"
  27. "runtime"
  28. "strings"
  29. "time"
  30. "github.com/coreos/etcd/discovery"
  31. "github.com/coreos/etcd/etcdserver"
  32. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  33. "github.com/coreos/etcd/etcdserver/etcdhttp"
  34. "github.com/coreos/etcd/pkg/cors"
  35. "github.com/coreos/etcd/pkg/fileutil"
  36. pkgioutil "github.com/coreos/etcd/pkg/ioutil"
  37. "github.com/coreos/etcd/pkg/osutil"
  38. runtimeutil "github.com/coreos/etcd/pkg/runtime"
  39. "github.com/coreos/etcd/pkg/transport"
  40. "github.com/coreos/etcd/pkg/types"
  41. "github.com/coreos/etcd/proxy"
  42. "github.com/coreos/etcd/rafthttp"
  43. "github.com/coreos/etcd/version"
  44. "github.com/coreos/go-systemd/daemon"
  45. systemdutil "github.com/coreos/go-systemd/util"
  46. "github.com/coreos/pkg/capnslog"
  47. "github.com/prometheus/client_golang/prometheus"
  48. "google.golang.org/grpc"
  49. )
  50. type dirType string
  51. var plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "etcdmain")
  52. const (
  53. // the owner can make/remove files inside the directory
  54. privateDirMode = 0700
  55. // internal fd usage includes disk usage and transport usage.
  56. // To read/write snapshot, snap pkg needs 1. In normal case, wal pkg needs
  57. // at most 2 to read/lock/write WALs. One case that it needs to 2 is to
  58. // read all logs after some snapshot index, which locates at the end of
  59. // the second last and the head of the last. For purging, it needs to read
  60. // directory, so it needs 1. For fd monitor, it needs 1.
  61. // For transport, rafthttp builds two long-polling connections and at most
  62. // four temporary connections with each member. There are at most 9 members
  63. // in a cluster, so it should reserve 96.
  64. // For the safety, we set the total reserved number to 150.
  65. reservedInternalFDNum = 150
  66. )
  67. var (
  68. dirMember = dirType("member")
  69. dirProxy = dirType("proxy")
  70. dirEmpty = dirType("empty")
  71. )
  72. func Main() {
  73. cfg := NewConfig()
  74. err := cfg.Parse(os.Args[1:])
  75. if err != nil {
  76. plog.Errorf("error verifying flags, %v. See 'etcd --help'.", err)
  77. switch err {
  78. case errUnsetAdvertiseClientURLsFlag:
  79. plog.Errorf("When listening on specific address(es), this etcd process must advertise accessible url(s) to each connected client.")
  80. }
  81. os.Exit(1)
  82. }
  83. setupLogging(cfg)
  84. var stopped <-chan struct{}
  85. plog.Infof("etcd Version: %s\n", version.Version)
  86. plog.Infof("Git SHA: %s\n", version.GitSHA)
  87. plog.Infof("Go Version: %s\n", runtime.Version())
  88. plog.Infof("Go OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
  89. GoMaxProcs := runtime.GOMAXPROCS(0)
  90. plog.Infof("setting maximum number of CPUs to %d, total number of available CPUs is %d", GoMaxProcs, runtime.NumCPU())
  91. // TODO: check whether fields are set instead of whether fields have default value
  92. if cfg.name != defaultName && cfg.initialCluster == initialClusterFromName(defaultName) {
  93. cfg.initialCluster = initialClusterFromName(cfg.name)
  94. }
  95. if cfg.dir == "" {
  96. cfg.dir = fmt.Sprintf("%v.etcd", cfg.name)
  97. plog.Warningf("no data-dir provided, using default data-dir ./%s", cfg.dir)
  98. }
  99. which := identifyDataDirOrDie(cfg.dir)
  100. if which != dirEmpty {
  101. plog.Noticef("the server is already initialized as %v before, starting as etcd %v...", which, which)
  102. switch which {
  103. case dirMember:
  104. stopped, err = startEtcd(cfg)
  105. case dirProxy:
  106. err = startProxy(cfg)
  107. default:
  108. plog.Panicf("unhandled dir type %v", which)
  109. }
  110. } else {
  111. shouldProxy := cfg.isProxy()
  112. if !shouldProxy {
  113. stopped, err = startEtcd(cfg)
  114. if derr, ok := err.(*etcdserver.DiscoveryError); ok && derr.Err == discovery.ErrFullCluster {
  115. if cfg.shouldFallbackToProxy() {
  116. plog.Noticef("discovery cluster full, falling back to %s", fallbackFlagProxy)
  117. shouldProxy = true
  118. }
  119. }
  120. }
  121. if shouldProxy {
  122. err = startProxy(cfg)
  123. }
  124. }
  125. if err != nil {
  126. if derr, ok := err.(*etcdserver.DiscoveryError); ok {
  127. switch derr.Err {
  128. case discovery.ErrDuplicateID:
  129. plog.Errorf("member %q has previously registered with discovery service token (%s).", cfg.name, cfg.durl)
  130. plog.Errorf("But etcd could not find valid cluster configuration in the given data dir (%s).", cfg.dir)
  131. plog.Infof("Please check the given data dir path if the previous bootstrap succeeded")
  132. plog.Infof("or use a new discovery token if the previous bootstrap failed.")
  133. case discovery.ErrDuplicateName:
  134. plog.Errorf("member with duplicated name has registered with discovery service token(%s).", cfg.durl)
  135. plog.Errorf("please check (cURL) the discovery token for more information.")
  136. plog.Errorf("please do not reuse the discovery token and generate a new one to bootstrap the cluster.")
  137. default:
  138. plog.Errorf("%v", err)
  139. plog.Infof("discovery token %s was used, but failed to bootstrap the cluster.", cfg.durl)
  140. plog.Infof("please generate a new discovery token and try to bootstrap again.")
  141. }
  142. os.Exit(1)
  143. }
  144. if strings.Contains(err.Error(), "include") && strings.Contains(err.Error(), "--initial-cluster") {
  145. plog.Infof("%v", err)
  146. if cfg.initialCluster == initialClusterFromName(cfg.name) {
  147. plog.Infof("forgot to set --initial-cluster flag?")
  148. }
  149. if types.URLs(cfg.apurls).String() == defaultInitialAdvertisePeerURLs {
  150. plog.Infof("forgot to set --initial-advertise-peer-urls flag?")
  151. }
  152. if cfg.initialCluster == initialClusterFromName(cfg.name) && len(cfg.durl) == 0 {
  153. plog.Infof("if you want to use discovery service, please set --discovery flag.")
  154. }
  155. os.Exit(1)
  156. }
  157. plog.Fatalf("%v", err)
  158. }
  159. osutil.HandleInterrupts()
  160. if systemdutil.IsRunningSystemd() {
  161. // At this point, the initialization of etcd is done.
  162. // The listeners are listening on the TCP ports and ready
  163. // for accepting connections.
  164. // The http server is probably ready for serving incoming
  165. // connections. If it is not, the connection might be pending
  166. // for less than one second.
  167. err := daemon.SdNotify("READY=1")
  168. if err != nil {
  169. plog.Errorf("failed to notify systemd for readiness: %v", err)
  170. if err == daemon.SdNotifyNoSocket {
  171. plog.Errorf("forgot to set Type=notify in systemd service file?")
  172. }
  173. }
  174. }
  175. <-stopped
  176. osutil.Exit(0)
  177. }
  178. // startEtcd launches the etcd server and HTTP handlers for client/server communication.
  179. func startEtcd(cfg *config) (<-chan struct{}, error) {
  180. urlsmap, token, err := getPeerURLsMapAndToken(cfg, "etcd")
  181. if err != nil {
  182. return nil, fmt.Errorf("error setting up initial cluster: %v", err)
  183. }
  184. if cfg.peerAutoTLS && cfg.peerTLSInfo.Empty() {
  185. phosts := make([]string, 0)
  186. for _, u := range cfg.lpurls {
  187. phosts = append(phosts, u.Host)
  188. }
  189. cfg.peerTLSInfo, err = transport.SelfCert(cfg.dir, phosts)
  190. if err != nil {
  191. plog.Fatalf("could not get certs (%v)", err)
  192. }
  193. } else if cfg.peerAutoTLS {
  194. plog.Warningf("ignoring peer auto TLS since certs given")
  195. }
  196. if !cfg.peerTLSInfo.Empty() {
  197. plog.Infof("peerTLS: %s", cfg.peerTLSInfo)
  198. }
  199. plns := make([]net.Listener, 0)
  200. for _, u := range cfg.lpurls {
  201. if u.Scheme == "http" && !cfg.peerTLSInfo.Empty() {
  202. plog.Warningf("The scheme of peer url %s is http while peer key/cert files are presented. Ignored peer key/cert files.", u.String())
  203. }
  204. var l net.Listener
  205. l, err = rafthttp.NewListener(u, cfg.peerTLSInfo)
  206. if err != nil {
  207. return nil, err
  208. }
  209. urlStr := u.String()
  210. plog.Info("listening for peers on ", urlStr)
  211. defer func() {
  212. if err != nil {
  213. l.Close()
  214. plog.Info("stopping listening for peers on ", urlStr)
  215. }
  216. }()
  217. plns = append(plns, l)
  218. }
  219. if !cfg.clientTLSInfo.Empty() {
  220. plog.Infof("clientTLS: %s", cfg.clientTLSInfo)
  221. }
  222. clns := make([]net.Listener, 0)
  223. for _, u := range cfg.lcurls {
  224. if u.Scheme == "http" && !cfg.clientTLSInfo.Empty() {
  225. plog.Warningf("The scheme of client url %s is http while client key/cert files are presented. Ignored client key/cert files.", u.String())
  226. }
  227. var l net.Listener
  228. l, err = net.Listen("tcp", u.Host)
  229. if err != nil {
  230. return nil, err
  231. }
  232. var fdLimit uint64
  233. if fdLimit, err = runtimeutil.FDLimit(); err == nil {
  234. if fdLimit <= reservedInternalFDNum {
  235. 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)
  236. }
  237. l = transport.LimitListener(l, int(fdLimit-reservedInternalFDNum))
  238. }
  239. // Do not wrap around this listener if TLS Info is set.
  240. // HTTPS server expects TLS Conn created by TLSListener.
  241. l, err = transport.NewKeepAliveListener(l, u.Scheme, cfg.clientTLSInfo)
  242. if err != nil {
  243. return nil, err
  244. }
  245. urlStr := u.String()
  246. plog.Info("listening for client requests on ", urlStr)
  247. defer func() {
  248. if err != nil {
  249. l.Close()
  250. plog.Info("stopping listening for client requests on ", urlStr)
  251. }
  252. }()
  253. clns = append(clns, l)
  254. }
  255. srvcfg := &etcdserver.ServerConfig{
  256. Name: cfg.name,
  257. ClientURLs: cfg.acurls,
  258. PeerURLs: cfg.apurls,
  259. DataDir: cfg.dir,
  260. DedicatedWALDir: cfg.walDir,
  261. SnapCount: cfg.snapCount,
  262. MaxSnapFiles: cfg.maxSnapFiles,
  263. MaxWALFiles: cfg.maxWalFiles,
  264. InitialPeerURLsMap: urlsmap,
  265. InitialClusterToken: token,
  266. DiscoveryURL: cfg.durl,
  267. DiscoveryProxy: cfg.dproxy,
  268. NewCluster: cfg.isNewCluster(),
  269. ForceNewCluster: cfg.forceNewCluster,
  270. PeerTLSInfo: cfg.peerTLSInfo,
  271. TickMs: cfg.TickMs,
  272. ElectionTicks: cfg.electionTicks(),
  273. V3demo: cfg.v3demo,
  274. AutoCompactionRetention: cfg.autoCompactionRetention,
  275. StrictReconfigCheck: cfg.strictReconfigCheck,
  276. EnablePprof: cfg.enablePprof,
  277. }
  278. var s *etcdserver.EtcdServer
  279. s, err = etcdserver.NewServer(srvcfg)
  280. if err != nil {
  281. return nil, err
  282. }
  283. s.Start()
  284. osutil.RegisterInterruptHandler(s.Stop)
  285. if cfg.corsInfo.String() != "" {
  286. plog.Infof("cors = %s", cfg.corsInfo)
  287. }
  288. ch := &cors.CORSHandler{
  289. Handler: etcdhttp.NewClientHandler(s, srvcfg.ReqTimeout()),
  290. Info: cfg.corsInfo,
  291. }
  292. ph := etcdhttp.NewPeerHandler(s)
  293. var grpcS *grpc.Server
  294. if cfg.v3demo {
  295. // set up v3 demo rpc
  296. tls := &cfg.clientTLSInfo
  297. if cfg.clientTLSInfo.Empty() {
  298. tls = nil
  299. }
  300. grpcS, err = v3rpc.Server(s, tls)
  301. if err != nil {
  302. s.Stop()
  303. <-s.StopNotify()
  304. return nil, err
  305. }
  306. }
  307. // Start the peer server in a goroutine
  308. for _, l := range plns {
  309. go func(l net.Listener) {
  310. plog.Fatal(serve(l, nil, ph, 5*time.Minute))
  311. }(l)
  312. }
  313. // Start a client server goroutine for each listen address
  314. for _, l := range clns {
  315. go func(l net.Listener) {
  316. // read timeout does not work with http close notify
  317. // TODO: https://github.com/golang/go/issues/9524
  318. plog.Fatal(serve(l, grpcS, ch, 0))
  319. }(l)
  320. }
  321. return s.StopNotify(), nil
  322. }
  323. // startProxy launches an HTTP proxy for client communication which proxies to other etcd nodes.
  324. func startProxy(cfg *config) error {
  325. pt, err := transport.NewTimeoutTransport(cfg.peerTLSInfo, time.Duration(cfg.proxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyWriteTimeoutMs)*time.Millisecond)
  326. if err != nil {
  327. return err
  328. }
  329. pt.MaxIdleConnsPerHost = proxy.DefaultMaxIdleConnsPerHost
  330. tr, err := transport.NewTimeoutTransport(cfg.peerTLSInfo, time.Duration(cfg.proxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyWriteTimeoutMs)*time.Millisecond)
  331. if err != nil {
  332. return err
  333. }
  334. cfg.dir = path.Join(cfg.dir, "proxy")
  335. err = os.MkdirAll(cfg.dir, 0700)
  336. if err != nil {
  337. return err
  338. }
  339. var peerURLs []string
  340. clusterfile := path.Join(cfg.dir, "cluster")
  341. b, err := ioutil.ReadFile(clusterfile)
  342. switch {
  343. case err == nil:
  344. if cfg.durl != "" {
  345. plog.Warningf("discovery token ignored since the proxy has already been initialized. Valid cluster file found at %q", clusterfile)
  346. }
  347. if cfg.dnsCluster != "" {
  348. plog.Warningf("DNS SRV discovery ignored since the proxy has already been initialized. Valid cluster file found at %q", clusterfile)
  349. }
  350. urls := struct{ PeerURLs []string }{}
  351. err = json.Unmarshal(b, &urls)
  352. if err != nil {
  353. return err
  354. }
  355. peerURLs = urls.PeerURLs
  356. plog.Infof("proxy: using peer urls %v from cluster file %q", peerURLs, clusterfile)
  357. case os.IsNotExist(err):
  358. var urlsmap types.URLsMap
  359. urlsmap, _, err = getPeerURLsMapAndToken(cfg, "proxy")
  360. if err != nil {
  361. return fmt.Errorf("error setting up initial cluster: %v", err)
  362. }
  363. if cfg.durl != "" {
  364. var s string
  365. s, err = discovery.GetCluster(cfg.durl, cfg.dproxy)
  366. if err != nil {
  367. return err
  368. }
  369. if urlsmap, err = types.NewURLsMap(s); err != nil {
  370. return err
  371. }
  372. }
  373. peerURLs = urlsmap.URLs()
  374. plog.Infof("proxy: using peer urls %v ", peerURLs)
  375. default:
  376. return err
  377. }
  378. clientURLs := []string{}
  379. uf := func() []string {
  380. gcls, err := etcdserver.GetClusterFromRemotePeers(peerURLs, tr)
  381. // TODO: remove the 2nd check when we fix GetClusterFromRemotePeers
  382. // GetClusterFromRemotePeers should not return nil error with an invalid empty cluster
  383. if err != nil {
  384. plog.Warningf("proxy: %v", err)
  385. return []string{}
  386. }
  387. if len(gcls.Members()) == 0 {
  388. return clientURLs
  389. }
  390. clientURLs = gcls.ClientURLs()
  391. urls := struct{ PeerURLs []string }{gcls.PeerURLs()}
  392. b, err := json.Marshal(urls)
  393. if err != nil {
  394. plog.Warningf("proxy: error on marshal peer urls %s", err)
  395. return clientURLs
  396. }
  397. err = pkgioutil.WriteAndSyncFile(clusterfile+".bak", b, 0600)
  398. if err != nil {
  399. plog.Warningf("proxy: error on writing urls %s", err)
  400. return clientURLs
  401. }
  402. err = os.Rename(clusterfile+".bak", clusterfile)
  403. if err != nil {
  404. plog.Warningf("proxy: error on updating clusterfile %s", err)
  405. return clientURLs
  406. }
  407. if !reflect.DeepEqual(gcls.PeerURLs(), peerURLs) {
  408. plog.Noticef("proxy: updated peer urls in cluster file from %v to %v", peerURLs, gcls.PeerURLs())
  409. }
  410. peerURLs = gcls.PeerURLs()
  411. return clientURLs
  412. }
  413. ph := proxy.NewHandler(pt, uf, time.Duration(cfg.proxyFailureWaitMs)*time.Millisecond, time.Duration(cfg.proxyRefreshIntervalMs)*time.Millisecond)
  414. ph = &cors.CORSHandler{
  415. Handler: ph,
  416. Info: cfg.corsInfo,
  417. }
  418. if cfg.isReadonlyProxy() {
  419. ph = proxy.NewReadonlyHandler(ph)
  420. }
  421. // Start a proxy server goroutine for each listen address
  422. for _, u := range cfg.lcurls {
  423. l, err := transport.NewListener(u.Host, u.Scheme, cfg.clientTLSInfo)
  424. if err != nil {
  425. return err
  426. }
  427. host := u.String()
  428. go func() {
  429. plog.Info("proxy: listening for client requests on ", host)
  430. mux := http.NewServeMux()
  431. mux.Handle("/metrics", prometheus.Handler())
  432. mux.Handle("/", ph)
  433. plog.Fatal(http.Serve(l, mux))
  434. }()
  435. }
  436. return nil
  437. }
  438. // getPeerURLsMapAndToken sets up an initial peer URLsMap and cluster token for bootstrap or discovery.
  439. func getPeerURLsMapAndToken(cfg *config, which string) (urlsmap types.URLsMap, token string, err error) {
  440. switch {
  441. case cfg.durl != "":
  442. urlsmap = types.URLsMap{}
  443. // If using discovery, generate a temporary cluster based on
  444. // self's advertised peer URLs
  445. urlsmap[cfg.name] = cfg.apurls
  446. token = cfg.durl
  447. case cfg.dnsCluster != "":
  448. var clusterStr string
  449. clusterStr, token, err = discovery.SRVGetCluster(cfg.name, cfg.dnsCluster, cfg.initialClusterToken, cfg.apurls)
  450. if err != nil {
  451. return nil, "", err
  452. }
  453. urlsmap, err = types.NewURLsMap(clusterStr)
  454. // only etcd member must belong to the discovered cluster.
  455. // proxy does not need to belong to the discovered cluster.
  456. if which == "etcd" {
  457. if _, ok := urlsmap[cfg.name]; !ok {
  458. return nil, "", fmt.Errorf("cannot find local etcd member %q in SRV records", cfg.name)
  459. }
  460. }
  461. default:
  462. // We're statically configured, and cluster has appropriately been set.
  463. urlsmap, err = types.NewURLsMap(cfg.initialCluster)
  464. token = cfg.initialClusterToken
  465. }
  466. return urlsmap, token, err
  467. }
  468. // identifyDataDirOrDie returns the type of the data dir.
  469. // Dies if the datadir is invalid.
  470. func identifyDataDirOrDie(dir string) dirType {
  471. names, err := fileutil.ReadDir(dir)
  472. if err != nil {
  473. if os.IsNotExist(err) {
  474. return dirEmpty
  475. }
  476. plog.Fatalf("error listing data dir: %s", dir)
  477. }
  478. var m, p bool
  479. for _, name := range names {
  480. switch dirType(name) {
  481. case dirMember:
  482. m = true
  483. case dirProxy:
  484. p = true
  485. default:
  486. plog.Warningf("found invalid file/dir %s under data dir %s (Ignore this if you are upgrading etcd)", name, dir)
  487. }
  488. }
  489. if m && p {
  490. plog.Fatal("invalid datadir. Both member and proxy directories exist.")
  491. }
  492. if m {
  493. return dirMember
  494. }
  495. if p {
  496. return dirProxy
  497. }
  498. return dirEmpty
  499. }
  500. func setupLogging(cfg *config) {
  501. capnslog.SetGlobalLogLevel(capnslog.INFO)
  502. if cfg.debug {
  503. capnslog.SetGlobalLogLevel(capnslog.DEBUG)
  504. }
  505. if cfg.logPkgLevels != "" {
  506. repoLog := capnslog.MustRepoLogger("github.com/coreos/etcd")
  507. settings, err := repoLog.ParseLogLevelConfig(cfg.logPkgLevels)
  508. if err != nil {
  509. plog.Warningf("couldn't parse log level string: %s, continuing with default levels", err.Error())
  510. return
  511. }
  512. repoLog.SetLogLevel(settings)
  513. }
  514. }