etcd.go 12 KB

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