etcd.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. // Copyright 2015 CoreOS, Inc.
  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"
  20. "net/http"
  21. "os"
  22. "path"
  23. "reflect"
  24. "runtime"
  25. "strconv"
  26. "time"
  27. "github.com/coreos/etcd/discovery"
  28. "github.com/coreos/etcd/etcdserver"
  29. "github.com/coreos/etcd/etcdserver/etcdhttp"
  30. "github.com/coreos/etcd/pkg/cors"
  31. "github.com/coreos/etcd/pkg/fileutil"
  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"
  36. "github.com/coreos/etcd/rafthttp"
  37. "github.com/coreos/etcd/version"
  38. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/pkg/capnslog"
  39. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus"
  40. )
  41. type dirType string
  42. var plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "etcdmain")
  43. const (
  44. // the owner can make/remove files inside the directory
  45. privateDirMode = 0700
  46. )
  47. var (
  48. dirMember = dirType("member")
  49. dirProxy = dirType("proxy")
  50. dirEmpty = dirType("empty")
  51. )
  52. func Main() {
  53. capnslog.SetFormatter(capnslog.NewStringFormatter(os.Stderr))
  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 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. plog.Infof("etcd Version: %s\n", version.Version)
  67. plog.Infof("Git SHA: %s\n", version.GitSHA)
  68. plog.Infof("Go Version: %s\n", runtime.Version())
  69. plog.Infof("Go OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
  70. GoMaxProcs := 1
  71. if envMaxProcs, err := strconv.Atoi(os.Getenv("GOMAXPROCS")); err == nil {
  72. GoMaxProcs = envMaxProcs
  73. }
  74. plog.Infof("setting maximum number of CPUs to %d, total number of available CPUs is %d", GoMaxProcs, runtime.NumCPU())
  75. runtime.GOMAXPROCS(GoMaxProcs)
  76. // TODO: check whether fields are set instead of whether fields have default value
  77. if cfg.name != defaultName && cfg.initialCluster == initialClusterFromName(defaultName) {
  78. cfg.initialCluster = initialClusterFromName(cfg.name)
  79. }
  80. if cfg.dir == "" {
  81. cfg.dir = fmt.Sprintf("%v.etcd", cfg.name)
  82. plog.Warningf("no data-dir provided, using default data-dir ./%s", cfg.dir)
  83. }
  84. which := identifyDataDirOrDie(cfg.dir)
  85. if which != dirEmpty {
  86. plog.Noticef("the server is already initialized as %v before, starting as etcd %v...", which, which)
  87. switch which {
  88. case dirMember:
  89. stopped, err = startEtcd(cfg)
  90. case dirProxy:
  91. err = startProxy(cfg)
  92. default:
  93. plog.Panicf("unhandled dir type %v", which)
  94. }
  95. } else {
  96. shouldProxy := cfg.isProxy()
  97. if !shouldProxy {
  98. stopped, err = startEtcd(cfg)
  99. if err == discovery.ErrFullCluster && cfg.shouldFallbackToProxy() {
  100. plog.Noticef("discovery cluster full, falling back to %s", fallbackFlagProxy)
  101. shouldProxy = true
  102. }
  103. }
  104. if shouldProxy {
  105. err = startProxy(cfg)
  106. }
  107. }
  108. if err != nil {
  109. switch 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 vaild 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. os.Exit(1)
  116. default:
  117. plog.Fatalf("%v", err)
  118. }
  119. }
  120. osutil.HandleInterrupts()
  121. <-stopped
  122. osutil.Exit(0)
  123. }
  124. // startEtcd launches the etcd server and HTTP handlers for client/server communication.
  125. func startEtcd(cfg *config) (<-chan struct{}, error) {
  126. urlsmap, token, err := getPeerURLsMapAndToken(cfg)
  127. if err != nil {
  128. return nil, fmt.Errorf("error setting up initial cluster: %v", err)
  129. }
  130. pt, err := transport.NewTimeoutTransport(cfg.peerTLSInfo, rafthttp.DialTimeout, rafthttp.ConnReadTimeout, rafthttp.ConnWriteTimeout)
  131. if err != nil {
  132. return nil, err
  133. }
  134. if !cfg.peerTLSInfo.Empty() {
  135. plog.Infof("peerTLS: %s", cfg.peerTLSInfo)
  136. }
  137. plns := make([]net.Listener, 0)
  138. for _, u := range cfg.lpurls {
  139. if u.Scheme == "http" && !cfg.peerTLSInfo.Empty() {
  140. plog.Warningf("The scheme of peer url %s is http while peer key/cert files are presented. Ignored peer key/cert files.", u.String())
  141. }
  142. var l net.Listener
  143. l, err = transport.NewTimeoutListener(u.Host, u.Scheme, cfg.peerTLSInfo, rafthttp.ConnReadTimeout, rafthttp.ConnWriteTimeout)
  144. if err != nil {
  145. return nil, err
  146. }
  147. urlStr := u.String()
  148. plog.Info("listening for peers on ", urlStr)
  149. defer func() {
  150. if err != nil {
  151. l.Close()
  152. plog.Info("stopping listening for peers on ", urlStr)
  153. }
  154. }()
  155. plns = append(plns, l)
  156. }
  157. if !cfg.clientTLSInfo.Empty() {
  158. plog.Infof("clientTLS: %s", cfg.clientTLSInfo)
  159. }
  160. clns := make([]net.Listener, 0)
  161. for _, u := range cfg.lcurls {
  162. if u.Scheme == "http" && !cfg.clientTLSInfo.Empty() {
  163. plog.Warningf("The scheme of client url %s is http while client key/cert files are presented. Ignored client key/cert files.", u.String())
  164. }
  165. var l net.Listener
  166. l, err = transport.NewKeepAliveListener(u.Host, u.Scheme, cfg.clientTLSInfo)
  167. if err != nil {
  168. return nil, err
  169. }
  170. urlStr := u.String()
  171. plog.Info("listening for client requests on ", urlStr)
  172. defer func() {
  173. if err != nil {
  174. l.Close()
  175. plog.Info("stopping listening for client requests on ", urlStr)
  176. }
  177. }()
  178. clns = append(clns, l)
  179. }
  180. srvcfg := &etcdserver.ServerConfig{
  181. Name: cfg.name,
  182. ClientURLs: cfg.acurls,
  183. PeerURLs: cfg.apurls,
  184. DataDir: cfg.dir,
  185. SnapCount: cfg.snapCount,
  186. MaxSnapFiles: cfg.maxSnapFiles,
  187. MaxWALFiles: cfg.maxWalFiles,
  188. InitialPeerURLsMap: urlsmap,
  189. InitialClusterToken: token,
  190. DiscoveryURL: cfg.durl,
  191. DiscoveryProxy: cfg.dproxy,
  192. NewCluster: cfg.isNewCluster(),
  193. ForceNewCluster: cfg.forceNewCluster,
  194. Transport: pt,
  195. TickMs: cfg.TickMs,
  196. ElectionTicks: cfg.electionTicks(),
  197. }
  198. var s *etcdserver.EtcdServer
  199. s, err = etcdserver.NewServer(srvcfg)
  200. if err != nil {
  201. return nil, err
  202. }
  203. s.Start()
  204. osutil.RegisterInterruptHandler(s.Stop)
  205. if cfg.corsInfo.String() != "" {
  206. plog.Infof("cors = %s", cfg.corsInfo)
  207. }
  208. ch := &cors.CORSHandler{
  209. Handler: etcdhttp.NewClientHandler(s),
  210. Info: cfg.corsInfo,
  211. }
  212. ph := etcdhttp.NewPeerHandler(s.Cluster(), s.RaftHandler())
  213. // Start the peer server in a goroutine
  214. for _, l := range plns {
  215. go func(l net.Listener) {
  216. plog.Fatal(serveHTTP(l, ph, 5*time.Minute))
  217. }(l)
  218. }
  219. // Start a client server goroutine for each listen address
  220. for _, l := range clns {
  221. go func(l net.Listener) {
  222. // read timeout does not work with http close notify
  223. // TODO: https://github.com/golang/go/issues/9524
  224. plog.Fatal(serveHTTP(l, ch, 0))
  225. }(l)
  226. }
  227. return s.StopNotify(), nil
  228. }
  229. // startProxy launches an HTTP proxy for client communication which proxies to other etcd nodes.
  230. func startProxy(cfg *config) error {
  231. urlsmap, _, err := getPeerURLsMapAndToken(cfg)
  232. if err != nil {
  233. return fmt.Errorf("error setting up initial cluster: %v", err)
  234. }
  235. pt, err := transport.NewTimeoutTransport(cfg.peerTLSInfo, time.Duration(cfg.proxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyWriteTimeoutMs)*time.Millisecond)
  236. if err != nil {
  237. return err
  238. }
  239. pt.MaxIdleConnsPerHost = proxy.DefaultMaxIdleConnsPerHost
  240. tr, err := transport.NewTimeoutTransport(cfg.peerTLSInfo, time.Duration(cfg.proxyDialTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyReadTimeoutMs)*time.Millisecond, time.Duration(cfg.proxyWriteTimeoutMs)*time.Millisecond)
  241. if err != nil {
  242. return err
  243. }
  244. cfg.dir = path.Join(cfg.dir, "proxy")
  245. err = os.MkdirAll(cfg.dir, 0700)
  246. if err != nil {
  247. return err
  248. }
  249. var peerURLs []string
  250. clusterfile := path.Join(cfg.dir, "cluster")
  251. b, err := ioutil.ReadFile(clusterfile)
  252. switch {
  253. case err == nil:
  254. if cfg.durl != "" {
  255. plog.Warningf("discovery token ignored since the proxy has already been initialized. Valid cluster file found at ./%s", clusterfile)
  256. }
  257. urls := struct{ PeerURLs []string }{}
  258. err := json.Unmarshal(b, &urls)
  259. if err != nil {
  260. return err
  261. }
  262. peerURLs = urls.PeerURLs
  263. plog.Infof("proxy: using peer urls %v from cluster file ./%s", peerURLs, clusterfile)
  264. case os.IsNotExist(err):
  265. if cfg.durl != "" {
  266. s, err := discovery.GetCluster(cfg.durl, cfg.dproxy)
  267. if err != nil {
  268. return err
  269. }
  270. if urlsmap, err = types.NewURLsMap(s); err != nil {
  271. return err
  272. }
  273. }
  274. peerURLs = urlsmap.URLs()
  275. plog.Infof("proxy: using peer urls %v ", peerURLs)
  276. default:
  277. return err
  278. }
  279. clientURLs := []string{}
  280. uf := func() []string {
  281. gcls, err := etcdserver.GetClusterFromRemotePeers(peerURLs, tr)
  282. // TODO: remove the 2nd check when we fix GetClusterFromPeers
  283. // GetClusterFromPeers should not return nil error with an invaild empty cluster
  284. if err != nil {
  285. plog.Warningf("proxy: %v", err)
  286. return []string{}
  287. }
  288. if len(gcls.Members()) == 0 {
  289. return clientURLs
  290. }
  291. clientURLs = gcls.ClientURLs()
  292. urls := struct{ PeerURLs []string }{gcls.PeerURLs()}
  293. b, err := json.Marshal(urls)
  294. if err != nil {
  295. plog.Warningf("proxy: error on marshal peer urls %s", err)
  296. return clientURLs
  297. }
  298. err = ioutil.WriteFile(clusterfile+".bak", b, 0600)
  299. if err != nil {
  300. plog.Warningf("proxy: error on writing urls %s", err)
  301. return clientURLs
  302. }
  303. err = os.Rename(clusterfile+".bak", clusterfile)
  304. if err != nil {
  305. plog.Warningf("proxy: error on updating clusterfile %s", err)
  306. return clientURLs
  307. }
  308. if !reflect.DeepEqual(gcls.PeerURLs(), peerURLs) {
  309. plog.Noticef("proxy: updated peer urls in cluster file from %v to %v", peerURLs, gcls.PeerURLs())
  310. }
  311. peerURLs = gcls.PeerURLs()
  312. return clientURLs
  313. }
  314. ph := proxy.NewHandler(pt, uf, time.Duration(cfg.proxyFailureWaitMs)*time.Millisecond, time.Duration(cfg.proxyRefreshIntervalMs)*time.Millisecond)
  315. ph = &cors.CORSHandler{
  316. Handler: ph,
  317. Info: cfg.corsInfo,
  318. }
  319. if cfg.isReadonlyProxy() {
  320. ph = proxy.NewReadonlyHandler(ph)
  321. }
  322. // Start a proxy server goroutine for each listen address
  323. for _, u := range cfg.lcurls {
  324. l, err := transport.NewListener(u.Host, u.Scheme, cfg.clientTLSInfo)
  325. if err != nil {
  326. return err
  327. }
  328. host := u.Host
  329. go func() {
  330. plog.Info("proxy: listening for client requests on ", host)
  331. mux := http.NewServeMux()
  332. mux.Handle("/metrics", prometheus.Handler())
  333. mux.Handle("/", ph)
  334. plog.Fatal(http.Serve(l, mux))
  335. }()
  336. }
  337. return nil
  338. }
  339. // getPeerURLsMapAndToken sets up an initial peer URLsMap and cluster token for bootstrap or discovery.
  340. func getPeerURLsMapAndToken(cfg *config) (urlsmap types.URLsMap, token string, err error) {
  341. switch {
  342. case cfg.durl != "":
  343. urlsmap = types.URLsMap{}
  344. // If using discovery, generate a temporary cluster based on
  345. // self's advertised peer URLs
  346. urlsmap[cfg.name] = cfg.apurls
  347. token = cfg.durl
  348. case cfg.dnsCluster != "":
  349. var clusterStr string
  350. clusterStr, token, err = discovery.SRVGetCluster(cfg.name, cfg.dnsCluster, cfg.initialClusterToken, cfg.apurls)
  351. if err != nil {
  352. return nil, "", err
  353. }
  354. urlsmap, err = types.NewURLsMap(clusterStr)
  355. default:
  356. // We're statically configured, and cluster has appropriately been set.
  357. urlsmap, err = types.NewURLsMap(cfg.initialCluster)
  358. token = cfg.initialClusterToken
  359. }
  360. return urlsmap, token, err
  361. }
  362. // identifyDataDirOrDie returns the type of the data dir.
  363. // Dies if the datadir is invalid.
  364. func identifyDataDirOrDie(dir string) dirType {
  365. names, err := fileutil.ReadDir(dir)
  366. if err != nil {
  367. if os.IsNotExist(err) {
  368. return dirEmpty
  369. }
  370. plog.Fatalf("error listing data dir: %s", dir)
  371. }
  372. var m, p bool
  373. for _, name := range names {
  374. switch dirType(name) {
  375. case dirMember:
  376. m = true
  377. case dirProxy:
  378. p = true
  379. default:
  380. plog.Warningf("found invalid file/dir %s under data dir %s (Ignore this if you are upgrading etcd)", name, dir)
  381. }
  382. }
  383. if m && p {
  384. plog.Fatal("invalid datadir. Both member and proxy directories exist.")
  385. }
  386. if m {
  387. return dirMember
  388. }
  389. if p {
  390. return dirProxy
  391. }
  392. return dirEmpty
  393. }
  394. func setupLogging(cfg *config) {
  395. capnslog.SetGlobalLogLevel(capnslog.INFO)
  396. if cfg.debug {
  397. capnslog.SetGlobalLogLevel(capnslog.DEBUG)
  398. }
  399. if cfg.logPkgLevels != "" {
  400. repoLog := capnslog.MustRepoLogger("github.com/coreos/etcd")
  401. settings, err := repoLog.ParseLogLevelConfig(cfg.logPkgLevels)
  402. if err != nil {
  403. plog.Warningf("couldn't parse log level string: %s, continuing with default levels", err.Error())
  404. return
  405. }
  406. repoLog.SetLogLevel(settings)
  407. }
  408. }