etcd.go 13 KB

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