etcd.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. "encoding/json"
  17. "fmt"
  18. "io/ioutil"
  19. "net/http"
  20. "os"
  21. "path/filepath"
  22. "reflect"
  23. "runtime"
  24. "strings"
  25. "time"
  26. "github.com/coreos/etcd/discovery"
  27. "github.com/coreos/etcd/embed"
  28. "github.com/coreos/etcd/etcdserver"
  29. "github.com/coreos/etcd/etcdserver/api/etcdhttp"
  30. "github.com/coreos/etcd/pkg/fileutil"
  31. pkgioutil "github.com/coreos/etcd/pkg/ioutil"
  32. "github.com/coreos/etcd/pkg/osutil"
  33. "github.com/coreos/etcd/pkg/transport"
  34. "github.com/coreos/etcd/pkg/types"
  35. "github.com/coreos/etcd/proxy/httpproxy"
  36. "github.com/coreos/etcd/version"
  37. "github.com/coreos/pkg/capnslog"
  38. "google.golang.org/grpc"
  39. )
  40. type dirType string
  41. var plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "etcdmain")
  42. var (
  43. dirMember = dirType("member")
  44. dirProxy = dirType("proxy")
  45. dirEmpty = dirType("empty")
  46. )
  47. func startEtcdOrProxyV2() {
  48. grpc.EnableTracing = false
  49. cfg := newConfig()
  50. defaultInitialCluster := cfg.ec.InitialCluster
  51. err := cfg.parse(os.Args[1:])
  52. if err != nil {
  53. plog.Errorf("error verifying flags, %v. See 'etcd --help'.", err)
  54. switch err {
  55. case embed.ErrUnsetAdvertiseClientURLsFlag:
  56. plog.Errorf("When listening on specific address(es), this etcd process must advertise accessible url(s) to each connected client.")
  57. }
  58. os.Exit(1)
  59. }
  60. cfg.ec.SetupLogging()
  61. var stopped <-chan struct{}
  62. var errc <-chan error
  63. plog.Infof("etcd Version: %s\n", version.Version)
  64. plog.Infof("Git SHA: %s\n", version.GitSHA)
  65. plog.Infof("Go Version: %s\n", runtime.Version())
  66. plog.Infof("Go OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
  67. GoMaxProcs := runtime.GOMAXPROCS(0)
  68. plog.Infof("setting maximum number of CPUs to %d, total number of available CPUs is %d", GoMaxProcs, runtime.NumCPU())
  69. defaultHost, dhErr := (&cfg.ec).UpdateDefaultClusterFromName(defaultInitialCluster)
  70. if defaultHost != "" {
  71. plog.Infof("advertising using detected default host %q", defaultHost)
  72. }
  73. if dhErr != nil {
  74. plog.Noticef("failed to detect default host (%v)", dhErr)
  75. }
  76. if cfg.ec.Dir == "" {
  77. cfg.ec.Dir = fmt.Sprintf("%v.etcd", cfg.ec.Name)
  78. plog.Warningf("no data-dir provided, using default data-dir ./%s", cfg.ec.Dir)
  79. }
  80. which := identifyDataDirOrDie(cfg.ec.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.ec)
  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.ec)
  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.ec.Name, cfg.ec.Durl)
  111. plog.Errorf("But etcd could not find valid cluster configuration in the given data dir (%s).", cfg.ec.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.ec.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.ec.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.ec.InitialCluster == cfg.ec.InitialClusterFromName(cfg.ec.Name) {
  128. plog.Infof("forgot to set --initial-cluster flag?")
  129. }
  130. if types.URLs(cfg.ec.APUrls).String() == embed.DefaultInitialAdvertisePeerURLs {
  131. plog.Infof("forgot to set --initial-advertise-peer-urls flag?")
  132. }
  133. if cfg.ec.InitialCluster == cfg.ec.InitialClusterFromName(cfg.ec.Name) && len(cfg.ec.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. // At this point, the initialization of etcd is done.
  142. // The listeners are listening on the TCP ports and ready
  143. // for accepting connections. The etcd instance should be
  144. // joined with the cluster and ready to serve incoming
  145. // connections.
  146. notifySystemd()
  147. select {
  148. case lerr := <-errc:
  149. // fatal out on listener errors
  150. plog.Fatal(lerr)
  151. case <-stopped:
  152. }
  153. osutil.Exit(0)
  154. }
  155. // startEtcd runs StartEtcd in addition to hooks needed for standalone etcd.
  156. func startEtcd(cfg *embed.Config) (<-chan struct{}, <-chan error, error) {
  157. e, err := embed.StartEtcd(cfg)
  158. if err != nil {
  159. return nil, nil, err
  160. }
  161. osutil.RegisterInterruptHandler(e.Close)
  162. select {
  163. case <-e.Server.ReadyNotify(): // wait for e.Server to join the cluster
  164. case <-e.Server.StopNotify(): // publish aborted from 'ErrStopped'
  165. }
  166. return e.Server.StopNotify(), e.Err(), nil
  167. }
  168. // startProxy launches an HTTP proxy for client communication which proxies to other etcd nodes.
  169. func startProxy(cfg *config) error {
  170. plog.Notice("proxy: this proxy supports v2 API only!")
  171. clientTLSInfo := cfg.ec.ClientTLSInfo
  172. if clientTLSInfo.Empty() {
  173. // Support old proxy behavior of defaulting to PeerTLSInfo
  174. // for both client and peer connections.
  175. clientTLSInfo = cfg.ec.PeerTLSInfo
  176. }
  177. clientTLSInfo.InsecureSkipVerify = cfg.ec.ClientAutoTLS
  178. cfg.ec.PeerTLSInfo.InsecureSkipVerify = cfg.ec.PeerAutoTLS
  179. pt, err := transport.NewTimeoutTransport(clientTLSInfo, time.Duration(cfg.cp.ProxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.cp.ProxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.cp.ProxyWriteTimeoutMs)*time.Millisecond)
  180. if err != nil {
  181. return err
  182. }
  183. pt.MaxIdleConnsPerHost = httpproxy.DefaultMaxIdleConnsPerHost
  184. if err = cfg.ec.PeerSelfCert(); err != nil {
  185. plog.Fatalf("could not get certs (%v)", err)
  186. }
  187. tr, err := transport.NewTimeoutTransport(cfg.ec.PeerTLSInfo, time.Duration(cfg.cp.ProxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.cp.ProxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.cp.ProxyWriteTimeoutMs)*time.Millisecond)
  188. if err != nil {
  189. return err
  190. }
  191. cfg.ec.Dir = filepath.Join(cfg.ec.Dir, "proxy")
  192. err = os.MkdirAll(cfg.ec.Dir, fileutil.PrivateDirMode)
  193. if err != nil {
  194. return err
  195. }
  196. var peerURLs []string
  197. clusterfile := filepath.Join(cfg.ec.Dir, "cluster")
  198. b, err := ioutil.ReadFile(clusterfile)
  199. switch {
  200. case err == nil:
  201. if cfg.ec.Durl != "" {
  202. plog.Warningf("discovery token ignored since the proxy has already been initialized. Valid cluster file found at %q", clusterfile)
  203. }
  204. if cfg.ec.DNSCluster != "" {
  205. plog.Warningf("DNS SRV discovery ignored since the proxy has already been initialized. Valid cluster file found at %q", clusterfile)
  206. }
  207. urls := struct{ PeerURLs []string }{}
  208. err = json.Unmarshal(b, &urls)
  209. if err != nil {
  210. return err
  211. }
  212. peerURLs = urls.PeerURLs
  213. plog.Infof("proxy: using peer urls %v from cluster file %q", peerURLs, clusterfile)
  214. case os.IsNotExist(err):
  215. var urlsmap types.URLsMap
  216. urlsmap, _, err = cfg.ec.PeerURLsMapAndToken("proxy")
  217. if err != nil {
  218. return fmt.Errorf("error setting up initial cluster: %v", err)
  219. }
  220. if cfg.ec.Durl != "" {
  221. var s string
  222. s, err = discovery.GetCluster(cfg.ec.Durl, cfg.ec.Dproxy)
  223. if err != nil {
  224. return err
  225. }
  226. if urlsmap, err = types.NewURLsMap(s); err != nil {
  227. return err
  228. }
  229. }
  230. peerURLs = urlsmap.URLs()
  231. plog.Infof("proxy: using peer urls %v ", peerURLs)
  232. default:
  233. return err
  234. }
  235. clientURLs := []string{}
  236. uf := func() []string {
  237. gcls, gerr := etcdserver.GetClusterFromRemotePeers(peerURLs, tr)
  238. if gerr != nil {
  239. plog.Warningf("proxy: %v", gerr)
  240. return []string{}
  241. }
  242. clientURLs = gcls.ClientURLs()
  243. urls := struct{ PeerURLs []string }{gcls.PeerURLs()}
  244. b, jerr := json.Marshal(urls)
  245. if jerr != nil {
  246. plog.Warningf("proxy: error on marshal peer urls %s", jerr)
  247. return clientURLs
  248. }
  249. err = pkgioutil.WriteAndSyncFile(clusterfile+".bak", b, 0600)
  250. if err != nil {
  251. plog.Warningf("proxy: error on writing urls %s", err)
  252. return clientURLs
  253. }
  254. err = os.Rename(clusterfile+".bak", clusterfile)
  255. if err != nil {
  256. plog.Warningf("proxy: error on updating clusterfile %s", err)
  257. return clientURLs
  258. }
  259. if !reflect.DeepEqual(gcls.PeerURLs(), peerURLs) {
  260. plog.Noticef("proxy: updated peer urls in cluster file from %v to %v", peerURLs, gcls.PeerURLs())
  261. }
  262. peerURLs = gcls.PeerURLs()
  263. return clientURLs
  264. }
  265. ph := httpproxy.NewHandler(pt, uf, time.Duration(cfg.cp.ProxyFailureWaitMs)*time.Millisecond, time.Duration(cfg.cp.ProxyRefreshIntervalMs)*time.Millisecond)
  266. ph = embed.WrapCORS(cfg.ec.CORS, ph)
  267. if cfg.isReadonlyProxy() {
  268. ph = httpproxy.NewReadonlyHandler(ph)
  269. }
  270. // setup self signed certs when serving https
  271. cHosts, cTLS := []string{}, false
  272. for _, u := range cfg.ec.LCUrls {
  273. cHosts = append(cHosts, u.Host)
  274. cTLS = cTLS || u.Scheme == "https"
  275. }
  276. for _, u := range cfg.ec.ACUrls {
  277. cHosts = append(cHosts, u.Host)
  278. cTLS = cTLS || u.Scheme == "https"
  279. }
  280. listenerTLS := cfg.ec.ClientTLSInfo
  281. if cfg.ec.ClientAutoTLS && cTLS {
  282. listenerTLS, err = transport.SelfCert(filepath.Join(cfg.ec.Dir, "clientCerts"), cHosts)
  283. if err != nil {
  284. plog.Fatalf("proxy: could not initialize self-signed client certs (%v)", err)
  285. }
  286. }
  287. // Start a proxy server goroutine for each listen address
  288. for _, u := range cfg.ec.LCUrls {
  289. l, err := transport.NewListener(u.Host, u.Scheme, &listenerTLS)
  290. if err != nil {
  291. return err
  292. }
  293. host := u.String()
  294. go func() {
  295. plog.Info("proxy: listening for client requests on ", host)
  296. mux := http.NewServeMux()
  297. etcdhttp.HandlePrometheus(mux) // v2 proxy just uses the same port
  298. mux.Handle("/", ph)
  299. plog.Fatal(http.Serve(l, mux))
  300. }()
  301. }
  302. return nil
  303. }
  304. // identifyDataDirOrDie returns the type of the data dir.
  305. // Dies if the datadir is invalid.
  306. func identifyDataDirOrDie(dir string) dirType {
  307. names, err := fileutil.ReadDir(dir)
  308. if err != nil {
  309. if os.IsNotExist(err) {
  310. return dirEmpty
  311. }
  312. plog.Fatalf("error listing data dir: %s", dir)
  313. }
  314. var m, p bool
  315. for _, name := range names {
  316. switch dirType(name) {
  317. case dirMember:
  318. m = true
  319. case dirProxy:
  320. p = true
  321. default:
  322. plog.Warningf("found invalid file/dir %s under data dir %s (Ignore this if you are upgrading etcd)", name, dir)
  323. }
  324. }
  325. if m && p {
  326. plog.Fatal("invalid datadir. Both member and proxy directories exist.")
  327. }
  328. if m {
  329. return dirMember
  330. }
  331. if p {
  332. return dirProxy
  333. }
  334. return dirEmpty
  335. }
  336. func checkSupportArch() {
  337. // TODO qualify arm64
  338. if runtime.GOARCH == "amd64" || runtime.GOARCH == "ppc64le" {
  339. return
  340. }
  341. // unsupported arch only configured via environment variable
  342. // so unset here to not parse through flag
  343. defer os.Unsetenv("ETCD_UNSUPPORTED_ARCH")
  344. if env, ok := os.LookupEnv("ETCD_UNSUPPORTED_ARCH"); ok && env == runtime.GOARCH {
  345. plog.Warningf("running etcd on unsupported architecture %q since ETCD_UNSUPPORTED_ARCH is set", env)
  346. return
  347. }
  348. plog.Errorf("etcd on unsupported platform without ETCD_UNSUPPORTED_ARCH=%s set.", runtime.GOARCH)
  349. os.Exit(1)
  350. }