etcd/etcd.go

442 lines
9.2 KiB
Go
Raw Normal View History

package main
import (
"bytes"
2013-06-21 02:59:23 +04:00
"crypto/tls"
"crypto/x509"
"encoding/json"
2013-06-20 08:03:28 +04:00
"encoding/pem"
"flag"
"fmt"
"github.com/xiangli-cmu/go-raft"
2013-06-21 02:59:23 +04:00
"github.com/xiangli-cmu/raft-etcd/store"
"github.com/xiangli-cmu/raft-etcd/web"
2013-06-29 01:17:16 +04:00
//"io"
"io/ioutil"
2013-06-21 02:59:23 +04:00
"log"
"net/http"
"os"
2013-06-29 01:17:16 +04:00
//"strconv"
2013-06-21 02:59:23 +04:00
"strings"
"time"
)
//------------------------------------------------------------------------------
//
// Initialization
//
//------------------------------------------------------------------------------
var verbose bool
2013-06-29 01:17:16 +04:00
var cluster string
2013-06-13 22:01:06 +04:00
var address string
2013-06-29 01:17:16 +04:00
var clientPort int
var serverPort int
2013-06-18 22:13:24 +04:00
var webPort int
2013-06-29 01:17:16 +04:00
2013-06-20 08:03:28 +04:00
var certFile string
var keyFile string
2013-06-19 02:04:30 +04:00
var CAFile string
2013-06-29 01:17:16 +04:00
var dirPath string
func init() {
flag.BoolVar(&verbose, "v", false, "verbose logging")
2013-06-29 01:17:16 +04:00
flag.StringVar(&cluster, "C", "", "join to a existing cluster")
flag.StringVar(&address, "a", "", "the ip address of the machine")
flag.IntVar(&clientPort, "c", 4001, "the port of client")
flag.IntVar(&serverPort, "s", 7001, "the port of server")
2013-06-18 22:13:24 +04:00
flag.IntVar(&webPort, "w", -1, "the port of web interface")
2013-06-29 01:17:16 +04:00
2013-06-20 08:03:28 +04:00
flag.StringVar(&CAFile, "CAFile", "", "the path of the CAFile")
flag.StringVar(&certFile, "cert", "", "the cert file of the server")
flag.StringVar(&keyFile, "key", "", "the key file of the server")
2013-06-29 01:17:16 +04:00
flag.StringVar(&dirPath, "d", "./", "the directory to store log and snapshot")
}
2013-06-21 02:59:23 +04:00
// CONSTANTS
2013-06-21 02:59:23 +04:00
const (
HTTP = iota
HTTPS
HTTPSANDVERIFY
)
2013-06-13 22:01:06 +04:00
const (
ELECTIONTIMTOUT = 200 * time.Millisecond
HEARTBEATTIMEOUT = 50 * time.Millisecond
2013-06-13 22:01:06 +04:00
)
//------------------------------------------------------------------------------
//
// Typedefs
//
//------------------------------------------------------------------------------
type Info struct {
2013-06-29 01:17:16 +04:00
Address string `json:"address"`
ServerPort int `json:"serverPort"`
ClientPort int `json:"clientPort"`
WebPort int `json:"webPort"`
}
//------------------------------------------------------------------------------
//
// Variables
//
//------------------------------------------------------------------------------
var server *raft.Server
var logger *log.Logger
2013-06-19 02:04:30 +04:00
var storeMsg chan string
//------------------------------------------------------------------------------
//
// Functions
//
//------------------------------------------------------------------------------
//--------------------------------------
// Main
//--------------------------------------
func main() {
var err error
logger = log.New(os.Stdout, "", log.LstdFlags)
flag.Parse()
// Setup commands.
raft.RegisterCommand(&JoinCommand{})
raft.RegisterCommand(&SetCommand{})
raft.RegisterCommand(&GetCommand{})
raft.RegisterCommand(&DeleteCommand{})
2013-06-21 02:59:23 +04:00
if err := os.MkdirAll(dirPath, 0744); err != nil {
fatal("Unable to create path: %v", err)
}
// Read server info from file or grab it from user.
var info *Info = getInfo(dirPath)
2013-06-13 22:01:06 +04:00
2013-06-29 01:17:16 +04:00
name := fmt.Sprintf("%s:%d", info.Address, info.ServerPort)
2013-06-13 22:01:06 +04:00
2013-06-29 01:17:16 +04:00
fmt.Printf("ServerName: %s\n\n", name)
2013-06-21 02:59:23 +04:00
2013-06-20 08:03:28 +04:00
// secrity type
st := securityType()
if st == -1 {
panic("ERROR type")
}
2013-06-21 02:59:23 +04:00
t := createTranHandler(st)
// Setup new raft server.
2013-06-18 22:13:24 +04:00
s := store.GetStore()
2013-06-19 02:04:30 +04:00
2013-06-20 08:03:28 +04:00
// create raft server
server, err = raft.NewServer(name, dirPath, t, s, nil)
2013-06-19 02:04:30 +04:00
if err != nil {
fatal("%v", err)
}
2013-06-12 20:46:53 +04:00
server.LoadSnapshot()
2013-06-18 22:13:24 +04:00
debug("%s finished load snapshot", server.Name())
server.Initialize()
2013-06-18 22:13:24 +04:00
debug("%s finished init", server.Name())
2013-06-13 22:01:06 +04:00
server.SetElectionTimeout(ELECTIONTIMTOUT)
server.SetHeartbeatTimeout(HEARTBEATTIMEOUT)
2013-06-18 22:13:24 +04:00
debug("%s finished set timeout", server.Name())
2013-06-13 22:01:06 +04:00
if server.IsLogEmpty() {
2013-06-13 22:01:06 +04:00
// start as a leader in a new cluster
2013-06-29 01:17:16 +04:00
if cluster == "" {
server.StartLeader()
2013-06-13 22:01:06 +04:00
// join self as a peer
2013-06-12 02:29:25 +04:00
command := &JoinCommand{}
command.Name = server.Name()
server.Do(command)
2013-06-18 22:13:24 +04:00
debug("%s start as a leader", server.Name())
2013-06-13 22:01:06 +04:00
2013-06-21 02:59:23 +04:00
// start as a fellower in a existing cluster
} else {
server.StartFollower()
2013-06-12 20:46:53 +04:00
2013-06-29 01:17:16 +04:00
err := Join(server, cluster)
2013-06-20 08:03:28 +04:00
if err != nil {
panic(err)
}
fmt.Println("success join")
}
2013-06-13 22:01:06 +04:00
2013-06-21 02:59:23 +04:00
// rejoin the previous cluster
2013-06-12 02:29:25 +04:00
} else {
server.StartFollower()
2013-06-18 22:13:24 +04:00
debug("%s start as a follower", server.Name())
}
2013-06-13 22:01:06 +04:00
// open the snapshot
2013-06-12 20:46:53 +04:00
go server.Snapshot()
2013-06-21 02:59:23 +04:00
if webPort != -1 {
// start web
s.SetMessager(&storeMsg)
go webHelper()
go web.Start(server, webPort)
}
2013-06-20 08:03:28 +04:00
2013-06-29 01:17:16 +04:00
go startServTransport(info.ServerPort, st)
startClientTransport(info.ClientPort, st)
2013-06-20 08:03:28 +04:00
}
func usage() {
fatal("usage: raftd [PATH]")
}
func createTranHandler(st int) transHandler {
t := transHandler{}
switch st {
case HTTP:
t := transHandler{}
t.client = nil
return t
case HTTPS:
fallthrough
case HTTPSANDVERIFY:
tlsCert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
panic(err)
}
tr := &http.Transport{
2013-06-21 02:59:23 +04:00
TLSClientConfig: &tls.Config{
Certificates: []tls.Certificate{tlsCert},
2013-06-20 08:03:28 +04:00
InsecureSkipVerify: true,
2013-06-21 02:59:23 +04:00
},
DisableCompression: true,
}
2013-06-20 08:03:28 +04:00
t.client = &http.Client{Transport: tr}
return t
}
// for complier
return transHandler{}
}
2013-06-29 01:17:16 +04:00
func startServTransport(port int, st int) {
2013-06-20 08:03:28 +04:00
// internal commands
2013-06-21 02:59:23 +04:00
http.HandleFunc("/join", JoinHttpHandler)
http.HandleFunc("/vote", VoteHttpHandler)
http.HandleFunc("/log", GetLogHttpHandler)
http.HandleFunc("/log/append", AppendEntriesHttpHandler)
http.HandleFunc("/snapshot", SnapshotHttpHandler)
2013-06-29 01:17:16 +04:00
switch st {
case HTTP:
debug("%s listen on http", server.Name())
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
case HTTPS:
http.ListenAndServeTLS(fmt.Sprintf(":%d", port), certFile, keyFile, nil)
case HTTPSANDVERIFY:
pemByte, _ := ioutil.ReadFile(CAFile)
block, pemByte := pem.Decode(pemByte)
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
fmt.Println(err)
}
certPool := x509.NewCertPool()
certPool.AddCert(cert)
server := &http.Server{
TLSConfig: &tls.Config{
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: certPool,
},
Addr: fmt.Sprintf(":%d", port),
}
err = server.ListenAndServeTLS(certFile, keyFile)
if err != nil {
log.Fatal(err)
}
}
}
func startClientTransport(port int, st int) {
2013-06-21 02:59:23 +04:00
// external commands
http.HandleFunc("/set/", SetHttpHandler)
http.HandleFunc("/get/", GetHttpHandler)
http.HandleFunc("/delete/", DeleteHttpHandler)
http.HandleFunc("/watch/", WatchHttpHandler)
http.HandleFunc("/master", MasterHttpHandler)
2013-06-21 02:59:23 +04:00
switch st {
2013-06-18 22:13:24 +04:00
2013-06-21 02:59:23 +04:00
case HTTP:
debug("%s listen on http", server.Name())
2013-06-21 02:59:23 +04:00
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
2013-06-18 22:13:24 +04:00
2013-06-21 02:59:23 +04:00
case HTTPS:
http.ListenAndServeTLS(fmt.Sprintf(":%d", port), certFile, keyFile, nil)
2013-06-20 08:03:28 +04:00
2013-06-21 02:59:23 +04:00
case HTTPSANDVERIFY:
pemByte, _ := ioutil.ReadFile(CAFile)
2013-06-20 08:03:28 +04:00
block, pemByte := pem.Decode(pemByte)
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
fmt.Println(err)
}
certPool := x509.NewCertPool()
certPool.AddCert(cert)
server := &http.Server{
TLSConfig: &tls.Config{
ClientAuth: tls.RequireAndVerifyClientCert,
2013-06-21 02:59:23 +04:00
ClientCAs: certPool,
},
Addr: fmt.Sprintf(":%d", port),
2013-06-20 08:03:28 +04:00
}
err = server.ListenAndServeTLS(certFile, keyFile)
if err != nil {
log.Fatal(err)
}
2013-06-21 02:59:23 +04:00
}
}
2013-06-29 01:17:16 +04:00
//--------------------------------------
// Config
//--------------------------------------
2013-06-21 02:59:23 +04:00
func securityType() int {
if keyFile == "" && certFile == "" && CAFile == "" {
2013-06-20 08:03:28 +04:00
return HTTP
}
if keyFile != "" && certFile != "" {
if CAFile != "" {
return HTTPSANDVERIFY
}
return HTTPS
}
return -1
}
func getInfo(path string) *Info {
info := &Info{}
// Read in the server info if available.
infoPath := fmt.Sprintf("%s/info", path)
if file, err := os.Open(infoPath); err == nil {
if content, err := ioutil.ReadAll(file); err != nil {
fatal("Unable to read info: %v", err)
} else {
if err = json.Unmarshal(content, &info); err != nil {
fatal("Unable to parse info: %v", err)
}
}
file.Close()
2013-06-21 02:59:23 +04:00
// Otherwise ask user for info and write it to file.
} else {
2013-06-21 02:59:23 +04:00
2013-06-13 22:01:06 +04:00
if address == "" {
fatal("Please give the address of the local machine")
}
2013-06-29 01:17:16 +04:00
info.Address = address
info.Address = strings.TrimSpace(info.Address)
fmt.Println("address ", info.Address)
2013-06-21 02:59:23 +04:00
2013-06-29 01:17:16 +04:00
info.ServerPort = serverPort
info.ClientPort = clientPort
info.WebPort = webPort
// Write to file.
content, _ := json.Marshal(info)
content = []byte(string(content) + "\n")
if err := ioutil.WriteFile(infoPath, content, 0644); err != nil {
fatal("Unable to write info to file: %v", err)
}
}
2013-06-21 02:59:23 +04:00
return info
}
//--------------------------------------
// Handlers
//--------------------------------------
// Send join requests to the leader.
func Join(s *raft.Server, serverName string) error {
var b bytes.Buffer
2013-06-21 02:59:23 +04:00
command := &JoinCommand{}
command.Name = s.Name()
json.NewEncoder(&b).Encode(command)
2013-06-20 08:03:28 +04:00
// t must be ok
2013-06-21 02:59:23 +04:00
t, _ := server.Transporter().(transHandler)
debug("Send Join Request to %s", serverName)
resp, err := Post(&t, fmt.Sprintf("%s/join", serverName), &b)
2013-06-20 08:03:28 +04:00
for {
if resp != nil {
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return nil
}
if resp.StatusCode == http.StatusServiceUnavailable {
address, err := ioutil.ReadAll(resp.Body)
if err != nil {
warn("Cannot Read Leader info: %v", err)
}
debug("Leader is %s", address)
debug("Send Join Request to %s", address)
json.NewEncoder(&b).Encode(command)
resp, err = Post(&t, fmt.Sprintf("%s/join", address), &b)
}
}
}
return fmt.Errorf("Unable to join: %v", err)
}
2013-06-21 02:59:23 +04:00