etcd.go 12 KB

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