etcd.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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. "encoding/json"
  17. "fmt"
  18. "io/ioutil"
  19. "net"
  20. "net/http"
  21. _ "net/http/pprof"
  22. "os"
  23. "path"
  24. "reflect"
  25. "runtime"
  26. "strings"
  27. "time"
  28. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/go-systemd/daemon"
  29. systemdutil "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/go-systemd/util"
  30. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/pkg/capnslog"
  31. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus"
  32. "github.com/coreos/etcd/discovery"
  33. "github.com/coreos/etcd/etcdserver"
  34. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  35. "github.com/coreos/etcd/etcdserver/etcdhttp"
  36. "github.com/coreos/etcd/pkg/cors"
  37. "github.com/coreos/etcd/pkg/fileutil"
  38. pkgioutil "github.com/coreos/etcd/pkg/ioutil"
  39. "github.com/coreos/etcd/pkg/osutil"
  40. runtimeutil "github.com/coreos/etcd/pkg/runtime"
  41. "github.com/coreos/etcd/pkg/transport"
  42. "github.com/coreos/etcd/pkg/types"
  43. "github.com/coreos/etcd/proxy"
  44. "github.com/coreos/etcd/rafthttp"
  45. "github.com/coreos/etcd/version"
  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. 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.
  161. // The http server is probably ready for serving incoming
  162. // connections. If it is not, the connection might be pending
  163. // for less than one second.
  164. err := daemon.SdNotify("READY=1")
  165. if err != nil {
  166. plog.Errorf("failed to notify systemd for readiness: %v", err)
  167. if err == daemon.SdNotifyNoSocket {
  168. plog.Errorf("forgot to set Type=notify in systemd service file?")
  169. }
  170. }
  171. }
  172. <-stopped
  173. osutil.Exit(0)
  174. }
  175. // startEtcd launches the etcd server and HTTP handlers for client/server communication.
  176. func startEtcd(cfg *config) (<-chan struct{}, error) {
  177. urlsmap, token, err := getPeerURLsMapAndToken(cfg, "etcd")
  178. if err != nil {
  179. return nil, fmt.Errorf("error setting up initial cluster: %v", err)
  180. }
  181. if !cfg.peerTLSInfo.Empty() {
  182. plog.Infof("peerTLS: %s", cfg.peerTLSInfo)
  183. }
  184. plns := make([]net.Listener, 0)
  185. for _, u := range cfg.lpurls {
  186. if u.Scheme == "http" && !cfg.peerTLSInfo.Empty() {
  187. plog.Warningf("The scheme of peer url %s is http while peer key/cert files are presented. Ignored peer key/cert files.", u.String())
  188. }
  189. var l net.Listener
  190. l, err = rafthttp.NewListener(u, cfg.peerTLSInfo)
  191. if err != nil {
  192. return nil, err
  193. }
  194. urlStr := u.String()
  195. plog.Info("listening for peers on ", urlStr)
  196. defer func() {
  197. if err != nil {
  198. l.Close()
  199. plog.Info("stopping listening for peers on ", urlStr)
  200. }
  201. }()
  202. plns = append(plns, l)
  203. }
  204. if !cfg.clientTLSInfo.Empty() {
  205. plog.Infof("clientTLS: %s", cfg.clientTLSInfo)
  206. }
  207. clns := make([]net.Listener, 0)
  208. for _, u := range cfg.lcurls {
  209. if u.Scheme == "http" && !cfg.clientTLSInfo.Empty() {
  210. plog.Warningf("The scheme of client url %s is http while client key/cert files are presented. Ignored client key/cert files.", u.String())
  211. }
  212. var l net.Listener
  213. l, err = net.Listen("tcp", u.Host)
  214. if err != nil {
  215. return nil, err
  216. }
  217. if fdLimit, err := runtimeutil.FDLimit(); err == nil {
  218. if fdLimit <= reservedInternalFDNum {
  219. 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)
  220. }
  221. l = transport.LimitListener(l, int(fdLimit-reservedInternalFDNum))
  222. }
  223. // Do not wrap around this listener if TLS Info is set.
  224. // HTTPS server expects TLS Conn created by TLSListener.
  225. l, err = transport.NewKeepAliveListener(l, u.Scheme, cfg.clientTLSInfo)
  226. if err != nil {
  227. return nil, err
  228. }
  229. urlStr := u.String()
  230. plog.Info("listening for client requests on ", urlStr)
  231. defer func() {
  232. if err != nil {
  233. l.Close()
  234. plog.Info("stopping listening for client requests on ", urlStr)
  235. }
  236. }()
  237. clns = append(clns, l)
  238. }
  239. var v3l net.Listener
  240. if cfg.v3demo {
  241. v3l, err = net.Listen("tcp", cfg.gRPCAddr)
  242. if err != nil {
  243. plog.Fatal(err)
  244. }
  245. plog.Infof("listening for client rpc on %s", cfg.gRPCAddr)
  246. }
  247. srvcfg := &etcdserver.ServerConfig{
  248. Name: cfg.name,
  249. ClientURLs: cfg.acurls,
  250. PeerURLs: cfg.apurls,
  251. DataDir: cfg.dir,
  252. DedicatedWALDir: cfg.walDir,
  253. SnapCount: cfg.snapCount,
  254. MaxSnapFiles: cfg.maxSnapFiles,
  255. MaxWALFiles: cfg.maxWalFiles,
  256. InitialPeerURLsMap: urlsmap,
  257. InitialClusterToken: token,
  258. DiscoveryURL: cfg.durl,
  259. DiscoveryProxy: cfg.dproxy,
  260. NewCluster: cfg.isNewCluster(),
  261. ForceNewCluster: cfg.forceNewCluster,
  262. PeerTLSInfo: cfg.peerTLSInfo,
  263. TickMs: cfg.TickMs,
  264. ElectionTicks: cfg.electionTicks(),
  265. V3demo: cfg.v3demo,
  266. AutoCompactionRetention: cfg.autoCompactionRetention,
  267. StrictReconfigCheck: cfg.strictReconfigCheck,
  268. EnablePprof: cfg.enablePprof,
  269. }
  270. var s *etcdserver.EtcdServer
  271. s, err = etcdserver.NewServer(srvcfg)
  272. if err != nil {
  273. return nil, err
  274. }
  275. s.Start()
  276. osutil.RegisterInterruptHandler(s.Stop)
  277. if cfg.corsInfo.String() != "" {
  278. plog.Infof("cors = %s", cfg.corsInfo)
  279. }
  280. ch := &cors.CORSHandler{
  281. Handler: etcdhttp.NewClientHandler(s, srvcfg.ReqTimeout()),
  282. Info: cfg.corsInfo,
  283. }
  284. ph := etcdhttp.NewPeerHandler(s)
  285. // Start the peer server in a goroutine
  286. for _, l := range plns {
  287. go func(l net.Listener) {
  288. plog.Fatal(serveHTTP(l, ph, 5*time.Minute))
  289. }(l)
  290. }
  291. // Start a client server goroutine for each listen address
  292. for _, l := range clns {
  293. go func(l net.Listener) {
  294. // read timeout does not work with http close notify
  295. // TODO: https://github.com/golang/go/issues/9524
  296. plog.Fatal(serveHTTP(l, ch, 0))
  297. }(l)
  298. }
  299. if cfg.v3demo {
  300. // set up v3 demo rpc
  301. tls := &cfg.clientTLSInfo
  302. if cfg.clientTLSInfo.Empty() {
  303. tls = nil
  304. }
  305. grpcServer, err := v3rpc.Server(s, tls)
  306. if err != nil {
  307. s.Stop()
  308. <-s.StopNotify()
  309. return nil, err
  310. }
  311. go func() { plog.Fatal(grpcServer.Serve(v3l)) }()
  312. }
  313. return s.StopNotify(), nil
  314. }
  315. // startProxy launches an HTTP proxy for client communication which proxies to other etcd nodes.
  316. func startProxy(cfg *config) error {
  317. pt, err := transport.NewTimeoutTransport(cfg.peerTLSInfo, time.Duration(cfg.proxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyWriteTimeoutMs)*time.Millisecond)
  318. if err != nil {
  319. return err
  320. }
  321. pt.MaxIdleConnsPerHost = proxy.DefaultMaxIdleConnsPerHost
  322. tr, err := transport.NewTimeoutTransport(cfg.peerTLSInfo, time.Duration(cfg.proxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyWriteTimeoutMs)*time.Millisecond)
  323. if err != nil {
  324. return err
  325. }
  326. cfg.dir = path.Join(cfg.dir, "proxy")
  327. err = os.MkdirAll(cfg.dir, 0700)
  328. if err != nil {
  329. return err
  330. }
  331. var peerURLs []string
  332. clusterfile := path.Join(cfg.dir, "cluster")
  333. b, err := ioutil.ReadFile(clusterfile)
  334. switch {
  335. case err == nil:
  336. if cfg.durl != "" {
  337. plog.Warningf("discovery token ignored since the proxy has already been initialized. Valid cluster file found at %q", clusterfile)
  338. }
  339. if cfg.dnsCluster != "" {
  340. plog.Warningf("DNS SRV discovery ignored since the proxy has already been initialized. Valid cluster file found at %q", clusterfile)
  341. }
  342. urls := struct{ PeerURLs []string }{}
  343. err = json.Unmarshal(b, &urls)
  344. if err != nil {
  345. return err
  346. }
  347. peerURLs = urls.PeerURLs
  348. plog.Infof("proxy: using peer urls %v from cluster file %q", peerURLs, clusterfile)
  349. case os.IsNotExist(err):
  350. urlsmap, _, err := getPeerURLsMapAndToken(cfg, "proxy")
  351. if err != nil {
  352. return fmt.Errorf("error setting up initial cluster: %v", err)
  353. }
  354. if cfg.durl != "" {
  355. s, err := discovery.GetCluster(cfg.durl, cfg.dproxy)
  356. if err != nil {
  357. return err
  358. }
  359. if urlsmap, err = types.NewURLsMap(s); err != nil {
  360. return err
  361. }
  362. }
  363. peerURLs = urlsmap.URLs()
  364. plog.Infof("proxy: using peer urls %v ", peerURLs)
  365. default:
  366. return err
  367. }
  368. clientURLs := []string{}
  369. uf := func() []string {
  370. gcls, err := etcdserver.GetClusterFromRemotePeers(peerURLs, tr)
  371. // TODO: remove the 2nd check when we fix GetClusterFromRemotePeers
  372. // GetClusterFromRemotePeers should not return nil error with an invalid empty cluster
  373. if err != nil {
  374. plog.Warningf("proxy: %v", err)
  375. return []string{}
  376. }
  377. if len(gcls.Members()) == 0 {
  378. return clientURLs
  379. }
  380. clientURLs = gcls.ClientURLs()
  381. urls := struct{ PeerURLs []string }{gcls.PeerURLs()}
  382. b, err := json.Marshal(urls)
  383. if err != nil {
  384. plog.Warningf("proxy: error on marshal peer urls %s", err)
  385. return clientURLs
  386. }
  387. err = pkgioutil.WriteAndSyncFile(clusterfile+".bak", b, 0600)
  388. if err != nil {
  389. plog.Warningf("proxy: error on writing urls %s", err)
  390. return clientURLs
  391. }
  392. err = os.Rename(clusterfile+".bak", clusterfile)
  393. if err != nil {
  394. plog.Warningf("proxy: error on updating clusterfile %s", err)
  395. return clientURLs
  396. }
  397. if !reflect.DeepEqual(gcls.PeerURLs(), peerURLs) {
  398. plog.Noticef("proxy: updated peer urls in cluster file from %v to %v", peerURLs, gcls.PeerURLs())
  399. }
  400. peerURLs = gcls.PeerURLs()
  401. return clientURLs
  402. }
  403. ph := proxy.NewHandler(pt, uf, time.Duration(cfg.proxyFailureWaitMs)*time.Millisecond, time.Duration(cfg.proxyRefreshIntervalMs)*time.Millisecond)
  404. ph = &cors.CORSHandler{
  405. Handler: ph,
  406. Info: cfg.corsInfo,
  407. }
  408. if cfg.isReadonlyProxy() {
  409. ph = proxy.NewReadonlyHandler(ph)
  410. }
  411. // Start a proxy server goroutine for each listen address
  412. for _, u := range cfg.lcurls {
  413. l, err := transport.NewListener(u.Host, u.Scheme, cfg.clientTLSInfo)
  414. if err != nil {
  415. return err
  416. }
  417. host := u.String()
  418. go func() {
  419. plog.Info("proxy: listening for client requests on ", host)
  420. mux := http.NewServeMux()
  421. mux.Handle("/metrics", prometheus.Handler())
  422. mux.Handle("/", ph)
  423. plog.Fatal(http.Serve(l, mux))
  424. }()
  425. }
  426. return nil
  427. }
  428. // getPeerURLsMapAndToken sets up an initial peer URLsMap and cluster token for bootstrap or discovery.
  429. func getPeerURLsMapAndToken(cfg *config, which string) (urlsmap types.URLsMap, token string, err error) {
  430. switch {
  431. case cfg.durl != "":
  432. urlsmap = types.URLsMap{}
  433. // If using discovery, generate a temporary cluster based on
  434. // self's advertised peer URLs
  435. urlsmap[cfg.name] = cfg.apurls
  436. token = cfg.durl
  437. case cfg.dnsCluster != "":
  438. var clusterStr string
  439. clusterStr, token, err = discovery.SRVGetCluster(cfg.name, cfg.dnsCluster, cfg.initialClusterToken, cfg.apurls)
  440. if err != nil {
  441. return nil, "", err
  442. }
  443. urlsmap, err = types.NewURLsMap(clusterStr)
  444. // only etcd member must belong to the discovered cluster.
  445. // proxy does not need to belong to the discovered cluster.
  446. if which == "etcd" {
  447. if _, ok := urlsmap[cfg.name]; !ok {
  448. return nil, "", fmt.Errorf("cannot find local etcd member %q in SRV records", cfg.name)
  449. }
  450. }
  451. default:
  452. // We're statically configured, and cluster has appropriately been set.
  453. urlsmap, err = types.NewURLsMap(cfg.initialCluster)
  454. token = cfg.initialClusterToken
  455. }
  456. return urlsmap, token, err
  457. }
  458. // identifyDataDirOrDie returns the type of the data dir.
  459. // Dies if the datadir is invalid.
  460. func identifyDataDirOrDie(dir string) dirType {
  461. names, err := fileutil.ReadDir(dir)
  462. if err != nil {
  463. if os.IsNotExist(err) {
  464. return dirEmpty
  465. }
  466. plog.Fatalf("error listing data dir: %s", dir)
  467. }
  468. var m, p bool
  469. for _, name := range names {
  470. switch dirType(name) {
  471. case dirMember:
  472. m = true
  473. case dirProxy:
  474. p = true
  475. default:
  476. plog.Warningf("found invalid file/dir %s under data dir %s (Ignore this if you are upgrading etcd)", name, dir)
  477. }
  478. }
  479. if m && p {
  480. plog.Fatal("invalid datadir. Both member and proxy directories exist.")
  481. }
  482. if m {
  483. return dirMember
  484. }
  485. if p {
  486. return dirProxy
  487. }
  488. return dirEmpty
  489. }
  490. func setupLogging(cfg *config) {
  491. capnslog.SetGlobalLogLevel(capnslog.INFO)
  492. if cfg.debug {
  493. capnslog.SetGlobalLogLevel(capnslog.DEBUG)
  494. }
  495. if cfg.logPkgLevels != "" {
  496. repoLog := capnslog.MustRepoLogger("github.com/coreos/etcd")
  497. settings, err := repoLog.ParseLogLevelConfig(cfg.logPkgLevels)
  498. if err != nil {
  499. plog.Warningf("couldn't parse log level string: %s, continuing with default levels", err.Error())
  500. return
  501. }
  502. repoLog.SetLogLevel(settings)
  503. }
  504. }