etcd.go 13 KB

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