etcd.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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. "os"
  22. "path"
  23. "reflect"
  24. "runtime"
  25. "strings"
  26. "time"
  27. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/go-systemd/daemon"
  28. systemdutil "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/go-systemd/util"
  29. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/pkg/capnslog"
  30. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus"
  31. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/netutil"
  32. "github.com/coreos/etcd/Godeps/_workspace/src/google.golang.org/grpc"
  33. "github.com/coreos/etcd/discovery"
  34. "github.com/coreos/etcd/etcdserver"
  35. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  36. "github.com/coreos/etcd/etcdserver/etcdhttp"
  37. "github.com/coreos/etcd/etcdserver/etcdserverpb"
  38. "github.com/coreos/etcd/pkg/cors"
  39. "github.com/coreos/etcd/pkg/fileutil"
  40. "github.com/coreos/etcd/pkg/osutil"
  41. runtimeutil "github.com/coreos/etcd/pkg/runtime"
  42. "github.com/coreos/etcd/pkg/transport"
  43. "github.com/coreos/etcd/pkg/types"
  44. "github.com/coreos/etcd/proxy"
  45. "github.com/coreos/etcd/rafthttp"
  46. "github.com/coreos/etcd/version"
  47. )
  48. type dirType string
  49. var plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "etcdmain")
  50. const (
  51. // the owner can make/remove files inside the directory
  52. privateDirMode = 0700
  53. // internal fd usage includes disk usage and transport usage.
  54. // To read/write snapshot, snap pkg needs 1. In normal case, wal pkg needs
  55. // at most 2 to read/lock/write WALs. One case that it needs to 2 is to
  56. // read all logs after some snapshot index, which locates at the end of
  57. // the second last and the head of the last. For purging, it needs to read
  58. // directory, so it needs 1. For fd monitor, it needs 1.
  59. // For transport, rafthttp builds two long-polling connections and at most
  60. // four temporary connections with each member. There are at most 9 members
  61. // in a cluster, so it should reserve 96.
  62. // For the safety, we set the total reserved number to 150.
  63. reservedInternalFDNum = 150
  64. )
  65. var (
  66. dirMember = dirType("member")
  67. dirProxy = dirType("proxy")
  68. dirEmpty = dirType("empty")
  69. )
  70. func Main() {
  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 err == discovery.ErrFullCluster && cfg.shouldFallbackToProxy() {
  113. plog.Noticef("discovery cluster full, falling back to %s", fallbackFlagProxy)
  114. shouldProxy = true
  115. }
  116. }
  117. if shouldProxy {
  118. err = startProxy(cfg)
  119. }
  120. }
  121. if err != nil {
  122. switch err {
  123. case discovery.ErrDuplicateID:
  124. plog.Errorf("member %q has previously registered with discovery service token (%s).", cfg.name, cfg.durl)
  125. plog.Errorf("But etcd could not find valid cluster configuration in the given data dir (%s).", cfg.dir)
  126. plog.Infof("Please check the given data dir path if the previous bootstrap succeeded")
  127. plog.Infof("or use a new discovery token if the previous bootstrap failed.")
  128. case discovery.ErrDuplicateName:
  129. plog.Errorf("member with duplicated name has registered with discovery service token(%s).", cfg.durl)
  130. plog.Errorf("please check (cURL) the discovery token for more information.")
  131. plog.Errorf("please do not reuse the discovery token and generate a new one to bootstrap the cluster.")
  132. default:
  133. if strings.Contains(err.Error(), "include") && strings.Contains(err.Error(), "--initial-cluster") {
  134. plog.Infof("%v", err)
  135. if cfg.initialCluster == initialClusterFromName(cfg.name) {
  136. plog.Infof("forgot to set --initial-cluster flag?")
  137. }
  138. if types.URLs(cfg.apurls).String() == defaultInitialAdvertisePeerURLs {
  139. plog.Infof("forgot to set --initial-advertise-peer-urls flag?")
  140. }
  141. if cfg.initialCluster == initialClusterFromName(cfg.name) && len(cfg.durl) == 0 {
  142. plog.Infof("if you want to use discovery service, please set --discovery flag.")
  143. }
  144. os.Exit(1)
  145. }
  146. if etcdserver.IsDiscoveryError(err) {
  147. plog.Errorf("%v", err)
  148. plog.Infof("discovery token %s was used, but failed to bootstrap the cluster.", cfg.durl)
  149. plog.Infof("please generate a new discovery token and try to bootstrap again.")
  150. os.Exit(1)
  151. }
  152. plog.Fatalf("%v", err)
  153. }
  154. os.Exit(1)
  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 = transport.NewTimeoutListener(u.Host, u.Scheme, cfg.peerTLSInfo, rafthttp.ConnReadTimeout, rafthttp.ConnWriteTimeout)
  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 = transport.NewKeepAliveListener(u.Host, u.Scheme, cfg.clientTLSInfo)
  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 = netutil.LimitListener(l, int(fdLimit-reservedInternalFDNum))
  222. }
  223. urlStr := u.String()
  224. plog.Info("listening for client requests on ", urlStr)
  225. defer func() {
  226. if err != nil {
  227. l.Close()
  228. plog.Info("stopping listening for client requests on ", urlStr)
  229. }
  230. }()
  231. clns = append(clns, l)
  232. }
  233. var v3l net.Listener
  234. if cfg.v3demo {
  235. v3l, err = net.Listen("tcp", cfg.gRPCAddr)
  236. if err != nil {
  237. plog.Fatal(err)
  238. }
  239. plog.Infof("listening for client rpc on %s", cfg.gRPCAddr)
  240. }
  241. srvcfg := &etcdserver.ServerConfig{
  242. Name: cfg.name,
  243. ClientURLs: cfg.acurls,
  244. PeerURLs: cfg.apurls,
  245. DataDir: cfg.dir,
  246. DedicatedWALDir: cfg.walDir,
  247. SnapCount: cfg.snapCount,
  248. MaxSnapFiles: cfg.maxSnapFiles,
  249. MaxWALFiles: cfg.maxWalFiles,
  250. InitialPeerURLsMap: urlsmap,
  251. InitialClusterToken: token,
  252. DiscoveryURL: cfg.durl,
  253. DiscoveryProxy: cfg.dproxy,
  254. NewCluster: cfg.isNewCluster(),
  255. ForceNewCluster: cfg.forceNewCluster,
  256. PeerTLSInfo: cfg.peerTLSInfo,
  257. TickMs: cfg.TickMs,
  258. ElectionTicks: cfg.electionTicks(),
  259. V3demo: cfg.v3demo,
  260. StrictReconfigCheck: cfg.strictReconfigCheck,
  261. }
  262. var s *etcdserver.EtcdServer
  263. s, err = etcdserver.NewServer(srvcfg)
  264. if err != nil {
  265. return nil, err
  266. }
  267. s.Start()
  268. osutil.RegisterInterruptHandler(s.Stop)
  269. if cfg.corsInfo.String() != "" {
  270. plog.Infof("cors = %s", cfg.corsInfo)
  271. }
  272. ch := &cors.CORSHandler{
  273. Handler: etcdhttp.NewClientHandler(s, srvcfg.ReqTimeout()),
  274. Info: cfg.corsInfo,
  275. }
  276. ph := etcdhttp.NewPeerHandler(s.Cluster(), s.RaftHandler())
  277. // Start the peer server in a goroutine
  278. for _, l := range plns {
  279. go func(l net.Listener) {
  280. plog.Fatal(serveHTTP(l, ph, 5*time.Minute))
  281. }(l)
  282. }
  283. // Start a client server goroutine for each listen address
  284. for _, l := range clns {
  285. go func(l net.Listener) {
  286. // read timeout does not work with http close notify
  287. // TODO: https://github.com/golang/go/issues/9524
  288. plog.Fatal(serveHTTP(l, ch, 0))
  289. }(l)
  290. }
  291. if cfg.v3demo {
  292. // set up v3 demo rpc
  293. grpcServer := grpc.NewServer()
  294. etcdserverpb.RegisterEtcdServer(grpcServer, v3rpc.New(s))
  295. go plog.Fatal(grpcServer.Serve(v3l))
  296. }
  297. return s.StopNotify(), nil
  298. }
  299. // startProxy launches an HTTP proxy for client communication which proxies to other etcd nodes.
  300. func startProxy(cfg *config) error {
  301. urlsmap, _, err := getPeerURLsMapAndToken(cfg, "proxy")
  302. if err != nil {
  303. return fmt.Errorf("error setting up initial cluster: %v", err)
  304. }
  305. pt, err := transport.NewTimeoutTransport(cfg.peerTLSInfo, time.Duration(cfg.proxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyWriteTimeoutMs)*time.Millisecond)
  306. if err != nil {
  307. return err
  308. }
  309. pt.MaxIdleConnsPerHost = proxy.DefaultMaxIdleConnsPerHost
  310. tr, err := transport.NewTimeoutTransport(cfg.peerTLSInfo, time.Duration(cfg.proxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyWriteTimeoutMs)*time.Millisecond)
  311. if err != nil {
  312. return err
  313. }
  314. cfg.dir = path.Join(cfg.dir, "proxy")
  315. err = os.MkdirAll(cfg.dir, 0700)
  316. if err != nil {
  317. return err
  318. }
  319. var peerURLs []string
  320. clusterfile := path.Join(cfg.dir, "cluster")
  321. b, err := ioutil.ReadFile(clusterfile)
  322. switch {
  323. case err == nil:
  324. if cfg.durl != "" {
  325. plog.Warningf("discovery token ignored since the proxy has already been initialized. Valid cluster file found at %q", clusterfile)
  326. }
  327. urls := struct{ PeerURLs []string }{}
  328. err := json.Unmarshal(b, &urls)
  329. if err != nil {
  330. return err
  331. }
  332. peerURLs = urls.PeerURLs
  333. plog.Infof("proxy: using peer urls %v from cluster file %q", peerURLs, clusterfile)
  334. case os.IsNotExist(err):
  335. if cfg.durl != "" {
  336. s, err := discovery.GetCluster(cfg.durl, cfg.dproxy)
  337. if err != nil {
  338. return err
  339. }
  340. if urlsmap, err = types.NewURLsMap(s); err != nil {
  341. return err
  342. }
  343. }
  344. peerURLs = urlsmap.URLs()
  345. plog.Infof("proxy: using peer urls %v ", peerURLs)
  346. default:
  347. return err
  348. }
  349. clientURLs := []string{}
  350. uf := func() []string {
  351. gcls, err := etcdserver.GetClusterFromRemotePeers(peerURLs, tr)
  352. // TODO: remove the 2nd check when we fix GetClusterFromPeers
  353. // GetClusterFromPeers should not return nil error with an invalid empty cluster
  354. if err != nil {
  355. plog.Warningf("proxy: %v", err)
  356. return []string{}
  357. }
  358. if len(gcls.Members()) == 0 {
  359. return clientURLs
  360. }
  361. clientURLs = gcls.ClientURLs()
  362. urls := struct{ PeerURLs []string }{gcls.PeerURLs()}
  363. b, err := json.Marshal(urls)
  364. if err != nil {
  365. plog.Warningf("proxy: error on marshal peer urls %s", err)
  366. return clientURLs
  367. }
  368. err = ioutil.WriteFile(clusterfile+".bak", b, 0600)
  369. if err != nil {
  370. plog.Warningf("proxy: error on writing urls %s", err)
  371. return clientURLs
  372. }
  373. err = os.Rename(clusterfile+".bak", clusterfile)
  374. if err != nil {
  375. plog.Warningf("proxy: error on updating clusterfile %s", err)
  376. return clientURLs
  377. }
  378. if !reflect.DeepEqual(gcls.PeerURLs(), peerURLs) {
  379. plog.Noticef("proxy: updated peer urls in cluster file from %v to %v", peerURLs, gcls.PeerURLs())
  380. }
  381. peerURLs = gcls.PeerURLs()
  382. return clientURLs
  383. }
  384. ph := proxy.NewHandler(pt, uf, time.Duration(cfg.proxyFailureWaitMs)*time.Millisecond, time.Duration(cfg.proxyRefreshIntervalMs)*time.Millisecond)
  385. ph = &cors.CORSHandler{
  386. Handler: ph,
  387. Info: cfg.corsInfo,
  388. }
  389. if cfg.isReadonlyProxy() {
  390. ph = proxy.NewReadonlyHandler(ph)
  391. }
  392. // Start a proxy server goroutine for each listen address
  393. for _, u := range cfg.lcurls {
  394. l, err := transport.NewListener(u.Host, u.Scheme, cfg.clientTLSInfo)
  395. if err != nil {
  396. return err
  397. }
  398. host := u.String()
  399. go func() {
  400. plog.Info("proxy: listening for client requests on ", host)
  401. mux := http.NewServeMux()
  402. mux.Handle("/metrics", prometheus.Handler())
  403. mux.Handle("/", ph)
  404. plog.Fatal(http.Serve(l, mux))
  405. }()
  406. }
  407. return nil
  408. }
  409. // getPeerURLsMapAndToken sets up an initial peer URLsMap and cluster token for bootstrap or discovery.
  410. func getPeerURLsMapAndToken(cfg *config, which string) (urlsmap types.URLsMap, token string, err error) {
  411. switch {
  412. case cfg.durl != "":
  413. urlsmap = types.URLsMap{}
  414. // If using discovery, generate a temporary cluster based on
  415. // self's advertised peer URLs
  416. urlsmap[cfg.name] = cfg.apurls
  417. token = cfg.durl
  418. case cfg.dnsCluster != "":
  419. var clusterStr string
  420. clusterStr, token, err = discovery.SRVGetCluster(cfg.name, cfg.dnsCluster, cfg.initialClusterToken, cfg.apurls)
  421. if err != nil {
  422. return nil, "", err
  423. }
  424. urlsmap, err = types.NewURLsMap(clusterStr)
  425. // only etcd member must belong to the discovered cluster.
  426. // proxy does not need to belong to the discovered cluster.
  427. if which == "etcd" {
  428. if _, ok := urlsmap[cfg.name]; !ok {
  429. return nil, "", fmt.Errorf("cannot find local etcd member %q in SRV records", cfg.name)
  430. }
  431. }
  432. default:
  433. // We're statically configured, and cluster has appropriately been set.
  434. urlsmap, err = types.NewURLsMap(cfg.initialCluster)
  435. token = cfg.initialClusterToken
  436. }
  437. return urlsmap, token, err
  438. }
  439. // identifyDataDirOrDie returns the type of the data dir.
  440. // Dies if the datadir is invalid.
  441. func identifyDataDirOrDie(dir string) dirType {
  442. names, err := fileutil.ReadDir(dir)
  443. if err != nil {
  444. if os.IsNotExist(err) {
  445. return dirEmpty
  446. }
  447. plog.Fatalf("error listing data dir: %s", dir)
  448. }
  449. var m, p bool
  450. for _, name := range names {
  451. switch dirType(name) {
  452. case dirMember:
  453. m = true
  454. case dirProxy:
  455. p = true
  456. default:
  457. plog.Warningf("found invalid file/dir %s under data dir %s (Ignore this if you are upgrading etcd)", name, dir)
  458. }
  459. }
  460. if m && p {
  461. plog.Fatal("invalid datadir. Both member and proxy directories exist.")
  462. }
  463. if m {
  464. return dirMember
  465. }
  466. if p {
  467. return dirProxy
  468. }
  469. return dirEmpty
  470. }
  471. func setupLogging(cfg *config) {
  472. capnslog.SetGlobalLogLevel(capnslog.INFO)
  473. if cfg.debug {
  474. capnslog.SetGlobalLogLevel(capnslog.DEBUG)
  475. }
  476. if cfg.logPkgLevels != "" {
  477. repoLog := capnslog.MustRepoLogger("github.com/coreos/etcd")
  478. settings, err := repoLog.ParseLogLevelConfig(cfg.logPkgLevels)
  479. if err != nil {
  480. plog.Warningf("couldn't parse log level string: %s, continuing with default levels", err.Error())
  481. return
  482. }
  483. repoLog.SetLogLevel(settings)
  484. }
  485. }