etcd.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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. "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. sent, err := daemon.SdNotify("READY=1")
  164. if err != nil {
  165. plog.Errorf("failed to notify systemd for readiness: %v", err)
  166. }
  167. if !sent {
  168. plog.Errorf("forgot to set Type=notify in systemd service file?")
  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. var (
  177. urlsmap types.URLsMap
  178. token string
  179. err error
  180. )
  181. if !isMemberInitialized(cfg) {
  182. urlsmap, token, err = getPeerURLsMapAndToken(cfg, "etcd")
  183. if err != nil {
  184. return nil, fmt.Errorf("error setting up initial cluster: %v", err)
  185. }
  186. }
  187. if cfg.PeerAutoTLS && cfg.peerTLSInfo.Empty() {
  188. var phosts []string
  189. for _, u := range cfg.lpurls {
  190. phosts = append(phosts, u.Host)
  191. }
  192. cfg.peerTLSInfo, err = transport.SelfCert(path.Join(cfg.Dir, "fixtures/peer"), phosts)
  193. if err != nil {
  194. plog.Fatalf("could not get certs (%v)", err)
  195. }
  196. } else if cfg.PeerAutoTLS {
  197. plog.Warningf("ignoring peer auto TLS since certs given")
  198. }
  199. if !cfg.peerTLSInfo.Empty() {
  200. plog.Infof("peerTLS: %s", cfg.peerTLSInfo)
  201. }
  202. var plns []net.Listener
  203. for _, u := range cfg.lpurls {
  204. if u.Scheme == "http" {
  205. if !cfg.peerTLSInfo.Empty() {
  206. plog.Warningf("The scheme of peer url %s is HTTP while peer key/cert files are presented. Ignored peer key/cert files.", u.String())
  207. }
  208. if cfg.peerTLSInfo.ClientCertAuth {
  209. 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())
  210. }
  211. }
  212. var (
  213. l net.Listener
  214. tlscfg *tls.Config
  215. )
  216. if !cfg.peerTLSInfo.Empty() {
  217. tlscfg, err = cfg.peerTLSInfo.ServerConfig()
  218. if err != nil {
  219. return nil, err
  220. }
  221. }
  222. l, err = rafthttp.NewListener(u, tlscfg)
  223. if err != nil {
  224. return nil, err
  225. }
  226. urlStr := u.String()
  227. plog.Info("listening for peers on ", urlStr)
  228. defer func() {
  229. if err != nil {
  230. l.Close()
  231. plog.Info("stopping listening for peers on ", urlStr)
  232. }
  233. }()
  234. plns = append(plns, l)
  235. }
  236. if cfg.ClientAutoTLS && cfg.clientTLSInfo.Empty() {
  237. var chosts []string
  238. for _, u := range cfg.lcurls {
  239. chosts = append(chosts, u.Host)
  240. }
  241. cfg.clientTLSInfo, err = transport.SelfCert(path.Join(cfg.Dir, "fixtures/client"), chosts)
  242. if err != nil {
  243. plog.Fatalf("could not get certs (%v)", err)
  244. }
  245. } else if cfg.ClientAutoTLS {
  246. plog.Warningf("ignoring client auto TLS since certs given")
  247. }
  248. var ctlscfg *tls.Config
  249. if !cfg.clientTLSInfo.Empty() {
  250. plog.Infof("clientTLS: %s", cfg.clientTLSInfo)
  251. ctlscfg, err = cfg.clientTLSInfo.ServerConfig()
  252. if err != nil {
  253. return nil, err
  254. }
  255. }
  256. sctxs := make(map[string]*serveCtx)
  257. for _, u := range cfg.lcurls {
  258. if u.Scheme == "http" {
  259. if !cfg.clientTLSInfo.Empty() {
  260. plog.Warningf("The scheme of client url %s is HTTP while peer key/cert files are presented. Ignored key/cert files.", u.String())
  261. }
  262. if cfg.clientTLSInfo.ClientCertAuth {
  263. 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())
  264. }
  265. }
  266. if u.Scheme == "https" && ctlscfg == nil {
  267. return nil, fmt.Errorf("TLS key/cert (--cert-file, --key-file) must be provided for client url %s with HTTPs scheme", u.String())
  268. }
  269. ctx := &serveCtx{host: u.Host}
  270. if u.Scheme == "https" {
  271. ctx.secure = true
  272. } else {
  273. ctx.insecure = true
  274. }
  275. if sctxs[u.Host] != nil {
  276. if ctx.secure {
  277. sctxs[u.Host].secure = true
  278. }
  279. if ctx.insecure {
  280. sctxs[u.Host].insecure = true
  281. }
  282. continue
  283. }
  284. var l net.Listener
  285. l, err = net.Listen("tcp", u.Host)
  286. if err != nil {
  287. return nil, err
  288. }
  289. var fdLimit uint64
  290. if fdLimit, err = runtimeutil.FDLimit(); err == nil {
  291. if fdLimit <= reservedInternalFDNum {
  292. 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)
  293. }
  294. l = transport.LimitListener(l, int(fdLimit-reservedInternalFDNum))
  295. }
  296. l, err = transport.NewKeepAliveListener(l, "tcp", nil)
  297. ctx.l = l
  298. if err != nil {
  299. return nil, err
  300. }
  301. plog.Info("listening for client requests on ", u.Host)
  302. defer func() {
  303. if err != nil {
  304. l.Close()
  305. plog.Info("stopping listening for client requests on ", u.Host)
  306. }
  307. }()
  308. sctxs[u.Host] = ctx
  309. }
  310. srvcfg := &etcdserver.ServerConfig{
  311. Name: cfg.Name,
  312. ClientURLs: cfg.acurls,
  313. PeerURLs: cfg.apurls,
  314. DataDir: cfg.Dir,
  315. DedicatedWALDir: cfg.WalDir,
  316. SnapCount: cfg.SnapCount,
  317. MaxSnapFiles: cfg.MaxSnapFiles,
  318. MaxWALFiles: cfg.MaxWalFiles,
  319. InitialPeerURLsMap: urlsmap,
  320. InitialClusterToken: token,
  321. DiscoveryURL: cfg.Durl,
  322. DiscoveryProxy: cfg.Dproxy,
  323. NewCluster: cfg.isNewCluster(),
  324. ForceNewCluster: cfg.ForceNewCluster,
  325. PeerTLSInfo: cfg.peerTLSInfo,
  326. TickMs: cfg.TickMs,
  327. ElectionTicks: cfg.electionTicks(),
  328. AutoCompactionRetention: cfg.autoCompactionRetention,
  329. QuotaBackendBytes: cfg.QuotaBackendBytes,
  330. StrictReconfigCheck: cfg.StrictReconfigCheck,
  331. EnablePprof: cfg.enablePprof,
  332. ClientCertAuthEnabled: cfg.clientTLSInfo.ClientCertAuth,
  333. }
  334. var s *etcdserver.EtcdServer
  335. s, err = etcdserver.NewServer(srvcfg)
  336. if err != nil {
  337. return nil, err
  338. }
  339. s.Start()
  340. osutil.RegisterInterruptHandler(s.Stop)
  341. if cfg.corsInfo.String() != "" {
  342. plog.Infof("cors = %s", cfg.corsInfo)
  343. }
  344. ch := http.Handler(&cors.CORSHandler{
  345. Handler: v2http.NewClientHandler(s, srvcfg.ReqTimeout()),
  346. Info: cfg.corsInfo,
  347. })
  348. ph := v2http.NewPeerHandler(s)
  349. // Start the peer server in a goroutine
  350. for _, l := range plns {
  351. go func(l net.Listener) {
  352. plog.Fatal(servePeerHTTP(l, ph))
  353. }(l)
  354. }
  355. // Start a client server goroutine for each listen address
  356. for _, sctx := range sctxs {
  357. go func(sctx *serveCtx) {
  358. // read timeout does not work with http close notify
  359. // TODO: https://github.com/golang/go/issues/9524
  360. plog.Fatal(serve(sctx, s, ctlscfg, ch))
  361. }(sctx)
  362. }
  363. <-s.ReadyNotify()
  364. return s.StopNotify(), nil
  365. }
  366. // startProxy launches an HTTP proxy for client communication which proxies to other etcd nodes.
  367. func startProxy(cfg *config) error {
  368. plog.Notice("proxy: this proxy supports v2 API only!")
  369. pt, err := transport.NewTimeoutTransport(cfg.peerTLSInfo, time.Duration(cfg.ProxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.ProxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.ProxyWriteTimeoutMs)*time.Millisecond)
  370. if err != nil {
  371. return err
  372. }
  373. pt.MaxIdleConnsPerHost = httpproxy.DefaultMaxIdleConnsPerHost
  374. tr, err := transport.NewTimeoutTransport(cfg.peerTLSInfo, time.Duration(cfg.ProxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.ProxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.ProxyWriteTimeoutMs)*time.Millisecond)
  375. if err != nil {
  376. return err
  377. }
  378. cfg.Dir = path.Join(cfg.Dir, "proxy")
  379. err = os.MkdirAll(cfg.Dir, privateDirMode)
  380. if err != nil {
  381. return err
  382. }
  383. var peerURLs []string
  384. clusterfile := path.Join(cfg.Dir, "cluster")
  385. b, err := ioutil.ReadFile(clusterfile)
  386. switch {
  387. case err == nil:
  388. if cfg.Durl != "" {
  389. plog.Warningf("discovery token ignored since the proxy has already been initialized. Valid cluster file found at %q", clusterfile)
  390. }
  391. if cfg.DnsCluster != "" {
  392. plog.Warningf("DNS SRV discovery ignored since the proxy has already been initialized. Valid cluster file found at %q", clusterfile)
  393. }
  394. urls := struct{ PeerURLs []string }{}
  395. err = json.Unmarshal(b, &urls)
  396. if err != nil {
  397. return err
  398. }
  399. peerURLs = urls.PeerURLs
  400. plog.Infof("proxy: using peer urls %v from cluster file %q", peerURLs, clusterfile)
  401. case os.IsNotExist(err):
  402. var urlsmap types.URLsMap
  403. urlsmap, _, err = getPeerURLsMapAndToken(cfg, "proxy")
  404. if err != nil {
  405. return fmt.Errorf("error setting up initial cluster: %v", err)
  406. }
  407. if cfg.Durl != "" {
  408. var s string
  409. s, err = discovery.GetCluster(cfg.Durl, cfg.Dproxy)
  410. if err != nil {
  411. return err
  412. }
  413. if urlsmap, err = types.NewURLsMap(s); err != nil {
  414. return err
  415. }
  416. }
  417. peerURLs = urlsmap.URLs()
  418. plog.Infof("proxy: using peer urls %v ", peerURLs)
  419. default:
  420. return err
  421. }
  422. clientURLs := []string{}
  423. uf := func() []string {
  424. gcls, gerr := etcdserver.GetClusterFromRemotePeers(peerURLs, tr)
  425. // TODO: remove the 2nd check when we fix GetClusterFromRemotePeers
  426. // GetClusterFromRemotePeers should not return nil error with an invalid empty cluster
  427. if gerr != nil {
  428. plog.Warningf("proxy: %v", gerr)
  429. return []string{}
  430. }
  431. if len(gcls.Members()) == 0 {
  432. return clientURLs
  433. }
  434. clientURLs = gcls.ClientURLs()
  435. urls := struct{ PeerURLs []string }{gcls.PeerURLs()}
  436. b, jerr := json.Marshal(urls)
  437. if jerr != nil {
  438. plog.Warningf("proxy: error on marshal peer urls %s", jerr)
  439. return clientURLs
  440. }
  441. err = pkgioutil.WriteAndSyncFile(clusterfile+".bak", b, 0600)
  442. if err != nil {
  443. plog.Warningf("proxy: error on writing urls %s", err)
  444. return clientURLs
  445. }
  446. err = os.Rename(clusterfile+".bak", clusterfile)
  447. if err != nil {
  448. plog.Warningf("proxy: error on updating clusterfile %s", err)
  449. return clientURLs
  450. }
  451. if !reflect.DeepEqual(gcls.PeerURLs(), peerURLs) {
  452. plog.Noticef("proxy: updated peer urls in cluster file from %v to %v", peerURLs, gcls.PeerURLs())
  453. }
  454. peerURLs = gcls.PeerURLs()
  455. return clientURLs
  456. }
  457. ph := httpproxy.NewHandler(pt, uf, time.Duration(cfg.ProxyFailureWaitMs)*time.Millisecond, time.Duration(cfg.ProxyRefreshIntervalMs)*time.Millisecond)
  458. ph = &cors.CORSHandler{
  459. Handler: ph,
  460. Info: cfg.corsInfo,
  461. }
  462. if cfg.isReadonlyProxy() {
  463. ph = httpproxy.NewReadonlyHandler(ph)
  464. }
  465. // Start a proxy server goroutine for each listen address
  466. for _, u := range cfg.lcurls {
  467. var (
  468. l net.Listener
  469. tlscfg *tls.Config
  470. )
  471. if !cfg.clientTLSInfo.Empty() {
  472. tlscfg, err = cfg.clientTLSInfo.ServerConfig()
  473. if err != nil {
  474. return err
  475. }
  476. }
  477. l, err := transport.NewListener(u.Host, u.Scheme, tlscfg)
  478. if err != nil {
  479. return err
  480. }
  481. host := u.String()
  482. go func() {
  483. plog.Info("proxy: listening for client requests on ", host)
  484. mux := http.NewServeMux()
  485. mux.Handle("/metrics", prometheus.Handler())
  486. mux.Handle("/", ph)
  487. plog.Fatal(http.Serve(l, mux))
  488. }()
  489. }
  490. return nil
  491. }
  492. // getPeerURLsMapAndToken sets up an initial peer URLsMap and cluster token for bootstrap or discovery.
  493. func getPeerURLsMapAndToken(cfg *config, which string) (urlsmap types.URLsMap, token string, err error) {
  494. switch {
  495. case cfg.Durl != "":
  496. urlsmap = types.URLsMap{}
  497. // If using discovery, generate a temporary cluster based on
  498. // self's advertised peer URLs
  499. urlsmap[cfg.Name] = cfg.apurls
  500. token = cfg.Durl
  501. case cfg.DnsCluster != "":
  502. var clusterStr string
  503. clusterStr, token, err = discovery.SRVGetCluster(cfg.Name, cfg.DnsCluster, cfg.InitialClusterToken, cfg.apurls)
  504. if err != nil {
  505. return nil, "", err
  506. }
  507. if strings.Contains(clusterStr, "https://") && cfg.peerTLSInfo.CAFile == "" {
  508. cfg.peerTLSInfo.ServerName = cfg.DnsCluster
  509. }
  510. urlsmap, err = types.NewURLsMap(clusterStr)
  511. // only etcd member must belong to the discovered cluster.
  512. // proxy does not need to belong to the discovered cluster.
  513. if which == "etcd" {
  514. if _, ok := urlsmap[cfg.Name]; !ok {
  515. return nil, "", fmt.Errorf("cannot find local etcd member %q in SRV records", cfg.Name)
  516. }
  517. }
  518. default:
  519. // We're statically configured, and cluster has appropriately been set.
  520. urlsmap, err = types.NewURLsMap(cfg.InitialCluster)
  521. token = cfg.InitialClusterToken
  522. }
  523. return urlsmap, token, err
  524. }
  525. // identifyDataDirOrDie returns the type of the data dir.
  526. // Dies if the datadir is invalid.
  527. func identifyDataDirOrDie(dir string) dirType {
  528. names, err := fileutil.ReadDir(dir)
  529. if err != nil {
  530. if os.IsNotExist(err) {
  531. return dirEmpty
  532. }
  533. plog.Fatalf("error listing data dir: %s", dir)
  534. }
  535. var m, p bool
  536. for _, name := range names {
  537. switch dirType(name) {
  538. case dirMember:
  539. m = true
  540. case dirProxy:
  541. p = true
  542. default:
  543. plog.Warningf("found invalid file/dir %s under data dir %s (Ignore this if you are upgrading etcd)", name, dir)
  544. }
  545. }
  546. if m && p {
  547. plog.Fatal("invalid datadir. Both member and proxy directories exist.")
  548. }
  549. if m {
  550. return dirMember
  551. }
  552. if p {
  553. return dirProxy
  554. }
  555. return dirEmpty
  556. }
  557. func setupLogging(cfg *config) {
  558. capnslog.SetGlobalLogLevel(capnslog.INFO)
  559. if cfg.Debug {
  560. capnslog.SetGlobalLogLevel(capnslog.DEBUG)
  561. }
  562. if cfg.LogPkgLevels != "" {
  563. repoLog := capnslog.MustRepoLogger("github.com/coreos/etcd")
  564. settings, err := repoLog.ParseLogLevelConfig(cfg.LogPkgLevels)
  565. if err != nil {
  566. plog.Warningf("couldn't parse log level string: %s, continuing with default levels", err.Error())
  567. return
  568. }
  569. repoLog.SetLogLevel(settings)
  570. }
  571. }
  572. func checkSupportArch() {
  573. // TODO qualify arm64
  574. if runtime.GOARCH == "amd64" {
  575. return
  576. }
  577. if env, ok := os.LookupEnv("ETCD_UNSUPPORTED_ARCH"); ok && env == runtime.GOARCH {
  578. plog.Warningf("running etcd on unsupported architecture %q since ETCD_UNSUPPORTED_ARCH is set", env)
  579. return
  580. }
  581. plog.Errorf("etcd on unsupported platform without ETCD_UNSUPPORTED_ARCH=%s set.", runtime.GOARCH)
  582. os.Exit(1)
  583. }