etcd.go 13 KB

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