etcd.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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. case HTTPS:
  228. fallthrough
  229. case HTTPSANDVERIFY:
  230. t.scheme = "https://"
  231. tlsCert, err := tls.LoadX509KeyPair(serverCertFile, serverKeyFile)
  232. if err != nil {
  233. fatal(fmt.Sprintln(err))
  234. }
  235. tr := &http.Transport{
  236. TLSClientConfig: &tls.Config{
  237. Certificates: []tls.Certificate{tlsCert},
  238. InsecureSkipVerify: true,
  239. },
  240. Dial: dialTimeout,
  241. DisableCompression: true,
  242. }
  243. t.client = &http.Client{Transport: tr}
  244. }
  245. return t
  246. }
  247. // Dial with timeout
  248. func dialTimeout(network, addr string) (net.Conn, error) {
  249. return net.DialTimeout(network, addr, HTTPTIMEOUT)
  250. }
  251. // Start to listen and response raft command
  252. func startRaftTransport(port int, st int) {
  253. // internal commands
  254. http.HandleFunc("/join", JoinHttpHandler)
  255. http.HandleFunc("/vote", VoteHttpHandler)
  256. http.HandleFunc("/log", GetLogHttpHandler)
  257. http.HandleFunc("/log/append", AppendEntriesHttpHandler)
  258. http.HandleFunc("/snapshot", SnapshotHttpHandler)
  259. http.HandleFunc("/client", ClientHttpHandler)
  260. switch st {
  261. case HTTP:
  262. fmt.Printf("raft server [%s] listen on http port %v\n", hostname, port)
  263. log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
  264. case HTTPS:
  265. fmt.Printf("raft server [%s] listen on https port %v\n", hostname, port)
  266. log.Fatal(http.ListenAndServeTLS(fmt.Sprintf(":%d", port), serverCertFile, serverKeyFile, nil))
  267. case HTTPSANDVERIFY:
  268. server := &http.Server{
  269. TLSConfig: &tls.Config{
  270. ClientAuth: tls.RequireAndVerifyClientCert,
  271. ClientCAs: createCertPool(serverCAFile),
  272. },
  273. Addr: fmt.Sprintf(":%d", port),
  274. }
  275. fmt.Printf("raft server [%s] listen on https port %v\n", hostname, port)
  276. err := server.ListenAndServeTLS(serverCertFile, serverKeyFile)
  277. if err != nil {
  278. log.Fatal(err)
  279. }
  280. }
  281. }
  282. // Start to listen and response client command
  283. func startClientTransport(port int, st int) {
  284. // external commands
  285. http.HandleFunc("/"+version+"/keys/", Multiplexer)
  286. http.HandleFunc("/"+version+"/watch/", WatchHttpHandler)
  287. http.HandleFunc("/leader", LeaderHttpHandler)
  288. http.HandleFunc("/machines", MachinesHttpHandler)
  289. switch st {
  290. case HTTP:
  291. fmt.Printf("etcd [%s] listen on http port %v\n", hostname, clientPort)
  292. log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
  293. case HTTPS:
  294. fmt.Printf("etcd [%s] listen on https port %v\n", hostname, clientPort)
  295. http.ListenAndServeTLS(fmt.Sprintf(":%d", port), clientCertFile, clientKeyFile, nil)
  296. case HTTPSANDVERIFY:
  297. server := &http.Server{
  298. TLSConfig: &tls.Config{
  299. ClientAuth: tls.RequireAndVerifyClientCert,
  300. ClientCAs: createCertPool(clientCAFile),
  301. },
  302. Addr: fmt.Sprintf(":%d", port),
  303. }
  304. fmt.Printf("etcd [%s] listen on https port %v\n", hostname, clientPort)
  305. err := server.ListenAndServeTLS(clientCertFile, clientKeyFile)
  306. if err != nil {
  307. fatal(fmt.Sprintln(err))
  308. }
  309. }
  310. }
  311. //--------------------------------------
  312. // Config
  313. //--------------------------------------
  314. // Get the security type
  315. func securityType(source int) int {
  316. var keyFile, certFile, CAFile string
  317. switch source {
  318. case SERVER:
  319. keyFile = info.ServerKeyFile
  320. certFile = info.ServerCertFile
  321. CAFile = info.ServerCAFile
  322. case CLIENT:
  323. keyFile = info.ClientKeyFile
  324. certFile = info.ClientCertFile
  325. CAFile = info.ClientCAFile
  326. }
  327. // If the user do not specify key file, cert file and
  328. // CA file, the type will be HTTP
  329. if keyFile == "" && certFile == "" && CAFile == "" {
  330. return HTTP
  331. }
  332. if keyFile != "" && certFile != "" {
  333. if CAFile != "" {
  334. // If the user specify all the three file, the type
  335. // will be HTTPS with client cert auth
  336. return HTTPSANDVERIFY
  337. }
  338. // If the user specify key file and cert file but not
  339. // CA file, the type will be HTTPS without client cert
  340. // auth
  341. return HTTPS
  342. }
  343. // bad specification
  344. return -1
  345. }
  346. // Get the server info from previous conf file
  347. // or from the user
  348. func getInfo(path string) *Info {
  349. info := &Info{}
  350. // Read in the server info if available.
  351. infoPath := fmt.Sprintf("%s/info", path)
  352. // Delete the old configuration if exist
  353. if ignore {
  354. logPath := fmt.Sprintf("%s/log", path)
  355. snapshotPath := fmt.Sprintf("%s/snapshotPath", path)
  356. os.Remove(infoPath)
  357. os.Remove(logPath)
  358. os.RemoveAll(snapshotPath)
  359. }
  360. if file, err := os.Open(infoPath); err == nil {
  361. if content, err := ioutil.ReadAll(file); err != nil {
  362. fatal("Unable to read info: %v", err)
  363. } else {
  364. if err = json.Unmarshal(content, &info); err != nil {
  365. fatal("Unable to parse info: %v", err)
  366. }
  367. }
  368. file.Close()
  369. } else {
  370. // Otherwise ask user for info and write it to file.
  371. if hostname == "" {
  372. fatal("Please give the address of the local machine")
  373. }
  374. info.Hostname = hostname
  375. info.Hostname = strings.TrimSpace(info.Hostname)
  376. fmt.Println("address ", info.Hostname)
  377. info.RaftPort = raftPort
  378. info.ClientPort = clientPort
  379. info.WebPort = webPort
  380. info.ClientCAFile = clientCAFile
  381. info.ClientCertFile = clientCertFile
  382. info.ClientKeyFile = clientKeyFile
  383. info.ServerCAFile = serverCAFile
  384. info.ServerKeyFile = serverKeyFile
  385. info.ServerCertFile = serverCertFile
  386. // Write to file.
  387. content, _ := json.Marshal(info)
  388. content = []byte(string(content) + "\n")
  389. if err := ioutil.WriteFile(infoPath, content, 0644); err != nil {
  390. fatal("Unable to write info to file: %v", err)
  391. }
  392. }
  393. return info
  394. }
  395. // Create client auth certpool
  396. func createCertPool(CAFile string) *x509.CertPool {
  397. pemByte, _ := ioutil.ReadFile(CAFile)
  398. block, pemByte := pem.Decode(pemByte)
  399. cert, err := x509.ParseCertificate(block.Bytes)
  400. if err != nil {
  401. fatal(fmt.Sprintln(err))
  402. }
  403. certPool := x509.NewCertPool()
  404. certPool.AddCert(cert)
  405. return certPool
  406. }
  407. // Send join requests to the leader.
  408. func joinCluster(s *raft.Server, serverName string) error {
  409. var b bytes.Buffer
  410. command := &JoinCommand{}
  411. command.Name = s.Name()
  412. command.Hostname = info.Hostname
  413. command.RaftPort = info.RaftPort
  414. command.ClientPort = info.ClientPort
  415. json.NewEncoder(&b).Encode(command)
  416. // t must be ok
  417. t, ok := raftServer.Transporter().(transporter)
  418. if !ok {
  419. panic("wrong type")
  420. }
  421. debug("Send Join Request to %s", serverName)
  422. resp, err := t.Post(fmt.Sprintf("%s/join", serverName), &b)
  423. for {
  424. if err != nil {
  425. return fmt.Errorf("Unable to join: %v", err)
  426. }
  427. if resp != nil {
  428. defer resp.Body.Close()
  429. if resp.StatusCode == http.StatusOK {
  430. return nil
  431. }
  432. if resp.StatusCode == http.StatusTemporaryRedirect {
  433. address := resp.Header.Get("Location")
  434. debug("Leader is %s", address)
  435. debug("Send Join Request to %s", address)
  436. json.NewEncoder(&b).Encode(command)
  437. resp, err = t.Post(fmt.Sprintf("%s/join", address), &b)
  438. } else {
  439. return fmt.Errorf("Unable to join")
  440. }
  441. }
  442. }
  443. return fmt.Errorf("Unable to join: %v", err)
  444. }
  445. // Register commands to raft server
  446. func registerCommands() {
  447. raft.RegisterCommand(&JoinCommand{})
  448. raft.RegisterCommand(&SetCommand{})
  449. raft.RegisterCommand(&GetCommand{})
  450. raft.RegisterCommand(&DeleteCommand{})
  451. raft.RegisterCommand(&WatchCommand{})
  452. raft.RegisterCommand(&TestAndSetCommand{})
  453. }