etcd/etcd.go

505 lines
12 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/coreos/etcd/store"
"github.com/coreos/etcd/web"
"github.com/coreos/go-raft"
"io/ioutil"
2013-06-21 02:59:23 +04:00
"log"
"net/http"
"os"
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
var serverCertFile string
var serverKeyFile string
var serverCAFile string
var clientCertFile string
var clientKeyFile string
var clientCAFile string
2013-06-29 01:17:16 +04:00
var dirPath string
var ignore bool
2013-07-01 03:30:41 +04:00
var maxSize int
2013-06-30 21:09:05 +04:00
func init() {
flag.BoolVar(&verbose, "v", false, "verbose logging")
2013-06-29 01:17:16 +04:00
2013-07-01 22:16:30 +04:00
flag.StringVar(&cluster, "C", "", "the ip address and port of a existing cluster")
2013-06-29 01:17:16 +04:00
2013-07-10 01:07:45 +04:00
flag.StringVar(&address, "a", "0.0.0.0", "the ip address of the local machine")
2013-07-01 22:16:30 +04:00
flag.IntVar(&clientPort, "c", 4001, "the port to communicate with clients")
flag.IntVar(&serverPort, "s", 7001, "the port to communicate with servers")
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
flag.StringVar(&serverCAFile, "serverCAFile", "", "the path of the CAFile")
flag.StringVar(&serverCertFile, "serverCert", "", "the cert file of the server")
flag.StringVar(&serverKeyFile, "serverKey", "", "the key file of the server")
2013-07-01 22:16:30 +04:00
flag.StringVar(&clientCAFile, "clientCAFile", "", "the path of the client CAFile")
flag.StringVar(&clientCertFile, "clientCert", "", "the cert file of the client")
flag.StringVar(&clientKeyFile, "clientKey", "", "the key file of the client")
2013-06-29 01:17:16 +04:00
2013-07-10 01:07:45 +04:00
flag.StringVar(&dirPath, "d", "/tmp/", "the directory to store log and snapshot")
flag.BoolVar(&ignore, "i", false, "ignore the old configuration, create a new node")
2013-07-01 03:30:41 +04:00
flag.IntVar(&maxSize, "m", 1024, "the max size of result buffer")
}
2013-06-21 02:59:23 +04:00
// CONSTANTS
2013-06-21 02:59:23 +04:00
const (
HTTP = iota
HTTPS
HTTPSANDVERIFY
)
const (
SERVER = iota
CLIENT
)
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 {
Address string `json:"address"`
2013-06-29 01:17:16 +04:00
ServerPort int `json:"serverPort"`
ClientPort int `json:"clientPort"`
WebPort int `json:"webPort"`
}
//------------------------------------------------------------------------------
//
// Variables
//
//------------------------------------------------------------------------------
2013-07-10 01:55:45 +04:00
var raftServer *raft.Server
var raftTransporter transporter
2013-07-10 00:14:12 +04:00
var etcdStore *store.Store
2013-06-19 02:04:30 +04:00
//------------------------------------------------------------------------------
//
// Functions
//
//------------------------------------------------------------------------------
//--------------------------------------
// Main
//--------------------------------------
func main() {
var err error
flag.Parse()
// Setup commands.
registerCommands()
2013-06-21 02:59:23 +04:00
// Read server info from file or grab it from user.
if err := os.MkdirAll(dirPath, 0744); err != nil {
fatal("Unable to create path: %v", err)
}
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-20 08:03:28 +04:00
// secrity type
st := securityType(SERVER)
2013-06-20 08:03:28 +04:00
clientSt := securityType(CLIENT)
if st == -1 || clientSt == -1 {
fatal("Please specify cert and key file or cert and key file and CAFile or none of the three")
2013-06-20 08:03:28 +04:00
}
// Create transporter for raft
2013-07-10 01:55:45 +04:00
raftTransporter = createTransporter(st)
// Create etcd key-value store
2013-07-10 00:14:12 +04:00
etcdStore = store.CreateStore(maxSize)
2013-06-19 02:04:30 +04:00
// Create raft server
2013-07-10 01:55:45 +04:00
raftServer, err = raft.NewServer(name, dirPath, raftTransporter, etcdStore, nil)
2013-06-19 02:04:30 +04:00
if err != nil {
fmt.Println(err)
os.Exit(1)
}
2013-06-12 20:46:53 +04:00
// LoadSnapshot
// err = raftServer.LoadSnapshot()
// if err == nil {
// debug("%s finished load snapshot", raftServer.Name())
// } else {
// debug(err)
// }
2013-07-10 01:58:59 +04:00
2013-07-10 01:55:45 +04:00
raftServer.Initialize()
raftServer.SetElectionTimeout(ELECTIONTIMTOUT)
raftServer.SetHeartbeatTimeout(HEARTBEATTIMEOUT)
2013-06-13 22:01:06 +04:00
2013-07-10 01:55:45 +04:00
if raftServer.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 == "" {
2013-07-10 01:55:45 +04:00
raftServer.StartLeader()
2013-07-07 09:32:08 +04:00
time.Sleep(time.Millisecond * 20)
2013-06-13 22:01:06 +04:00
2013-07-10 01:55:45 +04:00
// leader need to join self as a peer
2013-07-07 09:32:08 +04:00
for {
command := &JoinCommand{}
2013-07-10 01:55:45 +04:00
command.Name = raftServer.Name()
_, err := raftServer.Do(command)
2013-07-07 09:32:08 +04:00
if err == nil {
break
}
}
2013-07-10 01:55:45 +04:00
debug("%s start as a leader", raftServer.Name())
2013-06-13 22:01:06 +04:00
2013-07-10 01:55:45 +04:00
// start as a follower in a existing cluster
} else {
2013-07-10 01:55:45 +04:00
raftServer.StartFollower()
2013-06-12 20:46:53 +04:00
err := joinCluster(raftServer, cluster)
2013-06-20 08:03:28 +04:00
if err != nil {
fatal(fmt.Sprintln(err))
2013-06-20 08:03:28 +04:00
}
2013-07-10 01:55:45 +04:00
debug("%s success join to the cluster", raftServer.Name())
}
2013-06-13 22:01:06 +04:00
2013-06-12 02:29:25 +04:00
} else {
2013-07-10 01:55:45 +04:00
// rejoin the previous cluster
raftServer.StartFollower()
debug("%s restart as a follower", raftServer.Name())
}
2013-06-13 22:01:06 +04:00
// open the snapshot
// go server.Snapshot()
2013-06-21 02:59:23 +04:00
if webPort != -1 {
// start web
2013-07-10 00:14:12 +04:00
etcdStore.SetMessager(&storeMsg)
2013-06-21 02:59:23 +04:00
go webHelper()
2013-07-10 01:55:45 +04:00
go web.Start(raftServer, webPort)
2013-06-21 02:59:23 +04:00
}
2013-06-20 08:03:28 +04:00
go startRaftTransport(info.ServerPort, st)
startClientTransport(info.ClientPort, clientSt)
2013-06-20 08:03:28 +04:00
}
// Create transporter using by raft server
// Create http or https transporter based on
// wether the user give the server cert and key
2013-07-10 01:55:45 +04:00
func createTransporter(st int) transporter {
t := transporter{}
2013-06-20 08:03:28 +04:00
switch st {
case HTTP:
t.client = nil
return t
case HTTPS:
fallthrough
case HTTPSANDVERIFY:
tlsCert, err := tls.LoadX509KeyPair(serverCertFile, serverKeyFile)
2013-06-20 08:03:28 +04:00
if err != nil {
fatal(fmt.Sprintln(err))
2013-06-20 08:03:28 +04:00
}
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
2013-07-10 01:55:45 +04:00
return transporter{}
2013-06-20 08:03:28 +04:00
}
// Start to listen and response raft command
func startRaftTransport(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)
http.HandleFunc("/client", ClientHttpHandler)
2013-06-29 01:17:16 +04:00
switch st {
case HTTP:
fmt.Println("raft server [%s] listen on http port %v", address, port)
2013-06-29 01:17:16 +04:00
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
case HTTPS:
fmt.Println("raft server [%s] listen on https port %v", address, port)
2013-07-10 01:55:45 +04:00
log.Fatal(http.ListenAndServeTLS(fmt.Sprintf(":%d", port), serverCertFile, serverKeyFile, nil))
2013-06-29 01:17:16 +04:00
case HTTPSANDVERIFY:
server := &http.Server{
TLSConfig: &tls.Config{
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: createCertPool(serverCAFile),
2013-06-29 01:17:16 +04:00
},
Addr: fmt.Sprintf(":%d", port),
}
fmt.Println("raft server [%s] listen on https port %v", address, port)
err := server.ListenAndServeTLS(serverCertFile, serverKeyFile)
2013-06-29 01:17:16 +04:00
if err != nil {
log.Fatal(err)
}
}
}
// Start to listen and response client command
2013-06-29 01:17:16 +04:00
func startClientTransport(port int, st int) {
2013-06-21 02:59:23 +04:00
// external commands
http.HandleFunc("/" + version + "/keys/", Multiplexer)
http.HandleFunc("/" + version + "/watch/", WatchHttpHandler)
http.HandleFunc("/" + version + "/list/", ListHttpHandler)
http.HandleFunc("/" + version + "/testAndSet/", TestAndSetHttpHandler)
http.HandleFunc("/leader", LeaderHttpHandler)
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:
fmt.Println("etcd [%s] listen on http port %v", address, clientPort)
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:
fmt.Println("etcd [%s] listen on https port %v", address, clientPort)
http.ListenAndServeTLS(fmt.Sprintf(":%d", port), clientCertFile, clientKeyFile, nil)
2013-06-20 08:03:28 +04:00
2013-06-21 02:59:23 +04:00
case HTTPSANDVERIFY:
2013-06-20 08:03:28 +04:00
server := &http.Server{
TLSConfig: &tls.Config{
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: createCertPool(clientCAFile),
2013-06-21 02:59:23 +04:00
},
Addr: fmt.Sprintf(":%d", port),
2013-06-20 08:03:28 +04:00
}
fmt.Println("etcd [%s] listen on https port %v", address, clientPort)
err := server.ListenAndServeTLS(clientCertFile, clientKeyFile)
2013-06-20 08:03:28 +04:00
if err != nil {
log.Fatal(err)
os.Exit(1)
2013-06-20 08:03:28 +04:00
}
2013-06-21 02:59:23 +04:00
}
}
//--------------------------------------
// Config
//--------------------------------------
func securityType(source int) int {
var keyFile, certFile, CAFile string
switch source {
case SERVER:
keyFile = serverKeyFile
certFile = serverCertFile
CAFile = serverCAFile
case CLIENT:
keyFile = clientKeyFile
certFile = clientCertFile
CAFile = clientCAFile
}
// If the user do not specify key file, cert file and
// CA file, the type will be HTTP
2013-06-21 02:59:23 +04:00
if keyFile == "" && certFile == "" && CAFile == "" {
2013-06-20 08:03:28 +04:00
return HTTP
}
if keyFile != "" && certFile != "" {
if CAFile != "" {
// If the user specify all the three file, the type
// will be HTTPS with client cert auth
2013-06-20 08:03:28 +04:00
return HTTPSANDVERIFY
}
// If the user specify key file and cert file but not
// CA file, the type will be HTTPS without client cert
// auth
2013-06-20 08:03:28 +04:00
return HTTPS
}
// bad specification
2013-06-20 08:03:28 +04:00
return -1
}
func getInfo(path string) *Info {
info := &Info{}
// Read in the server info if available.
infoPath := fmt.Sprintf("%s/info", path)
// delete the old configuration if exist
if ignore {
logPath := fmt.Sprintf("%s/log", path)
snapshotPath := fmt.Sprintf("%s/snapshotPath", path)
os.Remove(infoPath)
os.Remove(logPath)
os.RemoveAll(snapshotPath)
}
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
}
func createCertPool(CAFile string) *x509.CertPool {
pemByte, _ := ioutil.ReadFile(CAFile)
block, pemByte := pem.Decode(pemByte)
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
certPool := x509.NewCertPool()
certPool.AddCert(cert)
return certPool
}
// Send join requests to the leader.
func joinCluster(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-07-10 01:55:45 +04:00
t, _ := raftServer.Transporter().(transporter)
debug("Send Join Request to %s", serverName)
2013-07-10 01:55:45 +04:00
resp, err := t.Post(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)
2013-07-10 01:55:45 +04:00
resp, err = t.Post(fmt.Sprintf("%s/join", address), &b)
}
}
}
return fmt.Errorf("Unable to join: %v", err)
}
// register commands to raft server
func registerCommands() {
raft.RegisterCommand(&JoinCommand{})
raft.RegisterCommand(&SetCommand{})
raft.RegisterCommand(&GetCommand{})
raft.RegisterCommand(&DeleteCommand{})
raft.RegisterCommand(&WatchCommand{})
raft.RegisterCommand(&ListCommand{})
raft.RegisterCommand(&TestAndSetCommand{})
}