etcd.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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 derr, ok := err.(*etcdserver.DiscoveryError); ok && derr.Err == discovery.ErrFullCluster {
  113. if cfg.shouldFallbackToProxy() {
  114. plog.Noticef("discovery cluster full, falling back to %s", fallbackFlagProxy)
  115. shouldProxy = true
  116. }
  117. }
  118. }
  119. if shouldProxy {
  120. err = startProxy(cfg)
  121. }
  122. }
  123. if err != nil {
  124. if derr, ok := err.(*etcdserver.DiscoveryError); ok {
  125. switch derr.Err {
  126. case discovery.ErrDuplicateID:
  127. plog.Errorf("member %q has previously registered with discovery service token (%s).", cfg.name, cfg.durl)
  128. plog.Errorf("But etcd could not find valid cluster configuration in the given data dir (%s).", cfg.dir)
  129. plog.Infof("Please check the given data dir path if the previous bootstrap succeeded")
  130. plog.Infof("or use a new discovery token if the previous bootstrap failed.")
  131. case discovery.ErrDuplicateName:
  132. plog.Errorf("member with duplicated name has registered with discovery service token(%s).", cfg.durl)
  133. plog.Errorf("please check (cURL) the discovery token for more information.")
  134. plog.Errorf("please do not reuse the discovery token and generate a new one to bootstrap the cluster.")
  135. default:
  136. plog.Errorf("%v", err)
  137. plog.Infof("discovery token %s was used, but failed to bootstrap the cluster.", cfg.durl)
  138. plog.Infof("please generate a new discovery token and try to bootstrap again.")
  139. }
  140. os.Exit(1)
  141. }
  142. if strings.Contains(err.Error(), "include") && strings.Contains(err.Error(), "--initial-cluster") {
  143. plog.Infof("%v", err)
  144. if cfg.initialCluster == initialClusterFromName(cfg.name) {
  145. plog.Infof("forgot to set --initial-cluster flag?")
  146. }
  147. if types.URLs(cfg.apurls).String() == defaultInitialAdvertisePeerURLs {
  148. plog.Infof("forgot to set --initial-advertise-peer-urls flag?")
  149. }
  150. if cfg.initialCluster == initialClusterFromName(cfg.name) && len(cfg.durl) == 0 {
  151. plog.Infof("if you want to use discovery service, please set --discovery flag.")
  152. }
  153. os.Exit(1)
  154. }
  155. plog.Fatalf("%v", err)
  156. }
  157. osutil.HandleInterrupts()
  158. if systemdutil.IsRunningSystemd() {
  159. // At this point, the initialization of etcd is done.
  160. // The listeners are listening on the TCP ports and ready
  161. // for accepting connections.
  162. // The http server is probably ready for serving incoming
  163. // connections. If it is not, the connection might be pending
  164. // for less than one second.
  165. err := daemon.SdNotify("READY=1")
  166. if err != nil {
  167. plog.Errorf("failed to notify systemd for readiness: %v", err)
  168. if err == daemon.SdNotifyNoSocket {
  169. plog.Errorf("forgot to set Type=notify in systemd service file?")
  170. }
  171. }
  172. }
  173. <-stopped
  174. osutil.Exit(0)
  175. }
  176. // startEtcd launches the etcd server and HTTP handlers for client/server communication.
  177. func startEtcd(cfg *config) (<-chan struct{}, error) {
  178. urlsmap, token, err := getPeerURLsMapAndToken(cfg, "etcd")
  179. if err != nil {
  180. return nil, fmt.Errorf("error setting up initial cluster: %v", err)
  181. }
  182. if !cfg.peerTLSInfo.Empty() {
  183. plog.Infof("peerTLS: %s", cfg.peerTLSInfo)
  184. }
  185. plns := make([]net.Listener, 0)
  186. for _, u := range cfg.lpurls {
  187. if u.Scheme == "http" && !cfg.peerTLSInfo.Empty() {
  188. plog.Warningf("The scheme of peer url %s is http while peer key/cert files are presented. Ignored peer key/cert files.", u.String())
  189. }
  190. var l net.Listener
  191. l, err = rafthttp.NewListener(u, cfg.peerTLSInfo)
  192. if err != nil {
  193. return nil, err
  194. }
  195. urlStr := u.String()
  196. plog.Info("listening for peers on ", urlStr)
  197. defer func() {
  198. if err != nil {
  199. l.Close()
  200. plog.Info("stopping listening for peers on ", urlStr)
  201. }
  202. }()
  203. plns = append(plns, l)
  204. }
  205. if !cfg.clientTLSInfo.Empty() {
  206. plog.Infof("clientTLS: %s", cfg.clientTLSInfo)
  207. }
  208. clns := make([]net.Listener, 0)
  209. for _, u := range cfg.lcurls {
  210. if u.Scheme == "http" && !cfg.clientTLSInfo.Empty() {
  211. plog.Warningf("The scheme of client url %s is http while client key/cert files are presented. Ignored client key/cert files.", u.String())
  212. }
  213. var l net.Listener
  214. l, err = transport.NewKeepAliveListener(u.Host, u.Scheme, cfg.clientTLSInfo)
  215. if err != nil {
  216. return nil, err
  217. }
  218. if fdLimit, err := runtimeutil.FDLimit(); err == nil {
  219. if fdLimit <= reservedInternalFDNum {
  220. 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)
  221. }
  222. l = netutil.LimitListener(l, int(fdLimit-reservedInternalFDNum))
  223. }
  224. urlStr := u.String()
  225. plog.Info("listening for client requests on ", urlStr)
  226. defer func() {
  227. if err != nil {
  228. l.Close()
  229. plog.Info("stopping listening for client requests on ", urlStr)
  230. }
  231. }()
  232. clns = append(clns, l)
  233. }
  234. var v3l net.Listener
  235. if cfg.v3demo {
  236. v3l, err = net.Listen("tcp", cfg.gRPCAddr)
  237. if err != nil {
  238. plog.Fatal(err)
  239. }
  240. plog.Infof("listening for client rpc on %s", cfg.gRPCAddr)
  241. }
  242. srvcfg := &etcdserver.ServerConfig{
  243. Name: cfg.name,
  244. ClientURLs: cfg.acurls,
  245. PeerURLs: cfg.apurls,
  246. DataDir: cfg.dir,
  247. DedicatedWALDir: cfg.walDir,
  248. SnapCount: cfg.snapCount,
  249. MaxSnapFiles: cfg.maxSnapFiles,
  250. MaxWALFiles: cfg.maxWalFiles,
  251. InitialPeerURLsMap: urlsmap,
  252. InitialClusterToken: token,
  253. DiscoveryURL: cfg.durl,
  254. DiscoveryProxy: cfg.dproxy,
  255. NewCluster: cfg.isNewCluster(),
  256. ForceNewCluster: cfg.forceNewCluster,
  257. PeerTLSInfo: cfg.peerTLSInfo,
  258. TickMs: cfg.TickMs,
  259. ElectionTicks: cfg.electionTicks(),
  260. V3demo: cfg.v3demo,
  261. StrictReconfigCheck: cfg.strictReconfigCheck,
  262. }
  263. var s *etcdserver.EtcdServer
  264. s, err = etcdserver.NewServer(srvcfg)
  265. if err != nil {
  266. return nil, err
  267. }
  268. s.Start()
  269. osutil.RegisterInterruptHandler(s.Stop)
  270. if cfg.corsInfo.String() != "" {
  271. plog.Infof("cors = %s", cfg.corsInfo)
  272. }
  273. ch := &cors.CORSHandler{
  274. Handler: etcdhttp.NewClientHandler(s, srvcfg.ReqTimeout()),
  275. Info: cfg.corsInfo,
  276. }
  277. ph := etcdhttp.NewPeerHandler(s.Cluster(), s.RaftHandler())
  278. // Start the peer server in a goroutine
  279. for _, l := range plns {
  280. go func(l net.Listener) {
  281. plog.Fatal(serveHTTP(l, ph, 5*time.Minute))
  282. }(l)
  283. }
  284. // Start a client server goroutine for each listen address
  285. for _, l := range clns {
  286. go func(l net.Listener) {
  287. // read timeout does not work with http close notify
  288. // TODO: https://github.com/golang/go/issues/9524
  289. plog.Fatal(serveHTTP(l, ch, 0))
  290. }(l)
  291. }
  292. if cfg.v3demo {
  293. // set up v3 demo rpc
  294. grpcServer := grpc.NewServer()
  295. etcdserverpb.RegisterKVServer(grpcServer, v3rpc.NewKVServer(s))
  296. etcdserverpb.RegisterWatchServer(grpcServer, v3rpc.NewWatchServer(s.Watchable()))
  297. go func() { plog.Fatal(grpcServer.Serve(v3l)) }()
  298. }
  299. return s.StopNotify(), nil
  300. }
  301. // startProxy launches an HTTP proxy for client communication which proxies to other etcd nodes.
  302. func startProxy(cfg *config) error {
  303. urlsmap, _, err := getPeerURLsMapAndToken(cfg, "proxy")
  304. if err != nil {
  305. return fmt.Errorf("error setting up initial cluster: %v", err)
  306. }
  307. pt, err := transport.NewTimeoutTransport(cfg.peerTLSInfo, time.Duration(cfg.proxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyWriteTimeoutMs)*time.Millisecond)
  308. if err != nil {
  309. return err
  310. }
  311. pt.MaxIdleConnsPerHost = proxy.DefaultMaxIdleConnsPerHost
  312. tr, err := transport.NewTimeoutTransport(cfg.peerTLSInfo, time.Duration(cfg.proxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyWriteTimeoutMs)*time.Millisecond)
  313. if err != nil {
  314. return err
  315. }
  316. cfg.dir = path.Join(cfg.dir, "proxy")
  317. err = os.MkdirAll(cfg.dir, 0700)
  318. if err != nil {
  319. return err
  320. }
  321. var peerURLs []string
  322. clusterfile := path.Join(cfg.dir, "cluster")
  323. b, err := ioutil.ReadFile(clusterfile)
  324. switch {
  325. case err == nil:
  326. if cfg.durl != "" {
  327. plog.Warningf("discovery token ignored since the proxy has already been initialized. Valid cluster file found at %q", clusterfile)
  328. }
  329. urls := struct{ PeerURLs []string }{}
  330. err := json.Unmarshal(b, &urls)
  331. if err != nil {
  332. return err
  333. }
  334. peerURLs = urls.PeerURLs
  335. plog.Infof("proxy: using peer urls %v from cluster file %q", peerURLs, clusterfile)
  336. case os.IsNotExist(err):
  337. if cfg.durl != "" {
  338. s, err := discovery.GetCluster(cfg.durl, cfg.dproxy)
  339. if err != nil {
  340. return err
  341. }
  342. if urlsmap, err = types.NewURLsMap(s); err != nil {
  343. return err
  344. }
  345. }
  346. peerURLs = urlsmap.URLs()
  347. plog.Infof("proxy: using peer urls %v ", peerURLs)
  348. default:
  349. return err
  350. }
  351. clientURLs := []string{}
  352. uf := func() []string {
  353. gcls, err := etcdserver.GetClusterFromRemotePeers(peerURLs, tr)
  354. // TODO: remove the 2nd check when we fix GetClusterFromPeers
  355. // GetClusterFromPeers should not return nil error with an invalid empty cluster
  356. if err != nil {
  357. plog.Warningf("proxy: %v", err)
  358. return []string{}
  359. }
  360. if len(gcls.Members()) == 0 {
  361. return clientURLs
  362. }
  363. clientURLs = gcls.ClientURLs()
  364. urls := struct{ PeerURLs []string }{gcls.PeerURLs()}
  365. b, err := json.Marshal(urls)
  366. if err != nil {
  367. plog.Warningf("proxy: error on marshal peer urls %s", err)
  368. return clientURLs
  369. }
  370. err = ioutil.WriteFile(clusterfile+".bak", b, 0600)
  371. if err != nil {
  372. plog.Warningf("proxy: error on writing urls %s", err)
  373. return clientURLs
  374. }
  375. err = os.Rename(clusterfile+".bak", clusterfile)
  376. if err != nil {
  377. plog.Warningf("proxy: error on updating clusterfile %s", err)
  378. return clientURLs
  379. }
  380. if !reflect.DeepEqual(gcls.PeerURLs(), peerURLs) {
  381. plog.Noticef("proxy: updated peer urls in cluster file from %v to %v", peerURLs, gcls.PeerURLs())
  382. }
  383. peerURLs = gcls.PeerURLs()
  384. return clientURLs
  385. }
  386. ph := proxy.NewHandler(pt, uf, time.Duration(cfg.proxyFailureWaitMs)*time.Millisecond, time.Duration(cfg.proxyRefreshIntervalMs)*time.Millisecond)
  387. ph = &cors.CORSHandler{
  388. Handler: ph,
  389. Info: cfg.corsInfo,
  390. }
  391. if cfg.isReadonlyProxy() {
  392. ph = proxy.NewReadonlyHandler(ph)
  393. }
  394. // Start a proxy server goroutine for each listen address
  395. for _, u := range cfg.lcurls {
  396. l, err := transport.NewListener(u.Host, u.Scheme, cfg.clientTLSInfo)
  397. if err != nil {
  398. return err
  399. }
  400. host := u.String()
  401. go func() {
  402. plog.Info("proxy: listening for client requests on ", host)
  403. mux := http.NewServeMux()
  404. mux.Handle("/metrics", prometheus.Handler())
  405. mux.Handle("/", ph)
  406. plog.Fatal(http.Serve(l, mux))
  407. }()
  408. }
  409. return nil
  410. }
  411. // getPeerURLsMapAndToken sets up an initial peer URLsMap and cluster token for bootstrap or discovery.
  412. func getPeerURLsMapAndToken(cfg *config, which string) (urlsmap types.URLsMap, token string, err error) {
  413. switch {
  414. case cfg.durl != "":
  415. urlsmap = types.URLsMap{}
  416. // If using discovery, generate a temporary cluster based on
  417. // self's advertised peer URLs
  418. urlsmap[cfg.name] = cfg.apurls
  419. token = cfg.durl
  420. case cfg.dnsCluster != "":
  421. var clusterStr string
  422. clusterStr, token, err = discovery.SRVGetCluster(cfg.name, cfg.dnsCluster, cfg.initialClusterToken, cfg.apurls)
  423. if err != nil {
  424. return nil, "", err
  425. }
  426. urlsmap, err = types.NewURLsMap(clusterStr)
  427. // only etcd member must belong to the discovered cluster.
  428. // proxy does not need to belong to the discovered cluster.
  429. if which == "etcd" {
  430. if _, ok := urlsmap[cfg.name]; !ok {
  431. return nil, "", fmt.Errorf("cannot find local etcd member %q in SRV records", cfg.name)
  432. }
  433. }
  434. default:
  435. // We're statically configured, and cluster has appropriately been set.
  436. urlsmap, err = types.NewURLsMap(cfg.initialCluster)
  437. token = cfg.initialClusterToken
  438. }
  439. return urlsmap, token, err
  440. }
  441. // identifyDataDirOrDie returns the type of the data dir.
  442. // Dies if the datadir is invalid.
  443. func identifyDataDirOrDie(dir string) dirType {
  444. names, err := fileutil.ReadDir(dir)
  445. if err != nil {
  446. if os.IsNotExist(err) {
  447. return dirEmpty
  448. }
  449. plog.Fatalf("error listing data dir: %s", dir)
  450. }
  451. var m, p bool
  452. for _, name := range names {
  453. switch dirType(name) {
  454. case dirMember:
  455. m = true
  456. case dirProxy:
  457. p = true
  458. default:
  459. plog.Warningf("found invalid file/dir %s under data dir %s (Ignore this if you are upgrading etcd)", name, dir)
  460. }
  461. }
  462. if m && p {
  463. plog.Fatal("invalid datadir. Both member and proxy directories exist.")
  464. }
  465. if m {
  466. return dirMember
  467. }
  468. if p {
  469. return dirProxy
  470. }
  471. return dirEmpty
  472. }
  473. func setupLogging(cfg *config) {
  474. capnslog.SetGlobalLogLevel(capnslog.INFO)
  475. if cfg.debug {
  476. capnslog.SetGlobalLogLevel(capnslog.DEBUG)
  477. }
  478. if cfg.logPkgLevels != "" {
  479. repoLog := capnslog.MustRepoLogger("github.com/coreos/etcd")
  480. settings, err := repoLog.ParseLogLevelConfig(cfg.logPkgLevels)
  481. if err != nil {
  482. plog.Warningf("couldn't parse log level string: %s, continuing with default levels", err.Error())
  483. return
  484. }
  485. repoLog.SetLogLevel(settings)
  486. }
  487. }