etcd.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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/Godeps/_workspace/src/github.com/coreos/go-systemd/daemon"
  31. systemdutil "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/go-systemd/util"
  32. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/pkg/capnslog"
  33. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus"
  34. "github.com/coreos/etcd/Godeps/_workspace/src/google.golang.org/grpc"
  35. "github.com/coreos/etcd/discovery"
  36. "github.com/coreos/etcd/etcdserver"
  37. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  38. "github.com/coreos/etcd/etcdserver/etcdhttp"
  39. "github.com/coreos/etcd/pkg/cors"
  40. "github.com/coreos/etcd/pkg/fileutil"
  41. pkgioutil "github.com/coreos/etcd/pkg/ioutil"
  42. "github.com/coreos/etcd/pkg/osutil"
  43. runtimeutil "github.com/coreos/etcd/pkg/runtime"
  44. "github.com/coreos/etcd/pkg/transport"
  45. "github.com/coreos/etcd/pkg/types"
  46. "github.com/coreos/etcd/proxy"
  47. "github.com/coreos/etcd/rafthttp"
  48. "github.com/coreos/etcd/version"
  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. if fdLimit, err := runtimeutil.FDLimit(); err == nil {
  233. if fdLimit <= reservedInternalFDNum {
  234. 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)
  235. }
  236. l = transport.LimitListener(l, int(fdLimit-reservedInternalFDNum))
  237. }
  238. // Do not wrap around this listener if TLS Info is set.
  239. // HTTPS server expects TLS Conn created by TLSListener.
  240. l, err = transport.NewKeepAliveListener(l, u.Scheme, cfg.clientTLSInfo)
  241. if err != nil {
  242. return nil, err
  243. }
  244. urlStr := u.String()
  245. plog.Info("listening for client requests on ", urlStr)
  246. defer func() {
  247. if err != nil {
  248. l.Close()
  249. plog.Info("stopping listening for client requests on ", urlStr)
  250. }
  251. }()
  252. clns = append(clns, l)
  253. }
  254. srvcfg := &etcdserver.ServerConfig{
  255. Name: cfg.name,
  256. ClientURLs: cfg.acurls,
  257. PeerURLs: cfg.apurls,
  258. DataDir: cfg.dir,
  259. DedicatedWALDir: cfg.walDir,
  260. SnapCount: cfg.snapCount,
  261. MaxSnapFiles: cfg.maxSnapFiles,
  262. MaxWALFiles: cfg.maxWalFiles,
  263. InitialPeerURLsMap: urlsmap,
  264. InitialClusterToken: token,
  265. DiscoveryURL: cfg.durl,
  266. DiscoveryProxy: cfg.dproxy,
  267. NewCluster: cfg.isNewCluster(),
  268. ForceNewCluster: cfg.forceNewCluster,
  269. PeerTLSInfo: cfg.peerTLSInfo,
  270. TickMs: cfg.TickMs,
  271. ElectionTicks: cfg.electionTicks(),
  272. V3demo: cfg.v3demo,
  273. AutoCompactionRetention: cfg.autoCompactionRetention,
  274. StrictReconfigCheck: cfg.strictReconfigCheck,
  275. EnablePprof: cfg.enablePprof,
  276. }
  277. var s *etcdserver.EtcdServer
  278. s, err = etcdserver.NewServer(srvcfg)
  279. if err != nil {
  280. return nil, err
  281. }
  282. s.Start()
  283. osutil.RegisterInterruptHandler(s.Stop)
  284. if cfg.corsInfo.String() != "" {
  285. plog.Infof("cors = %s", cfg.corsInfo)
  286. }
  287. ch := &cors.CORSHandler{
  288. Handler: etcdhttp.NewClientHandler(s, srvcfg.ReqTimeout()),
  289. Info: cfg.corsInfo,
  290. }
  291. ph := etcdhttp.NewPeerHandler(s)
  292. var grpcS *grpc.Server
  293. if cfg.v3demo {
  294. // set up v3 demo rpc
  295. tls := &cfg.clientTLSInfo
  296. if cfg.clientTLSInfo.Empty() {
  297. tls = nil
  298. }
  299. grpcS, err = v3rpc.Server(s, tls)
  300. if err != nil {
  301. s.Stop()
  302. <-s.StopNotify()
  303. return nil, err
  304. }
  305. }
  306. // Start the peer server in a goroutine
  307. for _, l := range plns {
  308. go func(l net.Listener) {
  309. plog.Fatal(serve(l, nil, ph, 5*time.Minute))
  310. }(l)
  311. }
  312. // Start a client server goroutine for each listen address
  313. for _, l := range clns {
  314. go func(l net.Listener) {
  315. // read timeout does not work with http close notify
  316. // TODO: https://github.com/golang/go/issues/9524
  317. plog.Fatal(serve(l, grpcS, ch, 0))
  318. }(l)
  319. }
  320. return s.StopNotify(), nil
  321. }
  322. // startProxy launches an HTTP proxy for client communication which proxies to other etcd nodes.
  323. func startProxy(cfg *config) error {
  324. pt, err := transport.NewTimeoutTransport(cfg.peerTLSInfo, time.Duration(cfg.proxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyWriteTimeoutMs)*time.Millisecond)
  325. if err != nil {
  326. return err
  327. }
  328. pt.MaxIdleConnsPerHost = proxy.DefaultMaxIdleConnsPerHost
  329. tr, err := transport.NewTimeoutTransport(cfg.peerTLSInfo, time.Duration(cfg.proxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyWriteTimeoutMs)*time.Millisecond)
  330. if err != nil {
  331. return err
  332. }
  333. cfg.dir = path.Join(cfg.dir, "proxy")
  334. err = os.MkdirAll(cfg.dir, 0700)
  335. if err != nil {
  336. return err
  337. }
  338. var peerURLs []string
  339. clusterfile := path.Join(cfg.dir, "cluster")
  340. b, err := ioutil.ReadFile(clusterfile)
  341. switch {
  342. case err == nil:
  343. if cfg.durl != "" {
  344. plog.Warningf("discovery token ignored since the proxy has already been initialized. Valid cluster file found at %q", clusterfile)
  345. }
  346. if cfg.dnsCluster != "" {
  347. plog.Warningf("DNS SRV discovery ignored since the proxy has already been initialized. Valid cluster file found at %q", clusterfile)
  348. }
  349. urls := struct{ PeerURLs []string }{}
  350. err = json.Unmarshal(b, &urls)
  351. if err != nil {
  352. return err
  353. }
  354. peerURLs = urls.PeerURLs
  355. plog.Infof("proxy: using peer urls %v from cluster file %q", peerURLs, clusterfile)
  356. case os.IsNotExist(err):
  357. urlsmap, _, err := getPeerURLsMapAndToken(cfg, "proxy")
  358. if err != nil {
  359. return fmt.Errorf("error setting up initial cluster: %v", err)
  360. }
  361. if cfg.durl != "" {
  362. s, err := discovery.GetCluster(cfg.durl, cfg.dproxy)
  363. if err != nil {
  364. return err
  365. }
  366. if urlsmap, err = types.NewURLsMap(s); err != nil {
  367. return err
  368. }
  369. }
  370. peerURLs = urlsmap.URLs()
  371. plog.Infof("proxy: using peer urls %v ", peerURLs)
  372. default:
  373. return err
  374. }
  375. clientURLs := []string{}
  376. uf := func() []string {
  377. gcls, err := etcdserver.GetClusterFromRemotePeers(peerURLs, tr)
  378. // TODO: remove the 2nd check when we fix GetClusterFromRemotePeers
  379. // GetClusterFromRemotePeers should not return nil error with an invalid empty cluster
  380. if err != nil {
  381. plog.Warningf("proxy: %v", err)
  382. return []string{}
  383. }
  384. if len(gcls.Members()) == 0 {
  385. return clientURLs
  386. }
  387. clientURLs = gcls.ClientURLs()
  388. urls := struct{ PeerURLs []string }{gcls.PeerURLs()}
  389. b, err := json.Marshal(urls)
  390. if err != nil {
  391. plog.Warningf("proxy: error on marshal peer urls %s", err)
  392. return clientURLs
  393. }
  394. err = pkgioutil.WriteAndSyncFile(clusterfile+".bak", b, 0600)
  395. if err != nil {
  396. plog.Warningf("proxy: error on writing urls %s", err)
  397. return clientURLs
  398. }
  399. err = os.Rename(clusterfile+".bak", clusterfile)
  400. if err != nil {
  401. plog.Warningf("proxy: error on updating clusterfile %s", err)
  402. return clientURLs
  403. }
  404. if !reflect.DeepEqual(gcls.PeerURLs(), peerURLs) {
  405. plog.Noticef("proxy: updated peer urls in cluster file from %v to %v", peerURLs, gcls.PeerURLs())
  406. }
  407. peerURLs = gcls.PeerURLs()
  408. return clientURLs
  409. }
  410. ph := proxy.NewHandler(pt, uf, time.Duration(cfg.proxyFailureWaitMs)*time.Millisecond, time.Duration(cfg.proxyRefreshIntervalMs)*time.Millisecond)
  411. ph = &cors.CORSHandler{
  412. Handler: ph,
  413. Info: cfg.corsInfo,
  414. }
  415. if cfg.isReadonlyProxy() {
  416. ph = proxy.NewReadonlyHandler(ph)
  417. }
  418. // Start a proxy server goroutine for each listen address
  419. for _, u := range cfg.lcurls {
  420. l, err := transport.NewListener(u.Host, u.Scheme, cfg.clientTLSInfo)
  421. if err != nil {
  422. return err
  423. }
  424. host := u.String()
  425. go func() {
  426. plog.Info("proxy: listening for client requests on ", host)
  427. mux := http.NewServeMux()
  428. mux.Handle("/metrics", prometheus.Handler())
  429. mux.Handle("/", ph)
  430. plog.Fatal(http.Serve(l, mux))
  431. }()
  432. }
  433. return nil
  434. }
  435. // getPeerURLsMapAndToken sets up an initial peer URLsMap and cluster token for bootstrap or discovery.
  436. func getPeerURLsMapAndToken(cfg *config, which string) (urlsmap types.URLsMap, token string, err error) {
  437. switch {
  438. case cfg.durl != "":
  439. urlsmap = types.URLsMap{}
  440. // If using discovery, generate a temporary cluster based on
  441. // self's advertised peer URLs
  442. urlsmap[cfg.name] = cfg.apurls
  443. token = cfg.durl
  444. case cfg.dnsCluster != "":
  445. var clusterStr string
  446. clusterStr, token, err = discovery.SRVGetCluster(cfg.name, cfg.dnsCluster, cfg.initialClusterToken, cfg.apurls)
  447. if err != nil {
  448. return nil, "", err
  449. }
  450. urlsmap, err = types.NewURLsMap(clusterStr)
  451. // only etcd member must belong to the discovered cluster.
  452. // proxy does not need to belong to the discovered cluster.
  453. if which == "etcd" {
  454. if _, ok := urlsmap[cfg.name]; !ok {
  455. return nil, "", fmt.Errorf("cannot find local etcd member %q in SRV records", cfg.name)
  456. }
  457. }
  458. default:
  459. // We're statically configured, and cluster has appropriately been set.
  460. urlsmap, err = types.NewURLsMap(cfg.initialCluster)
  461. token = cfg.initialClusterToken
  462. }
  463. return urlsmap, token, err
  464. }
  465. // identifyDataDirOrDie returns the type of the data dir.
  466. // Dies if the datadir is invalid.
  467. func identifyDataDirOrDie(dir string) dirType {
  468. names, err := fileutil.ReadDir(dir)
  469. if err != nil {
  470. if os.IsNotExist(err) {
  471. return dirEmpty
  472. }
  473. plog.Fatalf("error listing data dir: %s", dir)
  474. }
  475. var m, p bool
  476. for _, name := range names {
  477. switch dirType(name) {
  478. case dirMember:
  479. m = true
  480. case dirProxy:
  481. p = true
  482. default:
  483. plog.Warningf("found invalid file/dir %s under data dir %s (Ignore this if you are upgrading etcd)", name, dir)
  484. }
  485. }
  486. if m && p {
  487. plog.Fatal("invalid datadir. Both member and proxy directories exist.")
  488. }
  489. if m {
  490. return dirMember
  491. }
  492. if p {
  493. return dirProxy
  494. }
  495. return dirEmpty
  496. }
  497. func setupLogging(cfg *config) {
  498. capnslog.SetGlobalLogLevel(capnslog.INFO)
  499. if cfg.debug {
  500. capnslog.SetGlobalLogLevel(capnslog.DEBUG)
  501. }
  502. if cfg.logPkgLevels != "" {
  503. repoLog := capnslog.MustRepoLogger("github.com/coreos/etcd")
  504. settings, err := repoLog.ParseLogLevelConfig(cfg.logPkgLevels)
  505. if err != nil {
  506. plog.Warningf("couldn't parse log level string: %s, continuing with default levels", err.Error())
  507. return
  508. }
  509. repoLog.SetLogLevel(settings)
  510. }
  511. }