etcd.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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. 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 = transport.NewKeepAliveListener(u.Host, u.Scheme, cfg.clientTLSInfo)
  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 = netutil.LimitListener(l, int(fdLimit-reservedInternalFDNum))
  224. }
  225. urlStr := u.String()
  226. plog.Info("listening for client requests on ", urlStr)
  227. defer func() {
  228. if err != nil {
  229. l.Close()
  230. plog.Info("stopping listening for client requests on ", urlStr)
  231. }
  232. }()
  233. clns = append(clns, l)
  234. }
  235. var v3l net.Listener
  236. if cfg.v3demo {
  237. v3l, err = net.Listen("tcp", cfg.gRPCAddr)
  238. if err != nil {
  239. plog.Fatal(err)
  240. }
  241. plog.Infof("listening for client rpc on %s", cfg.gRPCAddr)
  242. }
  243. srvcfg := &etcdserver.ServerConfig{
  244. Name: cfg.name,
  245. ClientURLs: cfg.acurls,
  246. PeerURLs: cfg.apurls,
  247. DataDir: cfg.dir,
  248. DedicatedWALDir: cfg.walDir,
  249. SnapCount: cfg.snapCount,
  250. MaxSnapFiles: cfg.maxSnapFiles,
  251. MaxWALFiles: cfg.maxWalFiles,
  252. InitialPeerURLsMap: urlsmap,
  253. InitialClusterToken: token,
  254. DiscoveryURL: cfg.durl,
  255. DiscoveryProxy: cfg.dproxy,
  256. NewCluster: cfg.isNewCluster(),
  257. ForceNewCluster: cfg.forceNewCluster,
  258. PeerTLSInfo: cfg.peerTLSInfo,
  259. TickMs: cfg.TickMs,
  260. ElectionTicks: cfg.electionTicks(),
  261. V3demo: cfg.v3demo,
  262. StrictReconfigCheck: cfg.strictReconfigCheck,
  263. }
  264. var s *etcdserver.EtcdServer
  265. s, err = etcdserver.NewServer(srvcfg)
  266. if err != nil {
  267. return nil, err
  268. }
  269. s.Start()
  270. osutil.RegisterInterruptHandler(s.Stop)
  271. if cfg.corsInfo.String() != "" {
  272. plog.Infof("cors = %s", cfg.corsInfo)
  273. }
  274. ch := &cors.CORSHandler{
  275. Handler: etcdhttp.NewClientHandler(s, srvcfg.ReqTimeout()),
  276. Info: cfg.corsInfo,
  277. }
  278. ph := etcdhttp.NewPeerHandler(s.Cluster(), s.RaftHandler())
  279. // Start the peer server in a goroutine
  280. for _, l := range plns {
  281. go func(l net.Listener) {
  282. plog.Fatal(serveHTTP(l, ph, 5*time.Minute))
  283. }(l)
  284. }
  285. // Start a client server goroutine for each listen address
  286. for _, l := range clns {
  287. go func(l net.Listener) {
  288. // read timeout does not work with http close notify
  289. // TODO: https://github.com/golang/go/issues/9524
  290. plog.Fatal(serveHTTP(l, ch, 0))
  291. }(l)
  292. }
  293. if cfg.v3demo {
  294. // set up v3 demo rpc
  295. grpcServer := grpc.NewServer()
  296. etcdserverpb.RegisterKVServer(grpcServer, v3rpc.NewKVServer(s))
  297. etcdserverpb.RegisterWatchServer(grpcServer, v3rpc.NewWatchServer(s.Watchable()))
  298. go func() { plog.Fatal(grpcServer.Serve(v3l)) }()
  299. }
  300. return s.StopNotify(), nil
  301. }
  302. // startProxy launches an HTTP proxy for client communication which proxies to other etcd nodes.
  303. func startProxy(cfg *config) error {
  304. urlsmap, _, err := getPeerURLsMapAndToken(cfg, "proxy")
  305. if err != nil {
  306. return fmt.Errorf("error setting up initial cluster: %v", err)
  307. }
  308. pt, err := transport.NewTimeoutTransport(cfg.peerTLSInfo, time.Duration(cfg.proxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyWriteTimeoutMs)*time.Millisecond)
  309. if err != nil {
  310. return err
  311. }
  312. pt.MaxIdleConnsPerHost = proxy.DefaultMaxIdleConnsPerHost
  313. tr, err := transport.NewTimeoutTransport(cfg.peerTLSInfo, time.Duration(cfg.proxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyWriteTimeoutMs)*time.Millisecond)
  314. if err != nil {
  315. return err
  316. }
  317. cfg.dir = path.Join(cfg.dir, "proxy")
  318. err = os.MkdirAll(cfg.dir, 0700)
  319. if err != nil {
  320. return err
  321. }
  322. var peerURLs []string
  323. clusterfile := path.Join(cfg.dir, "cluster")
  324. b, err := ioutil.ReadFile(clusterfile)
  325. switch {
  326. case err == nil:
  327. if cfg.durl != "" {
  328. plog.Warningf("discovery token ignored since the proxy has already been initialized. Valid cluster file found at %q", clusterfile)
  329. }
  330. urls := struct{ PeerURLs []string }{}
  331. err = json.Unmarshal(b, &urls)
  332. if err != nil {
  333. return err
  334. }
  335. peerURLs = urls.PeerURLs
  336. plog.Infof("proxy: using peer urls %v from cluster file %q", peerURLs, clusterfile)
  337. case os.IsNotExist(err):
  338. if cfg.durl != "" {
  339. s, err := discovery.GetCluster(cfg.durl, cfg.dproxy)
  340. if err != nil {
  341. return err
  342. }
  343. if urlsmap, err = types.NewURLsMap(s); err != nil {
  344. return err
  345. }
  346. }
  347. peerURLs = urlsmap.URLs()
  348. plog.Infof("proxy: using peer urls %v ", peerURLs)
  349. default:
  350. return err
  351. }
  352. clientURLs := []string{}
  353. uf := func() []string {
  354. gcls, err := etcdserver.GetClusterFromRemotePeers(peerURLs, tr)
  355. // TODO: remove the 2nd check when we fix GetClusterFromPeers
  356. // GetClusterFromPeers should not return nil error with an invalid empty cluster
  357. if err != nil {
  358. plog.Warningf("proxy: %v", err)
  359. return []string{}
  360. }
  361. if len(gcls.Members()) == 0 {
  362. return clientURLs
  363. }
  364. clientURLs = gcls.ClientURLs()
  365. urls := struct{ PeerURLs []string }{gcls.PeerURLs()}
  366. b, err := json.Marshal(urls)
  367. if err != nil {
  368. plog.Warningf("proxy: error on marshal peer urls %s", err)
  369. return clientURLs
  370. }
  371. err = pkgioutil.WriteAndSyncFile(clusterfile+".bak", b, 0600)
  372. if err != nil {
  373. plog.Warningf("proxy: error on writing urls %s", err)
  374. return clientURLs
  375. }
  376. err = os.Rename(clusterfile+".bak", clusterfile)
  377. if err != nil {
  378. plog.Warningf("proxy: error on updating clusterfile %s", err)
  379. return clientURLs
  380. }
  381. if !reflect.DeepEqual(gcls.PeerURLs(), peerURLs) {
  382. plog.Noticef("proxy: updated peer urls in cluster file from %v to %v", peerURLs, gcls.PeerURLs())
  383. }
  384. peerURLs = gcls.PeerURLs()
  385. return clientURLs
  386. }
  387. ph := proxy.NewHandler(pt, uf, time.Duration(cfg.proxyFailureWaitMs)*time.Millisecond, time.Duration(cfg.proxyRefreshIntervalMs)*time.Millisecond)
  388. ph = &cors.CORSHandler{
  389. Handler: ph,
  390. Info: cfg.corsInfo,
  391. }
  392. if cfg.isReadonlyProxy() {
  393. ph = proxy.NewReadonlyHandler(ph)
  394. }
  395. // Start a proxy server goroutine for each listen address
  396. for _, u := range cfg.lcurls {
  397. l, err := transport.NewListener(u.Host, u.Scheme, cfg.clientTLSInfo)
  398. if err != nil {
  399. return err
  400. }
  401. host := u.String()
  402. go func() {
  403. plog.Info("proxy: listening for client requests on ", host)
  404. mux := http.NewServeMux()
  405. mux.Handle("/metrics", prometheus.Handler())
  406. mux.Handle("/", ph)
  407. plog.Fatal(http.Serve(l, mux))
  408. }()
  409. }
  410. return nil
  411. }
  412. // getPeerURLsMapAndToken sets up an initial peer URLsMap and cluster token for bootstrap or discovery.
  413. func getPeerURLsMapAndToken(cfg *config, which string) (urlsmap types.URLsMap, token string, err error) {
  414. switch {
  415. case cfg.durl != "":
  416. urlsmap = types.URLsMap{}
  417. // If using discovery, generate a temporary cluster based on
  418. // self's advertised peer URLs
  419. urlsmap[cfg.name] = cfg.apurls
  420. token = cfg.durl
  421. case cfg.dnsCluster != "":
  422. var clusterStr string
  423. clusterStr, token, err = discovery.SRVGetCluster(cfg.name, cfg.dnsCluster, cfg.initialClusterToken, cfg.apurls)
  424. if err != nil {
  425. return nil, "", err
  426. }
  427. urlsmap, err = types.NewURLsMap(clusterStr)
  428. // only etcd member must belong to the discovered cluster.
  429. // proxy does not need to belong to the discovered cluster.
  430. if which == "etcd" {
  431. if _, ok := urlsmap[cfg.name]; !ok {
  432. return nil, "", fmt.Errorf("cannot find local etcd member %q in SRV records", cfg.name)
  433. }
  434. }
  435. default:
  436. // We're statically configured, and cluster has appropriately been set.
  437. urlsmap, err = types.NewURLsMap(cfg.initialCluster)
  438. token = cfg.initialClusterToken
  439. }
  440. return urlsmap, token, err
  441. }
  442. // identifyDataDirOrDie returns the type of the data dir.
  443. // Dies if the datadir is invalid.
  444. func identifyDataDirOrDie(dir string) dirType {
  445. names, err := fileutil.ReadDir(dir)
  446. if err != nil {
  447. if os.IsNotExist(err) {
  448. return dirEmpty
  449. }
  450. plog.Fatalf("error listing data dir: %s", dir)
  451. }
  452. var m, p bool
  453. for _, name := range names {
  454. switch dirType(name) {
  455. case dirMember:
  456. m = true
  457. case dirProxy:
  458. p = true
  459. default:
  460. plog.Warningf("found invalid file/dir %s under data dir %s (Ignore this if you are upgrading etcd)", name, dir)
  461. }
  462. }
  463. if m && p {
  464. plog.Fatal("invalid datadir. Both member and proxy directories exist.")
  465. }
  466. if m {
  467. return dirMember
  468. }
  469. if p {
  470. return dirProxy
  471. }
  472. return dirEmpty
  473. }
  474. func setupLogging(cfg *config) {
  475. capnslog.SetGlobalLogLevel(capnslog.INFO)
  476. if cfg.debug {
  477. capnslog.SetGlobalLogLevel(capnslog.DEBUG)
  478. }
  479. if cfg.logPkgLevels != "" {
  480. repoLog := capnslog.MustRepoLogger("github.com/coreos/etcd")
  481. settings, err := repoLog.ParseLogLevelConfig(cfg.logPkgLevels)
  482. if err != nil {
  483. plog.Warningf("couldn't parse log level string: %s, continuing with default levels", err.Error())
  484. return
  485. }
  486. repoLog.SetLogLevel(settings)
  487. }
  488. }