etcd.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. // Copyright 2015 The etcd Authors
  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. "crypto/tls"
  17. "encoding/json"
  18. "fmt"
  19. "io/ioutil"
  20. "net"
  21. "net/http"
  22. "os"
  23. "path"
  24. "reflect"
  25. "runtime"
  26. "strings"
  27. "time"
  28. "github.com/coreos/etcd/discovery"
  29. "github.com/coreos/etcd/embed"
  30. "github.com/coreos/etcd/etcdserver"
  31. "github.com/coreos/etcd/pkg/cors"
  32. "github.com/coreos/etcd/pkg/fileutil"
  33. pkgioutil "github.com/coreos/etcd/pkg/ioutil"
  34. "github.com/coreos/etcd/pkg/osutil"
  35. "github.com/coreos/etcd/pkg/transport"
  36. "github.com/coreos/etcd/pkg/types"
  37. "github.com/coreos/etcd/proxy/httpproxy"
  38. "github.com/coreos/etcd/version"
  39. "github.com/coreos/go-systemd/daemon"
  40. systemdutil "github.com/coreos/go-systemd/util"
  41. "github.com/coreos/pkg/capnslog"
  42. "github.com/grpc-ecosystem/go-grpc-prometheus"
  43. "github.com/prometheus/client_golang/prometheus"
  44. "google.golang.org/grpc"
  45. )
  46. type dirType string
  47. var plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "etcdmain")
  48. var (
  49. dirMember = dirType("member")
  50. dirProxy = dirType("proxy")
  51. dirEmpty = dirType("empty")
  52. )
  53. func startEtcdOrProxyV2() {
  54. grpc.EnableTracing = false
  55. cfg := newConfig()
  56. defaultInitialCluster := cfg.InitialCluster
  57. err := cfg.parse(os.Args[1:])
  58. if err != nil {
  59. plog.Errorf("error verifying flags, %v. See 'etcd --help'.", err)
  60. switch err {
  61. case embed.ErrUnsetAdvertiseClientURLsFlag:
  62. plog.Errorf("When listening on specific address(es), this etcd process must advertise accessible url(s) to each connected client.")
  63. }
  64. os.Exit(1)
  65. }
  66. setupLogging(cfg)
  67. var stopped <-chan struct{}
  68. var errc <-chan error
  69. plog.Infof("etcd Version: %s\n", version.Version)
  70. plog.Infof("Git SHA: %s\n", version.GitSHA)
  71. plog.Infof("Go Version: %s\n", runtime.Version())
  72. plog.Infof("Go OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
  73. GoMaxProcs := runtime.GOMAXPROCS(0)
  74. plog.Infof("setting maximum number of CPUs to %d, total number of available CPUs is %d", GoMaxProcs, runtime.NumCPU())
  75. // TODO: check whether fields are set instead of whether fields have default value
  76. defaultHost, defaultHostErr := cfg.IsDefaultHost()
  77. defaultHostOverride := defaultHost == "" || defaultHostErr == nil
  78. if (defaultHostOverride || cfg.Name != embed.DefaultName) && cfg.InitialCluster == defaultInitialCluster {
  79. cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
  80. }
  81. if cfg.Dir == "" {
  82. cfg.Dir = fmt.Sprintf("%v.etcd", cfg.Name)
  83. plog.Warningf("no data-dir provided, using default data-dir ./%s", cfg.Dir)
  84. }
  85. which := identifyDataDirOrDie(cfg.Dir)
  86. if which != dirEmpty {
  87. plog.Noticef("the server is already initialized as %v before, starting as etcd %v...", which, which)
  88. switch which {
  89. case dirMember:
  90. stopped, errc, err = startEtcd(&cfg.Config)
  91. case dirProxy:
  92. err = startProxy(cfg)
  93. default:
  94. plog.Panicf("unhandled dir type %v", which)
  95. }
  96. } else {
  97. shouldProxy := cfg.isProxy()
  98. if !shouldProxy {
  99. stopped, errc, err = startEtcd(&cfg.Config)
  100. if derr, ok := err.(*etcdserver.DiscoveryError); ok && derr.Err == discovery.ErrFullCluster {
  101. if cfg.shouldFallbackToProxy() {
  102. plog.Noticef("discovery cluster full, falling back to %s", fallbackFlagProxy)
  103. shouldProxy = true
  104. }
  105. }
  106. }
  107. if shouldProxy {
  108. err = startProxy(cfg)
  109. }
  110. }
  111. if err != nil {
  112. if derr, ok := err.(*etcdserver.DiscoveryError); ok {
  113. switch derr.Err {
  114. case discovery.ErrDuplicateID:
  115. plog.Errorf("member %q has previously registered with discovery service token (%s).", cfg.Name, cfg.Durl)
  116. plog.Errorf("But etcd could not find valid cluster configuration in the given data dir (%s).", cfg.Dir)
  117. plog.Infof("Please check the given data dir path if the previous bootstrap succeeded")
  118. plog.Infof("or use a new discovery token if the previous bootstrap failed.")
  119. case discovery.ErrDuplicateName:
  120. plog.Errorf("member with duplicated name has registered with discovery service token(%s).", cfg.Durl)
  121. plog.Errorf("please check (cURL) the discovery token for more information.")
  122. plog.Errorf("please do not reuse the discovery token and generate a new one to bootstrap the cluster.")
  123. default:
  124. plog.Errorf("%v", err)
  125. plog.Infof("discovery token %s was used, but failed to bootstrap the cluster.", cfg.Durl)
  126. plog.Infof("please generate a new discovery token and try to bootstrap again.")
  127. }
  128. os.Exit(1)
  129. }
  130. if strings.Contains(err.Error(), "include") && strings.Contains(err.Error(), "--initial-cluster") {
  131. plog.Infof("%v", err)
  132. if cfg.InitialCluster == cfg.InitialClusterFromName(cfg.Name) {
  133. plog.Infof("forgot to set --initial-cluster flag?")
  134. }
  135. if types.URLs(cfg.APUrls).String() == embed.DefaultInitialAdvertisePeerURLs {
  136. plog.Infof("forgot to set --initial-advertise-peer-urls flag?")
  137. }
  138. if cfg.InitialCluster == cfg.InitialClusterFromName(cfg.Name) && len(cfg.Durl) == 0 {
  139. plog.Infof("if you want to use discovery service, please set --discovery flag.")
  140. }
  141. os.Exit(1)
  142. }
  143. plog.Fatalf("%v", err)
  144. }
  145. osutil.HandleInterrupts()
  146. if systemdutil.IsRunningSystemd() {
  147. // At this point, the initialization of etcd is done.
  148. // The listeners are listening on the TCP ports and ready
  149. // for accepting connections. The etcd instance should be
  150. // joined with the cluster and ready to serve incoming
  151. // connections.
  152. sent, err := daemon.SdNotify(false, "READY=1")
  153. if err != nil {
  154. plog.Errorf("failed to notify systemd for readiness: %v", err)
  155. }
  156. if !sent {
  157. plog.Errorf("forgot to set Type=notify in systemd service file?")
  158. }
  159. }
  160. select {
  161. case lerr := <-errc:
  162. // fatal out on listener errors
  163. plog.Fatal(lerr)
  164. case <-stopped:
  165. }
  166. osutil.Exit(0)
  167. }
  168. // startEtcd runs StartEtcd in addition to hooks needed for standalone etcd.
  169. func startEtcd(cfg *embed.Config) (<-chan struct{}, <-chan error, error) {
  170. defaultHost, dhErr := cfg.IsDefaultHost()
  171. if defaultHost != "" {
  172. if dhErr == nil {
  173. plog.Infof("advertising using detected default host %q", defaultHost)
  174. } else {
  175. plog.Noticef("failed to detect default host, advertise falling back to %q (%v)", defaultHost, dhErr)
  176. }
  177. }
  178. if cfg.Metrics == "extensive" {
  179. grpc_prometheus.EnableHandlingTimeHistogram()
  180. }
  181. e, err := embed.StartEtcd(cfg)
  182. if err != nil {
  183. return nil, nil, err
  184. }
  185. osutil.RegisterInterruptHandler(e.Server.Stop)
  186. <-e.Server.ReadyNotify() // wait for e.Server to join the cluster
  187. return e.Server.StopNotify(), e.Err(), nil
  188. }
  189. // startProxy launches an HTTP proxy for client communication which proxies to other etcd nodes.
  190. func startProxy(cfg *config) error {
  191. plog.Notice("proxy: this proxy supports v2 API only!")
  192. pt, err := transport.NewTimeoutTransport(cfg.PeerTLSInfo, time.Duration(cfg.ProxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.ProxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.ProxyWriteTimeoutMs)*time.Millisecond)
  193. if err != nil {
  194. return err
  195. }
  196. pt.MaxIdleConnsPerHost = httpproxy.DefaultMaxIdleConnsPerHost
  197. tr, err := transport.NewTimeoutTransport(cfg.PeerTLSInfo, time.Duration(cfg.ProxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.ProxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.ProxyWriteTimeoutMs)*time.Millisecond)
  198. if err != nil {
  199. return err
  200. }
  201. cfg.Dir = path.Join(cfg.Dir, "proxy")
  202. err = os.MkdirAll(cfg.Dir, fileutil.PrivateDirMode)
  203. if err != nil {
  204. return err
  205. }
  206. var peerURLs []string
  207. clusterfile := path.Join(cfg.Dir, "cluster")
  208. b, err := ioutil.ReadFile(clusterfile)
  209. switch {
  210. case err == nil:
  211. if cfg.Durl != "" {
  212. plog.Warningf("discovery token ignored since the proxy has already been initialized. Valid cluster file found at %q", clusterfile)
  213. }
  214. if cfg.DNSCluster != "" {
  215. plog.Warningf("DNS SRV discovery ignored since the proxy has already been initialized. Valid cluster file found at %q", clusterfile)
  216. }
  217. urls := struct{ PeerURLs []string }{}
  218. err = json.Unmarshal(b, &urls)
  219. if err != nil {
  220. return err
  221. }
  222. peerURLs = urls.PeerURLs
  223. plog.Infof("proxy: using peer urls %v from cluster file %q", peerURLs, clusterfile)
  224. case os.IsNotExist(err):
  225. var urlsmap types.URLsMap
  226. urlsmap, _, err = cfg.PeerURLsMapAndToken("proxy")
  227. if err != nil {
  228. return fmt.Errorf("error setting up initial cluster: %v", err)
  229. }
  230. if cfg.Durl != "" {
  231. var s string
  232. s, err = discovery.GetCluster(cfg.Durl, cfg.Dproxy)
  233. if err != nil {
  234. return err
  235. }
  236. if urlsmap, err = types.NewURLsMap(s); err != nil {
  237. return err
  238. }
  239. }
  240. peerURLs = urlsmap.URLs()
  241. plog.Infof("proxy: using peer urls %v ", peerURLs)
  242. default:
  243. return err
  244. }
  245. clientURLs := []string{}
  246. uf := func() []string {
  247. gcls, gerr := etcdserver.GetClusterFromRemotePeers(peerURLs, tr)
  248. if gerr != nil {
  249. plog.Warningf("proxy: %v", gerr)
  250. return []string{}
  251. }
  252. clientURLs = gcls.ClientURLs()
  253. urls := struct{ PeerURLs []string }{gcls.PeerURLs()}
  254. b, jerr := json.Marshal(urls)
  255. if jerr != nil {
  256. plog.Warningf("proxy: error on marshal peer urls %s", jerr)
  257. return clientURLs
  258. }
  259. err = pkgioutil.WriteAndSyncFile(clusterfile+".bak", b, 0600)
  260. if err != nil {
  261. plog.Warningf("proxy: error on writing urls %s", err)
  262. return clientURLs
  263. }
  264. err = os.Rename(clusterfile+".bak", clusterfile)
  265. if err != nil {
  266. plog.Warningf("proxy: error on updating clusterfile %s", err)
  267. return clientURLs
  268. }
  269. if !reflect.DeepEqual(gcls.PeerURLs(), peerURLs) {
  270. plog.Noticef("proxy: updated peer urls in cluster file from %v to %v", peerURLs, gcls.PeerURLs())
  271. }
  272. peerURLs = gcls.PeerURLs()
  273. return clientURLs
  274. }
  275. ph := httpproxy.NewHandler(pt, uf, time.Duration(cfg.ProxyFailureWaitMs)*time.Millisecond, time.Duration(cfg.ProxyRefreshIntervalMs)*time.Millisecond)
  276. ph = &cors.CORSHandler{
  277. Handler: ph,
  278. Info: cfg.CorsInfo,
  279. }
  280. if cfg.isReadonlyProxy() {
  281. ph = httpproxy.NewReadonlyHandler(ph)
  282. }
  283. // Start a proxy server goroutine for each listen address
  284. for _, u := range cfg.LCUrls {
  285. var (
  286. l net.Listener
  287. tlscfg *tls.Config
  288. )
  289. if !cfg.ClientTLSInfo.Empty() {
  290. tlscfg, err = cfg.ClientTLSInfo.ServerConfig()
  291. if err != nil {
  292. return err
  293. }
  294. }
  295. l, err := transport.NewListener(u.Host, u.Scheme, tlscfg)
  296. if err != nil {
  297. return err
  298. }
  299. host := u.String()
  300. go func() {
  301. plog.Info("proxy: listening for client requests on ", host)
  302. mux := http.NewServeMux()
  303. mux.Handle("/metrics", prometheus.Handler())
  304. mux.Handle("/", ph)
  305. plog.Fatal(http.Serve(l, mux))
  306. }()
  307. }
  308. return nil
  309. }
  310. // identifyDataDirOrDie returns the type of the data dir.
  311. // Dies if the datadir is invalid.
  312. func identifyDataDirOrDie(dir string) dirType {
  313. names, err := fileutil.ReadDir(dir)
  314. if err != nil {
  315. if os.IsNotExist(err) {
  316. return dirEmpty
  317. }
  318. plog.Fatalf("error listing data dir: %s", dir)
  319. }
  320. var m, p bool
  321. for _, name := range names {
  322. switch dirType(name) {
  323. case dirMember:
  324. m = true
  325. case dirProxy:
  326. p = true
  327. default:
  328. plog.Warningf("found invalid file/dir %s under data dir %s (Ignore this if you are upgrading etcd)", name, dir)
  329. }
  330. }
  331. if m && p {
  332. plog.Fatal("invalid datadir. Both member and proxy directories exist.")
  333. }
  334. if m {
  335. return dirMember
  336. }
  337. if p {
  338. return dirProxy
  339. }
  340. return dirEmpty
  341. }
  342. func setupLogging(cfg *config) {
  343. capnslog.SetGlobalLogLevel(capnslog.INFO)
  344. if cfg.Debug {
  345. capnslog.SetGlobalLogLevel(capnslog.DEBUG)
  346. }
  347. if cfg.LogPkgLevels != "" {
  348. repoLog := capnslog.MustRepoLogger("github.com/coreos/etcd")
  349. settings, err := repoLog.ParseLogLevelConfig(cfg.LogPkgLevels)
  350. if err != nil {
  351. plog.Warningf("couldn't parse log level string: %s, continuing with default levels", err.Error())
  352. return
  353. }
  354. repoLog.SetLogLevel(settings)
  355. }
  356. // capnslog initially SetFormatter(NewDefaultFormatter(os.Stderr))
  357. // where NewDefaultFormatter returns NewJournaldFormatter when syscall.Getppid() == 1
  358. // specify 'stdout' or 'stderr' to skip journald logging even when running under systemd
  359. switch cfg.logOutput {
  360. case "stdout":
  361. capnslog.SetFormatter(capnslog.NewPrettyFormatter(os.Stdout, cfg.Debug))
  362. case "stderr":
  363. capnslog.SetFormatter(capnslog.NewPrettyFormatter(os.Stderr, cfg.Debug))
  364. case "default":
  365. default:
  366. plog.Panicf(`unknown log-output %q (only supports "default", "stdout", "stderr")`, cfg.logOutput)
  367. }
  368. }
  369. func checkSupportArch() {
  370. // TODO qualify arm64
  371. if runtime.GOARCH == "amd64" {
  372. return
  373. }
  374. if env, ok := os.LookupEnv("ETCD_UNSUPPORTED_ARCH"); ok && env == runtime.GOARCH {
  375. plog.Warningf("running etcd on unsupported architecture %q since ETCD_UNSUPPORTED_ARCH is set", env)
  376. return
  377. }
  378. plog.Errorf("etcd on unsupported platform without ETCD_UNSUPPORTED_ARCH=%s set.", runtime.GOARCH)
  379. os.Exit(1)
  380. }