etcd.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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"
  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/go-systemd/daemon"
  40. systemdutil "github.com/coreos/go-systemd/util"
  41. "github.com/coreos/pkg/capnslog"
  42. "github.com/prometheus/client_golang/prometheus"
  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. cfg := newConfig()
  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. setupLogging(cfg)
  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. // TODO: check whether fields are set instead of whether fields have default value
  72. if cfg.Name != embed.DefaultName && cfg.InitialCluster == cfg.InitialClusterFromName(embed.DefaultName) {
  73. cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
  74. }
  75. if cfg.Dir == "" {
  76. cfg.Dir = fmt.Sprintf("%v.etcd", cfg.Name)
  77. plog.Warningf("no data-dir provided, using default data-dir ./%s", cfg.Dir)
  78. }
  79. which := identifyDataDirOrDie(cfg.Dir)
  80. if which != dirEmpty {
  81. plog.Noticef("the server is already initialized as %v before, starting as etcd %v...", which, which)
  82. switch which {
  83. case dirMember:
  84. stopped, errc, err = startEtcd(&cfg.Config)
  85. case dirProxy:
  86. err = startProxy(cfg)
  87. default:
  88. plog.Panicf("unhandled dir type %v", which)
  89. }
  90. } else {
  91. shouldProxy := cfg.isProxy()
  92. if !shouldProxy {
  93. stopped, errc, err = startEtcd(&cfg.Config)
  94. if derr, ok := err.(*etcdserver.DiscoveryError); ok && derr.Err == discovery.ErrFullCluster {
  95. if cfg.shouldFallbackToProxy() {
  96. plog.Noticef("discovery cluster full, falling back to %s", fallbackFlagProxy)
  97. shouldProxy = true
  98. }
  99. }
  100. }
  101. if shouldProxy {
  102. err = startProxy(cfg)
  103. }
  104. }
  105. if err != nil {
  106. if derr, ok := err.(*etcdserver.DiscoveryError); ok {
  107. switch derr.Err {
  108. case discovery.ErrDuplicateID:
  109. plog.Errorf("member %q has previously registered with discovery service token (%s).", cfg.Name, cfg.Durl)
  110. plog.Errorf("But etcd could not find valid cluster configuration in the given data dir (%s).", cfg.Dir)
  111. plog.Infof("Please check the given data dir path if the previous bootstrap succeeded")
  112. plog.Infof("or use a new discovery token if the previous bootstrap failed.")
  113. case discovery.ErrDuplicateName:
  114. plog.Errorf("member with duplicated name has registered with discovery service token(%s).", cfg.Durl)
  115. plog.Errorf("please check (cURL) the discovery token for more information.")
  116. plog.Errorf("please do not reuse the discovery token and generate a new one to bootstrap the cluster.")
  117. default:
  118. plog.Errorf("%v", err)
  119. plog.Infof("discovery token %s was used, but failed to bootstrap the cluster.", cfg.Durl)
  120. plog.Infof("please generate a new discovery token and try to bootstrap again.")
  121. }
  122. os.Exit(1)
  123. }
  124. if strings.Contains(err.Error(), "include") && strings.Contains(err.Error(), "--initial-cluster") {
  125. plog.Infof("%v", err)
  126. if cfg.InitialCluster == cfg.InitialClusterFromName(cfg.Name) {
  127. plog.Infof("forgot to set --initial-cluster flag?")
  128. }
  129. if types.URLs(cfg.APUrls).String() == embed.DefaultInitialAdvertisePeerURLs {
  130. plog.Infof("forgot to set --initial-advertise-peer-urls flag?")
  131. }
  132. if cfg.InitialCluster == cfg.InitialClusterFromName(cfg.Name) && len(cfg.Durl) == 0 {
  133. plog.Infof("if you want to use discovery service, please set --discovery flag.")
  134. }
  135. os.Exit(1)
  136. }
  137. plog.Fatalf("%v", err)
  138. }
  139. osutil.HandleInterrupts()
  140. if systemdutil.IsRunningSystemd() {
  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. err := daemon.SdNotify("READY=1")
  147. if err != nil {
  148. plog.Errorf("failed to notify systemd for readiness: %v", err)
  149. if err == daemon.SdNotifyNoSocket {
  150. plog.Errorf("forgot to set Type=notify in systemd service file?")
  151. }
  152. }
  153. }
  154. select {
  155. case lerr := <-errc:
  156. // fatal out on listener errors
  157. plog.Fatal(lerr)
  158. case <-stopped:
  159. }
  160. osutil.Exit(0)
  161. }
  162. // startEtcd runs StartEtcd in addition to hooks needed for standalone etcd.
  163. func startEtcd(cfg *embed.Config) (<-chan struct{}, <-chan error, error) {
  164. e, err := embed.StartEtcd(cfg)
  165. if err != nil {
  166. return nil, nil, err
  167. }
  168. osutil.RegisterInterruptHandler(e.Server.Stop)
  169. return e.Server.StopNotify(), e.Err(), nil
  170. }
  171. // startProxy launches an HTTP proxy for client communication which proxies to other etcd nodes.
  172. func startProxy(cfg *config) error {
  173. plog.Notice("proxy: this proxy supports v2 API only!")
  174. pt, err := transport.NewTimeoutTransport(cfg.PeerTLSInfo, time.Duration(cfg.ProxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.ProxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.ProxyWriteTimeoutMs)*time.Millisecond)
  175. if err != nil {
  176. return err
  177. }
  178. pt.MaxIdleConnsPerHost = httpproxy.DefaultMaxIdleConnsPerHost
  179. tr, err := transport.NewTimeoutTransport(cfg.PeerTLSInfo, time.Duration(cfg.ProxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.ProxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.ProxyWriteTimeoutMs)*time.Millisecond)
  180. if err != nil {
  181. return err
  182. }
  183. cfg.Dir = path.Join(cfg.Dir, "proxy")
  184. err = os.MkdirAll(cfg.Dir, fileutil.PrivateDirMode)
  185. if err != nil {
  186. return err
  187. }
  188. var peerURLs []string
  189. clusterfile := path.Join(cfg.Dir, "cluster")
  190. b, err := ioutil.ReadFile(clusterfile)
  191. switch {
  192. case err == nil:
  193. if cfg.Durl != "" {
  194. plog.Warningf("discovery token ignored since the proxy has already been initialized. Valid cluster file found at %q", clusterfile)
  195. }
  196. if cfg.DNSCluster != "" {
  197. plog.Warningf("DNS SRV discovery ignored since the proxy has already been initialized. Valid cluster file found at %q", clusterfile)
  198. }
  199. urls := struct{ PeerURLs []string }{}
  200. err = json.Unmarshal(b, &urls)
  201. if err != nil {
  202. return err
  203. }
  204. peerURLs = urls.PeerURLs
  205. plog.Infof("proxy: using peer urls %v from cluster file %q", peerURLs, clusterfile)
  206. case os.IsNotExist(err):
  207. var urlsmap types.URLsMap
  208. urlsmap, _, err = cfg.PeerURLsMapAndToken("proxy")
  209. if err != nil {
  210. return fmt.Errorf("error setting up initial cluster: %v", err)
  211. }
  212. if cfg.Durl != "" {
  213. var s string
  214. s, err = discovery.GetCluster(cfg.Durl, cfg.Dproxy)
  215. if err != nil {
  216. return err
  217. }
  218. if urlsmap, err = types.NewURLsMap(s); err != nil {
  219. return err
  220. }
  221. }
  222. peerURLs = urlsmap.URLs()
  223. plog.Infof("proxy: using peer urls %v ", peerURLs)
  224. default:
  225. return err
  226. }
  227. clientURLs := []string{}
  228. uf := func() []string {
  229. gcls, gerr := etcdserver.GetClusterFromRemotePeers(peerURLs, tr)
  230. // TODO: remove the 2nd check when we fix GetClusterFromRemotePeers
  231. // GetClusterFromRemotePeers should not return nil error with an invalid empty cluster
  232. if gerr != nil {
  233. plog.Warningf("proxy: %v", gerr)
  234. return []string{}
  235. }
  236. if len(gcls.Members()) == 0 {
  237. return clientURLs
  238. }
  239. clientURLs = gcls.ClientURLs()
  240. urls := struct{ PeerURLs []string }{gcls.PeerURLs()}
  241. b, jerr := json.Marshal(urls)
  242. if jerr != nil {
  243. plog.Warningf("proxy: error on marshal peer urls %s", jerr)
  244. return clientURLs
  245. }
  246. err = pkgioutil.WriteAndSyncFile(clusterfile+".bak", b, 0600)
  247. if err != nil {
  248. plog.Warningf("proxy: error on writing urls %s", err)
  249. return clientURLs
  250. }
  251. err = os.Rename(clusterfile+".bak", clusterfile)
  252. if err != nil {
  253. plog.Warningf("proxy: error on updating clusterfile %s", err)
  254. return clientURLs
  255. }
  256. if !reflect.DeepEqual(gcls.PeerURLs(), peerURLs) {
  257. plog.Noticef("proxy: updated peer urls in cluster file from %v to %v", peerURLs, gcls.PeerURLs())
  258. }
  259. peerURLs = gcls.PeerURLs()
  260. return clientURLs
  261. }
  262. ph := httpproxy.NewHandler(pt, uf, time.Duration(cfg.ProxyFailureWaitMs)*time.Millisecond, time.Duration(cfg.ProxyRefreshIntervalMs)*time.Millisecond)
  263. ph = &cors.CORSHandler{
  264. Handler: ph,
  265. Info: cfg.CorsInfo,
  266. }
  267. if cfg.isReadonlyProxy() {
  268. ph = httpproxy.NewReadonlyHandler(ph)
  269. }
  270. // Start a proxy server goroutine for each listen address
  271. for _, u := range cfg.LCUrls {
  272. var (
  273. l net.Listener
  274. tlscfg *tls.Config
  275. )
  276. if !cfg.ClientTLSInfo.Empty() {
  277. tlscfg, err = cfg.ClientTLSInfo.ServerConfig()
  278. if err != nil {
  279. return err
  280. }
  281. }
  282. l, err := transport.NewListener(u.Host, u.Scheme, tlscfg)
  283. if err != nil {
  284. return err
  285. }
  286. host := u.String()
  287. go func() {
  288. plog.Info("proxy: listening for client requests on ", host)
  289. mux := http.NewServeMux()
  290. mux.Handle("/metrics", prometheus.Handler())
  291. mux.Handle("/", ph)
  292. plog.Fatal(http.Serve(l, mux))
  293. }()
  294. }
  295. return nil
  296. }
  297. // identifyDataDirOrDie returns the type of the data dir.
  298. // Dies if the datadir is invalid.
  299. func identifyDataDirOrDie(dir string) dirType {
  300. names, err := fileutil.ReadDir(dir)
  301. if err != nil {
  302. if os.IsNotExist(err) {
  303. return dirEmpty
  304. }
  305. plog.Fatalf("error listing data dir: %s", dir)
  306. }
  307. var m, p bool
  308. for _, name := range names {
  309. switch dirType(name) {
  310. case dirMember:
  311. m = true
  312. case dirProxy:
  313. p = true
  314. default:
  315. plog.Warningf("found invalid file/dir %s under data dir %s (Ignore this if you are upgrading etcd)", name, dir)
  316. }
  317. }
  318. if m && p {
  319. plog.Fatal("invalid datadir. Both member and proxy directories exist.")
  320. }
  321. if m {
  322. return dirMember
  323. }
  324. if p {
  325. return dirProxy
  326. }
  327. return dirEmpty
  328. }
  329. func setupLogging(cfg *config) {
  330. capnslog.SetGlobalLogLevel(capnslog.INFO)
  331. if cfg.Debug {
  332. capnslog.SetGlobalLogLevel(capnslog.DEBUG)
  333. }
  334. if cfg.LogPkgLevels != "" {
  335. repoLog := capnslog.MustRepoLogger("github.com/coreos/etcd")
  336. settings, err := repoLog.ParseLogLevelConfig(cfg.LogPkgLevels)
  337. if err != nil {
  338. plog.Warningf("couldn't parse log level string: %s, continuing with default levels", err.Error())
  339. return
  340. }
  341. repoLog.SetLogLevel(settings)
  342. }
  343. }
  344. func checkSupportArch() {
  345. // TODO qualify arm64
  346. if runtime.GOARCH == "amd64" {
  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. }