etcd.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. package main
  2. import (
  3. "bytes"
  4. "crypto/tls"
  5. "crypto/x509"
  6. "encoding/json"
  7. "encoding/pem"
  8. "flag"
  9. "fmt"
  10. "github.com/coreos/etcd/store"
  11. "github.com/coreos/etcd/web"
  12. "github.com/coreos/go-raft"
  13. "io/ioutil"
  14. "net"
  15. "net/http"
  16. "os"
  17. "os/signal"
  18. "runtime/pprof"
  19. "strings"
  20. "time"
  21. )
  22. //------------------------------------------------------------------------------
  23. //
  24. // Initialization
  25. //
  26. //------------------------------------------------------------------------------
  27. var verbose bool
  28. var veryVerbose bool
  29. var machines string
  30. var machinesFile string
  31. var cluster []string
  32. var hostname string
  33. var clientPort int
  34. var raftPort int
  35. var webPort int
  36. var serverCertFile string
  37. var serverKeyFile string
  38. var serverCAFile string
  39. var clientCertFile string
  40. var clientKeyFile string
  41. var clientCAFile string
  42. var dirPath string
  43. var ignore bool
  44. var maxSize int
  45. var snapshot bool
  46. var retryTimes int
  47. var maxClusterSize int
  48. var cpuprofile string
  49. func init() {
  50. flag.BoolVar(&verbose, "v", false, "verbose logging")
  51. flag.BoolVar(&veryVerbose, "vv", false, "very verbose logging")
  52. flag.StringVar(&machines, "C", "", "the ip address and port of a existing machines in the cluster, sepearate by comma")
  53. flag.StringVar(&machinesFile, "CF", "", "the file contains a list of existing machines in the cluster, seperate by comma")
  54. flag.StringVar(&hostname, "h", "0.0.0.0", "the hostname of the local machine")
  55. flag.IntVar(&clientPort, "c", 4001, "the port to communicate with clients")
  56. flag.IntVar(&raftPort, "s", 7001, "the port to communicate with servers")
  57. flag.IntVar(&webPort, "w", -1, "the port of web interface (-1 means do not start web inteface)")
  58. flag.StringVar(&serverCAFile, "serverCAFile", "", "the path of the CAFile")
  59. flag.StringVar(&serverCertFile, "serverCert", "", "the cert file of the server")
  60. flag.StringVar(&serverKeyFile, "serverKey", "", "the key file of the server")
  61. flag.StringVar(&clientCAFile, "clientCAFile", "", "the path of the client CAFile")
  62. flag.StringVar(&clientCertFile, "clientCert", "", "the cert file of the client")
  63. flag.StringVar(&clientKeyFile, "clientKey", "", "the key file of the client")
  64. flag.StringVar(&dirPath, "d", "/tmp/", "the directory to store log and snapshot")
  65. flag.BoolVar(&ignore, "i", false, "ignore the old configuration, create a new node")
  66. flag.BoolVar(&snapshot, "snapshot", false, "open or close snapshot")
  67. flag.IntVar(&maxSize, "m", 1024, "the max size of result buffer")
  68. flag.IntVar(&retryTimes, "r", 3, "the max retry attempts when trying to join a cluster")
  69. flag.IntVar(&maxClusterSize, "maxsize", 9, "the max size of the cluster")
  70. flag.StringVar(&cpuprofile, "cpuprofile", "", "write cpu profile to file")
  71. }
  72. // CONSTANTS
  73. const (
  74. HTTP = iota
  75. HTTPS
  76. HTTPSANDVERIFY
  77. )
  78. const (
  79. SERVER = iota
  80. CLIENT
  81. )
  82. const (
  83. ELECTIONTIMEOUT = 200 * time.Millisecond
  84. HEARTBEATTIMEOUT = 50 * time.Millisecond
  85. // Timeout for internal raft http connection
  86. // The original timeout for http is 45 seconds
  87. // which is too long for our usage.
  88. HTTPTIMEOUT = 10 * time.Second
  89. RETRYINTERVAL = 10
  90. )
  91. //------------------------------------------------------------------------------
  92. //
  93. // Typedefs
  94. //
  95. //------------------------------------------------------------------------------
  96. type Info struct {
  97. Hostname string `json:"hostname"`
  98. RaftPort int `json:"raftPort"`
  99. ClientPort int `json:"clientPort"`
  100. WebPort int `json:"webPort"`
  101. ServerCertFile string `json:"serverCertFile"`
  102. ServerKeyFile string `json:"serverKeyFile"`
  103. ServerCAFile string `json:"serverCAFile"`
  104. ClientCertFile string `json:"clientCertFile"`
  105. ClientKeyFile string `json:"clientKeyFile"`
  106. ClientCAFile string `json:"clientCAFile"`
  107. }
  108. //------------------------------------------------------------------------------
  109. //
  110. // Variables
  111. //
  112. //------------------------------------------------------------------------------
  113. var raftServer *raft.Server
  114. var raftTransporter transporter
  115. var etcdStore *store.Store
  116. var info *Info
  117. //------------------------------------------------------------------------------
  118. //
  119. // Functions
  120. //
  121. //------------------------------------------------------------------------------
  122. //--------------------------------------
  123. // Main
  124. //--------------------------------------
  125. func main() {
  126. flag.Parse()
  127. if cpuprofile != "" {
  128. f, err := os.Create(cpuprofile)
  129. if err != nil {
  130. fatal(err)
  131. }
  132. pprof.StartCPUProfile(f)
  133. defer pprof.StopCPUProfile()
  134. c := make(chan os.Signal, 1)
  135. signal.Notify(c, os.Interrupt)
  136. go func() {
  137. for sig := range c {
  138. fmt.Printf("captured %v, stopping profiler and exiting..", sig)
  139. pprof.StopCPUProfile()
  140. os.Exit(1)
  141. }
  142. }()
  143. }
  144. if veryVerbose {
  145. verbose = true
  146. raft.SetLogLevel(raft.Debug)
  147. }
  148. if machines != "" {
  149. cluster = strings.Split(machines, ",")
  150. } else if machinesFile != "" {
  151. b, err := ioutil.ReadFile(machinesFile)
  152. if err != nil {
  153. fatalf("Unable to read the given machines file: %s", err)
  154. }
  155. cluster = strings.Split(string(b), ",")
  156. }
  157. // Setup commands.
  158. registerCommands()
  159. // Read server info from file or grab it from user.
  160. if err := os.MkdirAll(dirPath, 0744); err != nil {
  161. fatalf("Unable to create path: %s", err)
  162. }
  163. info = getInfo(dirPath)
  164. // security type
  165. st := securityType(SERVER)
  166. clientSt := securityType(CLIENT)
  167. if st == -1 || clientSt == -1 {
  168. fatal("Please specify cert and key file or cert and key file and CAFile or none of the three")
  169. }
  170. // Create etcd key-value store
  171. etcdStore = store.CreateStore(maxSize)
  172. startRaft(st)
  173. if webPort != -1 {
  174. // start web
  175. etcdStore.SetMessager(&storeMsg)
  176. go webHelper()
  177. go web.Start(raftServer, webPort)
  178. }
  179. startClientTransport(info.ClientPort, clientSt)
  180. }
  181. // Start the raft server
  182. func startRaft(securityType int) {
  183. var err error
  184. raftName := fmt.Sprintf("%s:%d", info.Hostname, info.RaftPort)
  185. // Create transporter for raft
  186. raftTransporter = createTransporter(securityType)
  187. // Create raft server
  188. raftServer, err = raft.NewServer(raftName, dirPath, raftTransporter, etcdStore, nil)
  189. if err != nil {
  190. fatal(err)
  191. }
  192. // LoadSnapshot
  193. if snapshot {
  194. err = raftServer.LoadSnapshot()
  195. if err == nil {
  196. debugf("%s finished load snapshot", raftServer.Name())
  197. } else {
  198. debug(err)
  199. }
  200. }
  201. raftServer.SetElectionTimeout(ELECTIONTIMEOUT)
  202. raftServer.SetHeartbeatTimeout(HEARTBEATTIMEOUT)
  203. raftServer.Start()
  204. // start to response to raft requests
  205. go startRaftTransport(info.RaftPort, securityType)
  206. if raftServer.IsLogEmpty() {
  207. // start as a leader in a new cluster
  208. if len(cluster) == 0 {
  209. time.Sleep(time.Millisecond * 20)
  210. // leader need to join self as a peer
  211. for {
  212. command := &JoinCommand{
  213. Name : raftServer.Name(),
  214. Hostname : hostname,
  215. RaftPort : raftPort,
  216. ClientPort : clientPort,
  217. }
  218. _, err := raftServer.Do(command)
  219. if err == nil {
  220. break
  221. }
  222. }
  223. debugf("%s start as a leader", raftServer.Name())
  224. // start as a follower in a existing cluster
  225. } else {
  226. time.Sleep(time.Millisecond * 20)
  227. for i := 0; i < retryTimes; i++ {
  228. success := false
  229. for _, machine := range cluster {
  230. if len(machine) == 0 {
  231. continue
  232. }
  233. err = joinCluster(raftServer, machine)
  234. if err != nil {
  235. if err.Error() == errors[103] {
  236. fmt.Println(err)
  237. os.Exit(1)
  238. }
  239. debugf("cannot join to cluster via machine %s %s", machine, err)
  240. } else {
  241. success = true
  242. break
  243. }
  244. }
  245. if success {
  246. break
  247. }
  248. warnf("cannot join to cluster via given machines, retry in %d seconds", RETRYINTERVAL)
  249. time.Sleep(time.Second * RETRYINTERVAL)
  250. }
  251. if err != nil {
  252. fatalf("Cannot join the cluster via given machines after %x retries", retryTimes)
  253. }
  254. debugf("%s success join to the cluster", raftServer.Name())
  255. }
  256. } else {
  257. // rejoin the previous cluster
  258. debugf("%s restart as a follower", raftServer.Name())
  259. }
  260. // open the snapshot
  261. if snapshot {
  262. go raftServer.Snapshot()
  263. }
  264. }
  265. // Create transporter using by raft server
  266. // Create http or https transporter based on
  267. // whether the user give the server cert and key
  268. func createTransporter(st int) transporter {
  269. t := transporter{}
  270. switch st {
  271. case HTTP:
  272. t.scheme = "http://"
  273. tr := &http.Transport{
  274. Dial: dialTimeout,
  275. }
  276. t.client = &http.Client{
  277. Transport: tr,
  278. }
  279. case HTTPS:
  280. fallthrough
  281. case HTTPSANDVERIFY:
  282. t.scheme = "https://"
  283. tlsCert, err := tls.LoadX509KeyPair(serverCertFile, serverKeyFile)
  284. if err != nil {
  285. fatal(err)
  286. }
  287. tr := &http.Transport{
  288. TLSClientConfig: &tls.Config{
  289. Certificates: []tls.Certificate{tlsCert},
  290. InsecureSkipVerify: true,
  291. },
  292. Dial: dialTimeout,
  293. DisableCompression: true,
  294. }
  295. t.client = &http.Client{Transport: tr}
  296. }
  297. return t
  298. }
  299. // Dial with timeout
  300. func dialTimeout(network, addr string) (net.Conn, error) {
  301. return net.DialTimeout(network, addr, HTTPTIMEOUT)
  302. }
  303. // Start to listen and response raft command
  304. func startRaftTransport(port int, st int) {
  305. // internal commands
  306. http.HandleFunc("/join", JoinHttpHandler)
  307. http.HandleFunc("/vote", VoteHttpHandler)
  308. http.HandleFunc("/log", GetLogHttpHandler)
  309. http.HandleFunc("/log/append", AppendEntriesHttpHandler)
  310. http.HandleFunc("/snapshot", SnapshotHttpHandler)
  311. http.HandleFunc("/snapshotRecovery", SnapshotRecoveryHttpHandler)
  312. http.HandleFunc("/client", ClientHttpHandler)
  313. switch st {
  314. case HTTP:
  315. fmt.Printf("raft server [%s] listen on http port %v\n", hostname, port)
  316. fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
  317. case HTTPS:
  318. fmt.Printf("raft server [%s] listen on https port %v\n", hostname, port)
  319. fatal(http.ListenAndServeTLS(fmt.Sprintf(":%d", port), serverCertFile, serverKeyFile, nil))
  320. case HTTPSANDVERIFY:
  321. server := &http.Server{
  322. TLSConfig: &tls.Config{
  323. ClientAuth: tls.RequireAndVerifyClientCert,
  324. ClientCAs: createCertPool(serverCAFile),
  325. },
  326. Addr: fmt.Sprintf(":%d", port),
  327. }
  328. fmt.Printf("raft server [%s] listen on https port %v\n", hostname, port)
  329. fatal(server.ListenAndServeTLS(serverCertFile, serverKeyFile))
  330. }
  331. }
  332. // Start to listen and response client command
  333. func startClientTransport(port int, st int) {
  334. // external commands
  335. http.HandleFunc("/"+version+"/keys/", Multiplexer)
  336. http.HandleFunc("/"+version+"/watch/", WatchHttpHandler)
  337. http.HandleFunc("/leader", LeaderHttpHandler)
  338. http.HandleFunc("/machines", MachinesHttpHandler)
  339. http.HandleFunc("/", VersionHttpHandler)
  340. http.HandleFunc("/stats", StatsHttpHandler)
  341. switch st {
  342. case HTTP:
  343. fmt.Printf("etcd [%s] listen on http port %v\n", hostname, clientPort)
  344. fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
  345. case HTTPS:
  346. fmt.Printf("etcd [%s] listen on https port %v\n", hostname, clientPort)
  347. http.ListenAndServeTLS(fmt.Sprintf(":%d", port), clientCertFile, clientKeyFile, nil)
  348. case HTTPSANDVERIFY:
  349. server := &http.Server{
  350. TLSConfig: &tls.Config{
  351. ClientAuth: tls.RequireAndVerifyClientCert,
  352. ClientCAs: createCertPool(clientCAFile),
  353. },
  354. Addr: fmt.Sprintf(":%d", port),
  355. }
  356. fmt.Printf("etcd [%s] listen on https port %v\n", hostname, clientPort)
  357. fatal(server.ListenAndServeTLS(clientCertFile, clientKeyFile))
  358. }
  359. }
  360. //--------------------------------------
  361. // Config
  362. //--------------------------------------
  363. // Get the security type
  364. func securityType(source int) int {
  365. var keyFile, certFile, CAFile string
  366. switch source {
  367. case SERVER:
  368. keyFile = info.ServerKeyFile
  369. certFile = info.ServerCertFile
  370. CAFile = info.ServerCAFile
  371. case CLIENT:
  372. keyFile = info.ClientKeyFile
  373. certFile = info.ClientCertFile
  374. CAFile = info.ClientCAFile
  375. }
  376. // If the user do not specify key file, cert file and
  377. // CA file, the type will be HTTP
  378. if keyFile == "" && certFile == "" && CAFile == "" {
  379. return HTTP
  380. }
  381. if keyFile != "" && certFile != "" {
  382. if CAFile != "" {
  383. // If the user specify all the three file, the type
  384. // will be HTTPS with client cert auth
  385. return HTTPSANDVERIFY
  386. }
  387. // If the user specify key file and cert file but not
  388. // CA file, the type will be HTTPS without client cert
  389. // auth
  390. return HTTPS
  391. }
  392. // bad specification
  393. return -1
  394. }
  395. // Get the server info from previous conf file
  396. // or from the user
  397. func getInfo(path string) *Info {
  398. info := &Info{}
  399. // Read in the server info if available.
  400. infoPath := fmt.Sprintf("%s/info", path)
  401. // Delete the old configuration if exist
  402. if ignore {
  403. logPath := fmt.Sprintf("%s/log", path)
  404. confPath := fmt.Sprintf("%s/conf", path)
  405. snapshotPath := fmt.Sprintf("%s/snapshot", path)
  406. os.Remove(infoPath)
  407. os.Remove(logPath)
  408. os.Remove(confPath)
  409. os.RemoveAll(snapshotPath)
  410. }
  411. if file, err := os.Open(infoPath); err == nil {
  412. if content, err := ioutil.ReadAll(file); err != nil {
  413. fatalf("Unable to read info: %v", err)
  414. } else {
  415. if err = json.Unmarshal(content, &info); err != nil {
  416. fatalf("Unable to parse info: %v", err)
  417. }
  418. }
  419. file.Close()
  420. } else {
  421. // Otherwise ask user for info and write it to file.
  422. if hostname == "" {
  423. fatal("Please give the address of the local machine")
  424. }
  425. info.Hostname = hostname
  426. info.Hostname = strings.TrimSpace(info.Hostname)
  427. fmt.Println("address ", info.Hostname)
  428. info.RaftPort = raftPort
  429. info.ClientPort = clientPort
  430. info.WebPort = webPort
  431. info.ClientCAFile = clientCAFile
  432. info.ClientCertFile = clientCertFile
  433. info.ClientKeyFile = clientKeyFile
  434. info.ServerCAFile = serverCAFile
  435. info.ServerKeyFile = serverKeyFile
  436. info.ServerCertFile = serverCertFile
  437. // Write to file.
  438. content, _ := json.Marshal(info)
  439. content = []byte(string(content) + "\n")
  440. if err := ioutil.WriteFile(infoPath, content, 0644); err != nil {
  441. fatalf("Unable to write info to file: %v", err)
  442. }
  443. }
  444. return info
  445. }
  446. // Create client auth certpool
  447. func createCertPool(CAFile string) *x509.CertPool {
  448. pemByte, _ := ioutil.ReadFile(CAFile)
  449. block, pemByte := pem.Decode(pemByte)
  450. cert, err := x509.ParseCertificate(block.Bytes)
  451. if err != nil {
  452. fatal(err)
  453. }
  454. certPool := x509.NewCertPool()
  455. certPool.AddCert(cert)
  456. return certPool
  457. }
  458. // Send join requests to the leader.
  459. func joinCluster(s *raft.Server, serverName string) error {
  460. var b bytes.Buffer
  461. command := &JoinCommand{}
  462. command.Name = s.Name()
  463. command.Hostname = info.Hostname
  464. command.RaftPort = info.RaftPort
  465. command.ClientPort = info.ClientPort
  466. json.NewEncoder(&b).Encode(command)
  467. // t must be ok
  468. t, ok := raftServer.Transporter().(transporter)
  469. if !ok {
  470. panic("wrong type")
  471. }
  472. debugf("Send Join Request to %s", serverName)
  473. resp, err := t.Post(fmt.Sprintf("%s/join", serverName), &b)
  474. for {
  475. if err != nil {
  476. return fmt.Errorf("Unable to join: %v", err)
  477. }
  478. if resp != nil {
  479. defer resp.Body.Close()
  480. if resp.StatusCode == http.StatusOK {
  481. return nil
  482. }
  483. if resp.StatusCode == http.StatusTemporaryRedirect {
  484. address := resp.Header.Get("Location")
  485. debugf("Leader is %s", address)
  486. debugf("Send Join Request to %s", address)
  487. json.NewEncoder(&b).Encode(command)
  488. resp, err = t.Post(fmt.Sprintf("%s/join", address), &b)
  489. } else if resp.StatusCode == http.StatusBadRequest {
  490. debug("Reach max number machines in the cluster")
  491. return fmt.Errorf(errors[103])
  492. } else {
  493. return fmt.Errorf("Unable to join")
  494. }
  495. }
  496. }
  497. return fmt.Errorf("Unable to join: %v", err)
  498. }
  499. // Register commands to raft server
  500. func registerCommands() {
  501. raft.RegisterCommand(&JoinCommand{})
  502. raft.RegisterCommand(&SetCommand{})
  503. raft.RegisterCommand(&GetCommand{})
  504. raft.RegisterCommand(&DeleteCommand{})
  505. raft.RegisterCommand(&WatchCommand{})
  506. raft.RegisterCommand(&TestAndSetCommand{})
  507. }