etcd.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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 = 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 = netutil.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. StrictReconfigCheck: cfg.strictReconfigCheck,
  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.Cluster(), s.RaftHandler())
  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. grpcServer := grpc.NewServer()
  302. etcdserverpb.RegisterKVServer(grpcServer, v3rpc.NewKVServer(s))
  303. etcdserverpb.RegisterWatchServer(grpcServer, v3rpc.NewWatchServer(s))
  304. etcdserverpb.RegisterLeaseServer(grpcServer, v3rpc.NewLeaseServer(s))
  305. go func() { plog.Fatal(grpcServer.Serve(v3l)) }()
  306. }
  307. return s.StopNotify(), nil
  308. }
  309. // startProxy launches an HTTP proxy for client communication which proxies to other etcd nodes.
  310. func startProxy(cfg *config) error {
  311. urlsmap, _, err := getPeerURLsMapAndToken(cfg, "proxy")
  312. if err != nil {
  313. return fmt.Errorf("error setting up initial cluster: %v", err)
  314. }
  315. pt, err := transport.NewTimeoutTransport(cfg.peerTLSInfo, time.Duration(cfg.proxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyWriteTimeoutMs)*time.Millisecond)
  316. if err != nil {
  317. return err
  318. }
  319. pt.MaxIdleConnsPerHost = proxy.DefaultMaxIdleConnsPerHost
  320. tr, err := transport.NewTimeoutTransport(cfg.peerTLSInfo, time.Duration(cfg.proxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyWriteTimeoutMs)*time.Millisecond)
  321. if err != nil {
  322. return err
  323. }
  324. cfg.dir = path.Join(cfg.dir, "proxy")
  325. err = os.MkdirAll(cfg.dir, 0700)
  326. if err != nil {
  327. return err
  328. }
  329. var peerURLs []string
  330. clusterfile := path.Join(cfg.dir, "cluster")
  331. b, err := ioutil.ReadFile(clusterfile)
  332. switch {
  333. case err == nil:
  334. if cfg.durl != "" {
  335. plog.Warningf("discovery token ignored since the proxy has already been initialized. Valid cluster file found at %q", clusterfile)
  336. }
  337. urls := struct{ PeerURLs []string }{}
  338. err = json.Unmarshal(b, &urls)
  339. if err != nil {
  340. return err
  341. }
  342. peerURLs = urls.PeerURLs
  343. plog.Infof("proxy: using peer urls %v from cluster file %q", peerURLs, clusterfile)
  344. case os.IsNotExist(err):
  345. if cfg.durl != "" {
  346. s, err := discovery.GetCluster(cfg.durl, cfg.dproxy)
  347. if err != nil {
  348. return err
  349. }
  350. if urlsmap, err = types.NewURLsMap(s); err != nil {
  351. return err
  352. }
  353. }
  354. peerURLs = urlsmap.URLs()
  355. plog.Infof("proxy: using peer urls %v ", peerURLs)
  356. default:
  357. return err
  358. }
  359. clientURLs := []string{}
  360. uf := func() []string {
  361. gcls, err := etcdserver.GetClusterFromRemotePeers(peerURLs, tr)
  362. // TODO: remove the 2nd check when we fix GetClusterFromPeers
  363. // GetClusterFromPeers should not return nil error with an invalid empty cluster
  364. if err != nil {
  365. plog.Warningf("proxy: %v", err)
  366. return []string{}
  367. }
  368. if len(gcls.Members()) == 0 {
  369. return clientURLs
  370. }
  371. clientURLs = gcls.ClientURLs()
  372. urls := struct{ PeerURLs []string }{gcls.PeerURLs()}
  373. b, err := json.Marshal(urls)
  374. if err != nil {
  375. plog.Warningf("proxy: error on marshal peer urls %s", err)
  376. return clientURLs
  377. }
  378. err = pkgioutil.WriteAndSyncFile(clusterfile+".bak", b, 0600)
  379. if err != nil {
  380. plog.Warningf("proxy: error on writing urls %s", err)
  381. return clientURLs
  382. }
  383. err = os.Rename(clusterfile+".bak", clusterfile)
  384. if err != nil {
  385. plog.Warningf("proxy: error on updating clusterfile %s", err)
  386. return clientURLs
  387. }
  388. if !reflect.DeepEqual(gcls.PeerURLs(), peerURLs) {
  389. plog.Noticef("proxy: updated peer urls in cluster file from %v to %v", peerURLs, gcls.PeerURLs())
  390. }
  391. peerURLs = gcls.PeerURLs()
  392. return clientURLs
  393. }
  394. ph := proxy.NewHandler(pt, uf, time.Duration(cfg.proxyFailureWaitMs)*time.Millisecond, time.Duration(cfg.proxyRefreshIntervalMs)*time.Millisecond)
  395. ph = &cors.CORSHandler{
  396. Handler: ph,
  397. Info: cfg.corsInfo,
  398. }
  399. if cfg.isReadonlyProxy() {
  400. ph = proxy.NewReadonlyHandler(ph)
  401. }
  402. // Start a proxy server goroutine for each listen address
  403. for _, u := range cfg.lcurls {
  404. l, err := transport.NewListener(u.Host, u.Scheme, cfg.clientTLSInfo)
  405. if err != nil {
  406. return err
  407. }
  408. host := u.String()
  409. go func() {
  410. plog.Info("proxy: listening for client requests on ", host)
  411. mux := http.NewServeMux()
  412. mux.Handle("/metrics", prometheus.Handler())
  413. mux.Handle("/", ph)
  414. plog.Fatal(http.Serve(l, mux))
  415. }()
  416. }
  417. return nil
  418. }
  419. // getPeerURLsMapAndToken sets up an initial peer URLsMap and cluster token for bootstrap or discovery.
  420. func getPeerURLsMapAndToken(cfg *config, which string) (urlsmap types.URLsMap, token string, err error) {
  421. switch {
  422. case cfg.durl != "":
  423. urlsmap = types.URLsMap{}
  424. // If using discovery, generate a temporary cluster based on
  425. // self's advertised peer URLs
  426. urlsmap[cfg.name] = cfg.apurls
  427. token = cfg.durl
  428. case cfg.dnsCluster != "":
  429. var clusterStr string
  430. clusterStr, token, err = discovery.SRVGetCluster(cfg.name, cfg.dnsCluster, cfg.initialClusterToken, cfg.apurls)
  431. if err != nil {
  432. return nil, "", err
  433. }
  434. urlsmap, err = types.NewURLsMap(clusterStr)
  435. // only etcd member must belong to the discovered cluster.
  436. // proxy does not need to belong to the discovered cluster.
  437. if which == "etcd" {
  438. if _, ok := urlsmap[cfg.name]; !ok {
  439. return nil, "", fmt.Errorf("cannot find local etcd member %q in SRV records", cfg.name)
  440. }
  441. }
  442. default:
  443. // We're statically configured, and cluster has appropriately been set.
  444. urlsmap, err = types.NewURLsMap(cfg.initialCluster)
  445. token = cfg.initialClusterToken
  446. }
  447. return urlsmap, token, err
  448. }
  449. // identifyDataDirOrDie returns the type of the data dir.
  450. // Dies if the datadir is invalid.
  451. func identifyDataDirOrDie(dir string) dirType {
  452. names, err := fileutil.ReadDir(dir)
  453. if err != nil {
  454. if os.IsNotExist(err) {
  455. return dirEmpty
  456. }
  457. plog.Fatalf("error listing data dir: %s", dir)
  458. }
  459. var m, p bool
  460. for _, name := range names {
  461. switch dirType(name) {
  462. case dirMember:
  463. m = true
  464. case dirProxy:
  465. p = true
  466. default:
  467. plog.Warningf("found invalid file/dir %s under data dir %s (Ignore this if you are upgrading etcd)", name, dir)
  468. }
  469. }
  470. if m && p {
  471. plog.Fatal("invalid datadir. Both member and proxy directories exist.")
  472. }
  473. if m {
  474. return dirMember
  475. }
  476. if p {
  477. return dirProxy
  478. }
  479. return dirEmpty
  480. }
  481. func setupLogging(cfg *config) {
  482. capnslog.SetGlobalLogLevel(capnslog.INFO)
  483. if cfg.debug {
  484. capnslog.SetGlobalLogLevel(capnslog.DEBUG)
  485. }
  486. if cfg.logPkgLevels != "" {
  487. repoLog := capnslog.MustRepoLogger("github.com/coreos/etcd")
  488. settings, err := repoLog.ParseLogLevelConfig(cfg.logPkgLevels)
  489. if err != nil {
  490. plog.Warningf("couldn't parse log level string: %s, continuing with default levels", err.Error())
  491. return
  492. }
  493. repoLog.SetLogLevel(settings)
  494. }
  495. }