etcd.go 17 KB

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