etcd.go 14 KB

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