etcd.go 19 KB

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