This repository has been archived by the owner on Feb 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
101 lines (88 loc) · 2.34 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"github.com/hashicorp/go-hclog"
"github.com/kei6u/raftkv/config"
"github.com/kei6u/raftkv/kv"
raftkvpb "github.com/kei6u/raftkv/proto/v1"
"github.com/kei6u/retry"
"google.golang.org/grpc"
)
var (
l hclog.Logger
conf = &config.Values{}
)
func init() {
// setup a logger
l = hclog.New(hclog.DefaultOptions)
if err := conf.Load(); err != nil {
l.Warn("exit since loading environment variables failed", "error", err)
os.Exit(1)
}
l.SetLevel(hclog.Level(conf.LogLevel))
if err := os.MkdirAll(conf.DataDir, 0700); err != nil {
l.Warn("exit since making a directory for a file snapshot store failed", "error", err)
os.Exit(1)
}
}
func main() {
sig := make(chan os.Signal, 1)
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, os.Kill, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sig
cancel()
}()
store := kv.NewStore(l)
kvserver := kv.NewServer(store, l, conf)
if err := kvserver.Start(); err != nil {
l.Warn("exit since a store failed to be opened", "error", err)
os.Exit(1)
}
if conf.JoinAddr == "" {
l.Info("bootstraping a new cluster")
if err := kvserver.BootstrapCluster(); err != nil {
l.Warn("exit since bootstraping a cluster failed", "error", err)
os.Exit(1)
}
} else {
conn, err := grpc.DialContext(ctx, conf.JoinAddr, grpc.WithInsecure())
if err != nil {
l.Warn(fmt.Sprintf("failed to dial a gRPC server at %s", conf.JoinAddr), "error", err)
cancel()
return
}
c := raftkvpb.NewRaftkvServiceClient(conn)
l.Info("new server is joining to a cluster", "server_id", conf.ServerId, "advertise_addr", conf.AdvertiseAddr)
r := retry.New(retry.Jitter{})
for r.Next() {
_, err = c.Join(ctx, &raftkvpb.JoinRequest{
ServerId: conf.ServerId,
Address: conf.AdvertiseAddr,
})
if err == nil {
break
}
}
if err != nil {
l.Warn("new server failed to join a cluster", "error", err)
cancel()
}
_ = conn.Close()
}
server, err := raftkvpb.NewServer(ctx, conf.GRPCAddr(), conf.GRPCGWAddr(), l, kvserver)
if err != nil {
l.Warn("exit due to a failure of initializing a server", "error", err)
cancel()
}
if err := server.Start(); err != nil {
l.Warn("exit due to a failure of starting a server", "error", err)
cancel()
}
<-ctx.Done()
_ = kvserver.Shutdown()
server.Stop()
}