etcd.go 13 KB

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