etcd.go 17 KB

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