etcd.go 12 KB

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