-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
73 lines (60 loc) · 1.53 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
package main
import (
"context"
"fmt"
"log/slog"
"net"
"os"
"strconv"
"strings"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
pb "github.com/jm96441n/raft/gen/go/raft/v1"
"github.com/jm96441n/raft/raft"
)
type Config struct {
port int
serverAddrs []string
leaderAddr string
}
func main() {
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
envVars, err := parseEnvVars()
if err != nil {
logger.Error("failed to parse env vars", slog.Any("err", err))
os.Exit(1)
}
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", envVars.port))
if err != nil {
logger.Error("failed to construct listener on port", slog.Any("err", err), slog.Any("port", envVars.port))
}
node, err := raft.NewNode(raft.NodeConfig{
Logger: logger,
ServerAddrs: envVars.serverAddrs,
LogStore: raft.NewInMemStore(),
})
if err != nil {
logger.Error("failed to create server", slog.Any("err", err))
}
logger.Info("running")
go node.Run(context.Background())
s := grpc.NewServer()
pb.RegisterRaftServer(s, node)
reflection.Register(s)
logger.Info("server listening", slog.Any("addr", listener.Addr().String()))
if err := s.Serve(listener); err != nil {
logger.Error("failed to serve", slog.Any("err", err))
os.Exit(1)
}
}
func parseEnvVars() (Config, error) {
port, err := strconv.Atoi(os.Getenv("PORT"))
if err != nil {
return Config{}, err
}
return Config{
port: port,
leaderAddr: os.Getenv("LEADER_ADDR"),
serverAddrs: strings.Split(os.Getenv("SERVER_ADDRS"), ","),
}, nil
}