etcd.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. // Copyright 2015 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 etcdmain
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "io/ioutil"
  19. "net/http"
  20. "os"
  21. "path/filepath"
  22. "reflect"
  23. "runtime"
  24. "strings"
  25. "time"
  26. "github.com/coreos/etcd/discovery"
  27. "github.com/coreos/etcd/embed"
  28. "github.com/coreos/etcd/etcdserver"
  29. "github.com/coreos/etcd/etcdserver/api/etcdhttp"
  30. "github.com/coreos/etcd/pkg/fileutil"
  31. pkgioutil "github.com/coreos/etcd/pkg/ioutil"
  32. "github.com/coreos/etcd/pkg/osutil"
  33. "github.com/coreos/etcd/pkg/transport"
  34. "github.com/coreos/etcd/pkg/types"
  35. "github.com/coreos/etcd/proxy/httpproxy"
  36. "github.com/coreos/etcd/version"
  37. "github.com/coreos/pkg/capnslog"
  38. "go.uber.org/zap"
  39. "google.golang.org/grpc"
  40. )
  41. type dirType string
  42. var plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "etcdmain")
  43. var (
  44. dirMember = dirType("member")
  45. dirProxy = dirType("proxy")
  46. dirEmpty = dirType("empty")
  47. )
  48. func startEtcdOrProxyV2() {
  49. grpc.EnableTracing = false
  50. cfg := newConfig()
  51. defaultInitialCluster := cfg.ec.InitialCluster
  52. err := cfg.parse(os.Args[1:])
  53. if err != nil {
  54. lg := cfg.ec.GetLogger()
  55. if lg != nil {
  56. lg.Error("failed to verify flags", zap.Error(err))
  57. } else {
  58. plog.Errorf("error verifying flags, %v. See 'etcd --help'.", err)
  59. }
  60. switch err {
  61. case embed.ErrUnsetAdvertiseClientURLsFlag:
  62. if lg != nil {
  63. lg.Error("advertise client URLs are not set", zap.Error(err))
  64. } else {
  65. plog.Errorf("When listening on specific address(es), this etcd process must advertise accessible url(s) to each connected client.")
  66. }
  67. }
  68. os.Exit(1)
  69. }
  70. maxProcs, cpus := runtime.GOMAXPROCS(0), runtime.NumCPU()
  71. lg := cfg.ec.GetLogger()
  72. if lg != nil {
  73. lg.Info(
  74. "starting etcd",
  75. zap.String("etcd-version", version.Version),
  76. zap.String("git-sha", version.GitSHA),
  77. zap.String("go-version", runtime.Version()),
  78. zap.String("go-os", runtime.GOOS),
  79. zap.String("go-arch", runtime.GOARCH),
  80. zap.Int("max-cpu-set", maxProcs),
  81. zap.Int("max-cpu-available", cpus),
  82. )
  83. } else {
  84. plog.Infof("etcd Version: %s\n", version.Version)
  85. plog.Infof("Git SHA: %s\n", version.GitSHA)
  86. plog.Infof("Go Version: %s\n", runtime.Version())
  87. plog.Infof("Go OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
  88. plog.Infof("setting maximum number of CPUs to %d, total number of available CPUs is %d", maxProcs, cpus)
  89. }
  90. defer func() {
  91. logger := cfg.ec.GetLogger()
  92. if logger != nil {
  93. logger.Sync()
  94. }
  95. }()
  96. defaultHost, dhErr := (&cfg.ec).UpdateDefaultClusterFromName(defaultInitialCluster)
  97. if defaultHost != "" {
  98. if lg != nil {
  99. lg.Info(
  100. "detected default host for advertise",
  101. zap.String("host", defaultHost),
  102. )
  103. } else {
  104. plog.Infof("advertising using detected default host %q", defaultHost)
  105. }
  106. }
  107. if dhErr != nil {
  108. if lg != nil {
  109. lg.Info("failed to detect default host", zap.Error(dhErr))
  110. } else {
  111. plog.Noticef("failed to detect default host (%v)", dhErr)
  112. }
  113. }
  114. if cfg.ec.Dir == "" {
  115. cfg.ec.Dir = fmt.Sprintf("%v.etcd", cfg.ec.Name)
  116. if lg != nil {
  117. lg.Warn(
  118. "'data-dir' was empty; using default",
  119. zap.String("data-dir", cfg.ec.Dir),
  120. )
  121. } else {
  122. plog.Warningf("no data-dir provided, using default data-dir ./%s", cfg.ec.Dir)
  123. }
  124. }
  125. var stopped <-chan struct{}
  126. var errc <-chan error
  127. which := identifyDataDirOrDie(cfg.ec.GetLogger(), cfg.ec.Dir)
  128. if which != dirEmpty {
  129. if lg != nil {
  130. } else {
  131. plog.Noticef("the server is already initialized as %v before, starting as etcd %v...", which, which)
  132. }
  133. switch which {
  134. case dirMember:
  135. stopped, errc, err = startEtcd(&cfg.ec)
  136. case dirProxy:
  137. err = startProxy(cfg)
  138. default:
  139. plog.Panicf("unhandled dir type %v", which)
  140. }
  141. } else {
  142. shouldProxy := cfg.isProxy()
  143. if !shouldProxy {
  144. stopped, errc, err = startEtcd(&cfg.ec)
  145. if derr, ok := err.(*etcdserver.DiscoveryError); ok && derr.Err == discovery.ErrFullCluster {
  146. if cfg.shouldFallbackToProxy() {
  147. if lg != nil {
  148. } else {
  149. plog.Noticef("discovery cluster full, falling back to %s", fallbackFlagProxy)
  150. }
  151. shouldProxy = true
  152. }
  153. }
  154. }
  155. if shouldProxy {
  156. err = startProxy(cfg)
  157. }
  158. }
  159. if err != nil {
  160. if derr, ok := err.(*etcdserver.DiscoveryError); ok {
  161. switch derr.Err {
  162. case discovery.ErrDuplicateID:
  163. if lg != nil {
  164. lg.Error(
  165. "member has been registered with discovery service",
  166. zap.String("name", cfg.ec.Name),
  167. zap.String("discovery-token", cfg.ec.Durl),
  168. zap.Error(derr.Err),
  169. )
  170. lg.Error(
  171. "but could not find valid cluster configuration",
  172. zap.String("data-dir", cfg.ec.Dir),
  173. )
  174. lg.Warn("check data dir if previous bootstrap succeeded")
  175. lg.Warn("or use a new discovery token if previous bootstrap failed")
  176. } else {
  177. plog.Errorf("member %q has previously registered with discovery service token (%s).", cfg.ec.Name, cfg.ec.Durl)
  178. plog.Errorf("But etcd could not find valid cluster configuration in the given data dir (%s).", cfg.ec.Dir)
  179. plog.Infof("Please check the given data dir path if the previous bootstrap succeeded")
  180. plog.Infof("or use a new discovery token if the previous bootstrap failed.")
  181. }
  182. case discovery.ErrDuplicateName:
  183. if lg != nil {
  184. lg.Error(
  185. "member with duplicated name has already been registered",
  186. zap.String("discovery-token", cfg.ec.Durl),
  187. zap.Error(derr.Err),
  188. )
  189. lg.Warn("cURL the discovery token URL for details")
  190. lg.Warn("do not reuse discovery token; generate a new one to bootstrap a cluster")
  191. } else {
  192. plog.Errorf("member with duplicated name has registered with discovery service token(%s).", cfg.ec.Durl)
  193. plog.Errorf("please check (cURL) the discovery token for more information.")
  194. plog.Errorf("please do not reuse the discovery token and generate a new one to bootstrap the cluster.")
  195. }
  196. default:
  197. if lg != nil {
  198. lg.Error(
  199. "failed to bootstrap; discovery token was already used",
  200. zap.String("discovery-token", cfg.ec.Durl),
  201. zap.Error(err),
  202. )
  203. lg.Warn("do not reuse discovery token; generate a new one to bootstrap a cluster")
  204. } else {
  205. plog.Errorf("%v", err)
  206. plog.Infof("discovery token %s was used, but failed to bootstrap the cluster.", cfg.ec.Durl)
  207. plog.Infof("please generate a new discovery token and try to bootstrap again.")
  208. }
  209. }
  210. os.Exit(1)
  211. }
  212. if strings.Contains(err.Error(), "include") && strings.Contains(err.Error(), "--initial-cluster") {
  213. if lg != nil {
  214. lg.Error("failed to start", zap.Error(err))
  215. } else {
  216. plog.Infof("%v", err)
  217. }
  218. if cfg.ec.InitialCluster == cfg.ec.InitialClusterFromName(cfg.ec.Name) {
  219. if lg != nil {
  220. lg.Warn("forgot to set --initial-cluster?")
  221. } else {
  222. plog.Infof("forgot to set --initial-cluster flag?")
  223. }
  224. }
  225. if types.URLs(cfg.ec.APUrls).String() == embed.DefaultInitialAdvertisePeerURLs {
  226. if lg != nil {
  227. lg.Warn("forgot to set --initial-advertise-peer-urls?")
  228. } else {
  229. plog.Infof("forgot to set --initial-advertise-peer-urls flag?")
  230. }
  231. }
  232. if cfg.ec.InitialCluster == cfg.ec.InitialClusterFromName(cfg.ec.Name) && len(cfg.ec.Durl) == 0 {
  233. if lg != nil {
  234. lg.Warn("--discovery flag is not set")
  235. } else {
  236. plog.Infof("if you want to use discovery service, please set --discovery flag.")
  237. }
  238. }
  239. os.Exit(1)
  240. }
  241. if lg != nil {
  242. lg.Fatal("discovery failed", zap.Error(err))
  243. } else {
  244. plog.Fatalf("%v", err)
  245. }
  246. }
  247. osutil.HandleInterrupts(lg)
  248. // At this point, the initialization of etcd is done.
  249. // The listeners are listening on the TCP ports and ready
  250. // for accepting connections. The etcd instance should be
  251. // joined with the cluster and ready to serve incoming
  252. // connections.
  253. notifySystemd(lg)
  254. select {
  255. case lerr := <-errc:
  256. // fatal out on listener errors
  257. if lg != nil {
  258. lg.Fatal("listener failed", zap.Error(err))
  259. } else {
  260. plog.Fatal(lerr)
  261. }
  262. case <-stopped:
  263. }
  264. osutil.Exit(0)
  265. }
  266. // startEtcd runs StartEtcd in addition to hooks needed for standalone etcd.
  267. func startEtcd(cfg *embed.Config) (<-chan struct{}, <-chan error, error) {
  268. e, err := embed.StartEtcd(cfg)
  269. if err != nil {
  270. return nil, nil, err
  271. }
  272. osutil.RegisterInterruptHandler(e.Close)
  273. select {
  274. case <-e.Server.ReadyNotify(): // wait for e.Server to join the cluster
  275. case <-e.Server.StopNotify(): // publish aborted from 'ErrStopped'
  276. }
  277. return e.Server.StopNotify(), e.Err(), nil
  278. }
  279. // startProxy launches an HTTP proxy for client communication which proxies to other etcd nodes.
  280. func startProxy(cfg *config) error {
  281. lg := cfg.ec.GetLogger()
  282. if lg != nil {
  283. lg.Info("v2 API proxy starting")
  284. } else {
  285. plog.Notice("proxy: this proxy supports v2 API only!")
  286. }
  287. clientTLSInfo := cfg.ec.ClientTLSInfo
  288. if clientTLSInfo.Empty() {
  289. // Support old proxy behavior of defaulting to PeerTLSInfo
  290. // for both client and peer connections.
  291. clientTLSInfo = cfg.ec.PeerTLSInfo
  292. }
  293. clientTLSInfo.InsecureSkipVerify = cfg.ec.ClientAutoTLS
  294. cfg.ec.PeerTLSInfo.InsecureSkipVerify = cfg.ec.PeerAutoTLS
  295. pt, err := transport.NewTimeoutTransport(clientTLSInfo, time.Duration(cfg.cp.ProxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.cp.ProxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.cp.ProxyWriteTimeoutMs)*time.Millisecond)
  296. if err != nil {
  297. return err
  298. }
  299. pt.MaxIdleConnsPerHost = httpproxy.DefaultMaxIdleConnsPerHost
  300. if err = cfg.ec.PeerSelfCert(); err != nil {
  301. if lg != nil {
  302. lg.Fatal("failed to get self-signed certs for peer", zap.Error(err))
  303. } else {
  304. plog.Fatalf("could not get certs (%v)", err)
  305. }
  306. }
  307. tr, err := transport.NewTimeoutTransport(cfg.ec.PeerTLSInfo, time.Duration(cfg.cp.ProxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.cp.ProxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.cp.ProxyWriteTimeoutMs)*time.Millisecond)
  308. if err != nil {
  309. return err
  310. }
  311. cfg.ec.Dir = filepath.Join(cfg.ec.Dir, "proxy")
  312. err = os.MkdirAll(cfg.ec.Dir, fileutil.PrivateDirMode)
  313. if err != nil {
  314. return err
  315. }
  316. var peerURLs []string
  317. clusterfile := filepath.Join(cfg.ec.Dir, "cluster")
  318. b, err := ioutil.ReadFile(clusterfile)
  319. switch {
  320. case err == nil:
  321. if cfg.ec.Durl != "" {
  322. if lg != nil {
  323. lg.Warn(
  324. "discovery token ignored since the proxy has already been initialized; valid cluster file found",
  325. zap.String("cluster-file", clusterfile),
  326. )
  327. } else {
  328. plog.Warningf("discovery token ignored since the proxy has already been initialized. Valid cluster file found at %q", clusterfile)
  329. }
  330. }
  331. if cfg.ec.DNSCluster != "" {
  332. if lg != nil {
  333. lg.Warn(
  334. "DNS SRV discovery ignored since the proxy has already been initialized; valid cluster file found",
  335. zap.String("cluster-file", clusterfile),
  336. )
  337. } else {
  338. plog.Warningf("DNS SRV discovery ignored since the proxy has already been initialized. Valid cluster file found at %q", clusterfile)
  339. }
  340. }
  341. urls := struct{ PeerURLs []string }{}
  342. err = json.Unmarshal(b, &urls)
  343. if err != nil {
  344. return err
  345. }
  346. peerURLs = urls.PeerURLs
  347. if lg != nil {
  348. lg.Info(
  349. "proxy using peer URLS from cluster file",
  350. zap.Strings("peer-urls", peerURLs),
  351. zap.String("cluster-file", clusterfile),
  352. )
  353. } else {
  354. plog.Infof("proxy: using peer urls %v from cluster file %q", peerURLs, clusterfile)
  355. }
  356. case os.IsNotExist(err):
  357. var urlsmap types.URLsMap
  358. urlsmap, _, err = cfg.ec.PeerURLsMapAndToken("proxy")
  359. if err != nil {
  360. return fmt.Errorf("error setting up initial cluster: %v", err)
  361. }
  362. if cfg.ec.Durl != "" {
  363. var s string
  364. s, err = discovery.GetCluster(cfg.ec.Durl, cfg.ec.Dproxy)
  365. if err != nil {
  366. return err
  367. }
  368. if urlsmap, err = types.NewURLsMap(s); err != nil {
  369. return err
  370. }
  371. }
  372. peerURLs = urlsmap.URLs()
  373. if lg != nil {
  374. lg.Info("proxy using peer URLS", zap.Strings("peer-urls", peerURLs))
  375. } else {
  376. plog.Infof("proxy: using peer urls %v ", peerURLs)
  377. }
  378. default:
  379. return err
  380. }
  381. clientURLs := []string{}
  382. uf := func() []string {
  383. gcls, gerr := etcdserver.GetClusterFromRemotePeers(lg, peerURLs, tr)
  384. if gerr != nil {
  385. if lg != nil {
  386. lg.Warn(
  387. "failed to get cluster from remote peers",
  388. zap.Strings("peer-urls", peerURLs),
  389. zap.Error(gerr),
  390. )
  391. } else {
  392. plog.Warningf("proxy: %v", gerr)
  393. }
  394. return []string{}
  395. }
  396. clientURLs = gcls.ClientURLs()
  397. urls := struct{ PeerURLs []string }{gcls.PeerURLs()}
  398. b, jerr := json.Marshal(urls)
  399. if jerr != nil {
  400. if lg != nil {
  401. lg.Warn("proxy failed to marshal peer URLs", zap.Error(jerr))
  402. } else {
  403. plog.Warningf("proxy: error on marshal peer urls %s", jerr)
  404. }
  405. return clientURLs
  406. }
  407. err = pkgioutil.WriteAndSyncFile(clusterfile+".bak", b, 0600)
  408. if err != nil {
  409. if lg != nil {
  410. lg.Warn("proxy failed to write cluster file", zap.Error(err))
  411. } else {
  412. plog.Warningf("proxy: error on writing urls %s", err)
  413. }
  414. return clientURLs
  415. }
  416. err = os.Rename(clusterfile+".bak", clusterfile)
  417. if err != nil {
  418. if lg != nil {
  419. lg.Warn(
  420. "proxy failed to rename cluster file",
  421. zap.String("path", clusterfile),
  422. zap.Error(err),
  423. )
  424. } else {
  425. plog.Warningf("proxy: error on updating clusterfile %s", err)
  426. }
  427. return clientURLs
  428. }
  429. if !reflect.DeepEqual(gcls.PeerURLs(), peerURLs) {
  430. if lg != nil {
  431. lg.Info(
  432. "proxy updated peer URLs",
  433. zap.Strings("from", peerURLs),
  434. zap.Strings("to", gcls.PeerURLs()),
  435. )
  436. } else {
  437. plog.Noticef("proxy: updated peer urls in cluster file from %v to %v", peerURLs, gcls.PeerURLs())
  438. }
  439. }
  440. peerURLs = gcls.PeerURLs()
  441. return clientURLs
  442. }
  443. ph := httpproxy.NewHandler(pt, uf, time.Duration(cfg.cp.ProxyFailureWaitMs)*time.Millisecond, time.Duration(cfg.cp.ProxyRefreshIntervalMs)*time.Millisecond)
  444. ph = embed.WrapCORS(cfg.ec.CORS, ph)
  445. if cfg.isReadonlyProxy() {
  446. ph = httpproxy.NewReadonlyHandler(ph)
  447. }
  448. // setup self signed certs when serving https
  449. cHosts, cTLS := []string{}, false
  450. for _, u := range cfg.ec.LCUrls {
  451. cHosts = append(cHosts, u.Host)
  452. cTLS = cTLS || u.Scheme == "https"
  453. }
  454. for _, u := range cfg.ec.ACUrls {
  455. cHosts = append(cHosts, u.Host)
  456. cTLS = cTLS || u.Scheme == "https"
  457. }
  458. listenerTLS := cfg.ec.ClientTLSInfo
  459. if cfg.ec.ClientAutoTLS && cTLS {
  460. listenerTLS, err = transport.SelfCert(cfg.ec.GetLogger(), filepath.Join(cfg.ec.Dir, "clientCerts"), cHosts)
  461. if err != nil {
  462. if lg != nil {
  463. lg.Fatal("failed to initialize self-signed client cert", zap.Error(err))
  464. } else {
  465. plog.Fatalf("proxy: could not initialize self-signed client certs (%v)", err)
  466. }
  467. }
  468. }
  469. // Start a proxy server goroutine for each listen address
  470. for _, u := range cfg.ec.LCUrls {
  471. l, err := transport.NewListener(u.Host, u.Scheme, &listenerTLS)
  472. if err != nil {
  473. return err
  474. }
  475. host := u.String()
  476. go func() {
  477. if lg != nil {
  478. lg.Info("proxy started listening on client requests", zap.String("host", host))
  479. } else {
  480. plog.Info("proxy: listening for client requests on ", host)
  481. }
  482. mux := http.NewServeMux()
  483. etcdhttp.HandlePrometheus(mux) // v2 proxy just uses the same port
  484. mux.Handle("/", ph)
  485. plog.Fatal(http.Serve(l, mux))
  486. }()
  487. }
  488. return nil
  489. }
  490. // identifyDataDirOrDie returns the type of the data dir.
  491. // Dies if the datadir is invalid.
  492. func identifyDataDirOrDie(lg *zap.Logger, dir string) dirType {
  493. names, err := fileutil.ReadDir(dir)
  494. if err != nil {
  495. if os.IsNotExist(err) {
  496. return dirEmpty
  497. }
  498. if lg != nil {
  499. lg.Fatal("failed to list data directory", zap.String("dir", dir), zap.Error(err))
  500. } else {
  501. plog.Fatalf("error listing data dir: %s", dir)
  502. }
  503. }
  504. var m, p bool
  505. for _, name := range names {
  506. switch dirType(name) {
  507. case dirMember:
  508. m = true
  509. case dirProxy:
  510. p = true
  511. default:
  512. if lg != nil {
  513. lg.Warn(
  514. "found invalid file under data directory",
  515. zap.String("filename", name),
  516. zap.String("data-dir", dir),
  517. )
  518. } else {
  519. plog.Warningf("found invalid file/dir %s under data dir %s (Ignore this if you are upgrading etcd)", name, dir)
  520. }
  521. }
  522. }
  523. if m && p {
  524. if lg != nil {
  525. lg.Fatal("invalid datadir; both member and proxy directories exist")
  526. } else {
  527. plog.Fatal("invalid datadir. Both member and proxy directories exist.")
  528. }
  529. }
  530. if m {
  531. return dirMember
  532. }
  533. if p {
  534. return dirProxy
  535. }
  536. return dirEmpty
  537. }
  538. func checkSupportArch() {
  539. // TODO qualify arm64
  540. if runtime.GOARCH == "amd64" || runtime.GOARCH == "ppc64le" {
  541. return
  542. }
  543. // unsupported arch only configured via environment variable
  544. // so unset here to not parse through flag
  545. defer os.Unsetenv("ETCD_UNSUPPORTED_ARCH")
  546. if env, ok := os.LookupEnv("ETCD_UNSUPPORTED_ARCH"); ok && env == runtime.GOARCH {
  547. fmt.Printf("running etcd on unsupported architecture %q since ETCD_UNSUPPORTED_ARCH is set\n", env)
  548. return
  549. }
  550. fmt.Printf("etcd on unsupported platform without ETCD_UNSUPPORTED_ARCH=%s set\n", runtime.GOARCH)
  551. os.Exit(1)
  552. }