etcd.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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. "google.golang.org/grpc"
  44. )
  45. type dirType string
  46. var plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "etcdmain")
  47. var (
  48. dirMember = dirType("member")
  49. dirProxy = dirType("proxy")
  50. dirEmpty = dirType("empty")
  51. )
  52. func startEtcdOrProxyV2() {
  53. grpc.EnableTracing = false
  54. cfg := newConfig()
  55. err := cfg.parse(os.Args[1:])
  56. if err != nil {
  57. plog.Errorf("error verifying flags, %v. See 'etcd --help'.", err)
  58. switch err {
  59. case embed.ErrUnsetAdvertiseClientURLsFlag:
  60. plog.Errorf("When listening on specific address(es), this etcd process must advertise accessible url(s) to each connected client.")
  61. }
  62. os.Exit(1)
  63. }
  64. setupLogging(cfg)
  65. var stopped <-chan struct{}
  66. var errc <-chan error
  67. plog.Infof("etcd Version: %s\n", version.Version)
  68. plog.Infof("Git SHA: %s\n", version.GitSHA)
  69. plog.Infof("Go Version: %s\n", runtime.Version())
  70. plog.Infof("Go OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
  71. GoMaxProcs := runtime.GOMAXPROCS(0)
  72. plog.Infof("setting maximum number of CPUs to %d, total number of available CPUs is %d", GoMaxProcs, runtime.NumCPU())
  73. // TODO: check whether fields are set instead of whether fields have default value
  74. if cfg.Name != embed.DefaultName && cfg.InitialCluster == cfg.InitialClusterFromName(embed.DefaultName) {
  75. cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
  76. }
  77. if cfg.Dir == "" {
  78. cfg.Dir = fmt.Sprintf("%v.etcd", cfg.Name)
  79. plog.Warningf("no data-dir provided, using default data-dir ./%s", cfg.Dir)
  80. }
  81. which := identifyDataDirOrDie(cfg.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.Config)
  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.Config)
  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.Name, cfg.Durl)
  112. plog.Errorf("But etcd could not find valid cluster configuration in the given data dir (%s).", cfg.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.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.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.InitialCluster == cfg.InitialClusterFromName(cfg.Name) {
  129. plog.Infof("forgot to set --initial-cluster flag?")
  130. }
  131. if types.URLs(cfg.APUrls).String() == embed.DefaultInitialAdvertisePeerURLs {
  132. plog.Infof("forgot to set --initial-advertise-peer-urls flag?")
  133. }
  134. if cfg.InitialCluster == cfg.InitialClusterFromName(cfg.Name) && len(cfg.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. if systemdutil.IsRunningSystemd() {
  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. sent, err := daemon.SdNotify("READY=1")
  149. if err != nil {
  150. plog.Errorf("failed to notify systemd for readiness: %v", err)
  151. }
  152. if !sent {
  153. plog.Errorf("forgot to set Type=notify in systemd service file?")
  154. }
  155. }
  156. select {
  157. case lerr := <-errc:
  158. // fatal out on listener errors
  159. plog.Fatal(lerr)
  160. case <-stopped:
  161. }
  162. osutil.Exit(0)
  163. }
  164. // startEtcd runs StartEtcd in addition to hooks needed for standalone etcd.
  165. func startEtcd(cfg *embed.Config) (<-chan struct{}, <-chan error, error) {
  166. e, err := embed.StartEtcd(cfg)
  167. if err != nil {
  168. return nil, nil, err
  169. }
  170. osutil.RegisterInterruptHandler(e.Server.Stop)
  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. pt, err := transport.NewTimeoutTransport(cfg.PeerTLSInfo, time.Duration(cfg.ProxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.ProxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.ProxyWriteTimeoutMs)*time.Millisecond)
  177. if err != nil {
  178. return err
  179. }
  180. pt.MaxIdleConnsPerHost = httpproxy.DefaultMaxIdleConnsPerHost
  181. tr, err := transport.NewTimeoutTransport(cfg.PeerTLSInfo, time.Duration(cfg.ProxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.ProxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.ProxyWriteTimeoutMs)*time.Millisecond)
  182. if err != nil {
  183. return err
  184. }
  185. cfg.Dir = path.Join(cfg.Dir, "proxy")
  186. err = os.MkdirAll(cfg.Dir, fileutil.PrivateDirMode)
  187. if err != nil {
  188. return err
  189. }
  190. var peerURLs []string
  191. clusterfile := path.Join(cfg.Dir, "cluster")
  192. b, err := ioutil.ReadFile(clusterfile)
  193. switch {
  194. case err == nil:
  195. if cfg.Durl != "" {
  196. plog.Warningf("discovery token ignored since the proxy has already been initialized. Valid cluster file found at %q", clusterfile)
  197. }
  198. if cfg.DNSCluster != "" {
  199. plog.Warningf("DNS SRV discovery ignored since the proxy has already been initialized. Valid cluster file found at %q", clusterfile)
  200. }
  201. urls := struct{ PeerURLs []string }{}
  202. err = json.Unmarshal(b, &urls)
  203. if err != nil {
  204. return err
  205. }
  206. peerURLs = urls.PeerURLs
  207. plog.Infof("proxy: using peer urls %v from cluster file %q", peerURLs, clusterfile)
  208. case os.IsNotExist(err):
  209. var urlsmap types.URLsMap
  210. urlsmap, _, err = cfg.PeerURLsMapAndToken("proxy")
  211. if err != nil {
  212. return fmt.Errorf("error setting up initial cluster: %v", err)
  213. }
  214. if cfg.Durl != "" {
  215. var s string
  216. s, err = discovery.GetCluster(cfg.Durl, cfg.Dproxy)
  217. if err != nil {
  218. return err
  219. }
  220. if urlsmap, err = types.NewURLsMap(s); err != nil {
  221. return err
  222. }
  223. }
  224. peerURLs = urlsmap.URLs()
  225. plog.Infof("proxy: using peer urls %v ", peerURLs)
  226. default:
  227. return err
  228. }
  229. clientURLs := []string{}
  230. uf := func() []string {
  231. gcls, gerr := etcdserver.GetClusterFromRemotePeers(peerURLs, tr)
  232. // TODO: remove the 2nd check when we fix GetClusterFromRemotePeers
  233. // GetClusterFromRemotePeers should not return nil error with an invalid empty cluster
  234. if gerr != nil {
  235. plog.Warningf("proxy: %v", gerr)
  236. return []string{}
  237. }
  238. if len(gcls.Members()) == 0 {
  239. return clientURLs
  240. }
  241. clientURLs = gcls.ClientURLs()
  242. urls := struct{ PeerURLs []string }{gcls.PeerURLs()}
  243. b, jerr := json.Marshal(urls)
  244. if jerr != nil {
  245. plog.Warningf("proxy: error on marshal peer urls %s", jerr)
  246. return clientURLs
  247. }
  248. err = pkgioutil.WriteAndSyncFile(clusterfile+".bak", b, 0600)
  249. if err != nil {
  250. plog.Warningf("proxy: error on writing urls %s", err)
  251. return clientURLs
  252. }
  253. err = os.Rename(clusterfile+".bak", clusterfile)
  254. if err != nil {
  255. plog.Warningf("proxy: error on updating clusterfile %s", err)
  256. return clientURLs
  257. }
  258. if !reflect.DeepEqual(gcls.PeerURLs(), peerURLs) {
  259. plog.Noticef("proxy: updated peer urls in cluster file from %v to %v", peerURLs, gcls.PeerURLs())
  260. }
  261. peerURLs = gcls.PeerURLs()
  262. return clientURLs
  263. }
  264. ph := httpproxy.NewHandler(pt, uf, time.Duration(cfg.ProxyFailureWaitMs)*time.Millisecond, time.Duration(cfg.ProxyRefreshIntervalMs)*time.Millisecond)
  265. ph = &cors.CORSHandler{
  266. Handler: ph,
  267. Info: cfg.CorsInfo,
  268. }
  269. if cfg.isReadonlyProxy() {
  270. ph = httpproxy.NewReadonlyHandler(ph)
  271. }
  272. // Start a proxy server goroutine for each listen address
  273. for _, u := range cfg.LCUrls {
  274. var (
  275. l net.Listener
  276. tlscfg *tls.Config
  277. )
  278. if !cfg.ClientTLSInfo.Empty() {
  279. tlscfg, err = cfg.ClientTLSInfo.ServerConfig()
  280. if err != nil {
  281. return err
  282. }
  283. }
  284. l, err := transport.NewListener(u.Host, u.Scheme, tlscfg)
  285. if err != nil {
  286. return err
  287. }
  288. host := u.String()
  289. go func() {
  290. plog.Info("proxy: listening for client requests on ", host)
  291. mux := http.NewServeMux()
  292. mux.Handle("/metrics", prometheus.Handler())
  293. mux.Handle("/", ph)
  294. plog.Fatal(http.Serve(l, mux))
  295. }()
  296. }
  297. return nil
  298. }
  299. // identifyDataDirOrDie returns the type of the data dir.
  300. // Dies if the datadir is invalid.
  301. func identifyDataDirOrDie(dir string) dirType {
  302. names, err := fileutil.ReadDir(dir)
  303. if err != nil {
  304. if os.IsNotExist(err) {
  305. return dirEmpty
  306. }
  307. plog.Fatalf("error listing data dir: %s", dir)
  308. }
  309. var m, p bool
  310. for _, name := range names {
  311. switch dirType(name) {
  312. case dirMember:
  313. m = true
  314. case dirProxy:
  315. p = true
  316. default:
  317. plog.Warningf("found invalid file/dir %s under data dir %s (Ignore this if you are upgrading etcd)", name, dir)
  318. }
  319. }
  320. if m && p {
  321. plog.Fatal("invalid datadir. Both member and proxy directories exist.")
  322. }
  323. if m {
  324. return dirMember
  325. }
  326. if p {
  327. return dirProxy
  328. }
  329. return dirEmpty
  330. }
  331. func setupLogging(cfg *config) {
  332. capnslog.SetGlobalLogLevel(capnslog.INFO)
  333. if cfg.Debug {
  334. capnslog.SetGlobalLogLevel(capnslog.DEBUG)
  335. }
  336. if cfg.LogPkgLevels != "" {
  337. repoLog := capnslog.MustRepoLogger("github.com/coreos/etcd")
  338. settings, err := repoLog.ParseLogLevelConfig(cfg.LogPkgLevels)
  339. if err != nil {
  340. plog.Warningf("couldn't parse log level string: %s, continuing with default levels", err.Error())
  341. return
  342. }
  343. repoLog.SetLogLevel(settings)
  344. }
  345. }
  346. func checkSupportArch() {
  347. // TODO qualify arm64
  348. if runtime.GOARCH == "amd64" {
  349. return
  350. }
  351. if env, ok := os.LookupEnv("ETCD_UNSUPPORTED_ARCH"); ok && env == runtime.GOARCH {
  352. plog.Warningf("running etcd on unsupported architecture %q since ETCD_UNSUPPORTED_ARCH is set", env)
  353. return
  354. }
  355. plog.Errorf("etcd on unsupported platform without ETCD_UNSUPPORTED_ARCH=%s set.", runtime.GOARCH)
  356. os.Exit(1)
  357. }