etcd.go 19 KB

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