-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
105 lines (79 loc) · 1.79 KB
/
Copy pathmain.go
File metadata and controls
105 lines (79 loc) · 1.79 KB
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
102
103
104
105
package main
import (
"context"
"fmt"
"log"
"net"
"net/rpc"
"os"
"os/signal"
"sync"
"time"
"raft/client"
"raft/election"
kvstore "raft/kv_store"
"raft/replication"
"raft/state"
)
type Arithmetic struct{}
type Args struct {
A, B int
}
var CurrentTerm int = 0
var VotedFor string
var Wg sync.WaitGroup
func init() {
if len(os.Args) < 3 {
log.Fatal("Please provide server address and key value store api address")
return
}
Wg.Add(1)
go state.InitializeState(&Wg, os.Args[1])
Wg.Wait()
fmt.Println("Initialized state")
// Initialize election timeout
go election.InitElectionFlow()
}
func main() {
formattedAddr := fmt.Sprintf("localhost%s", os.Args[1])
fmt.Println("ADDR => ", formattedAddr)
// open RPC connections
election := new(election.ElectionRPC)
replicationRPC := new(replication.ReplicationRPC)
clientRPC := new(client.ClientRPC)
rpc.Register(election)
rpc.Register(replicationRPC)
rpc.Register(clientRPC)
// Graceful shutdown
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
// Start listening on a specific port
fmt.Println("POrt => ", state.Node.Ip)
listener, err := net.Listen("tcp", state.Node.Ip)
if err != nil {
fmt.Println("Error starting listener:", err)
}
// defer listener.Close()
// Initialize key value store
// kvstore.InitiateKVState()
go kvstore.InitializeApi(os.Args[2])
fmt.Printf("Listening on port %s\n\n", os.Args[1])
go func() {
for {
conn, err := listener.Accept()
if err != nil {
log.Fatal(err)
continue
}
fmt.Println("Received Connection")
// Serve request in goroutine
go rpc.ServeConn(conn)
}
}()
<-stop
fmt.Println("Shuting down Raft...")
state.Node.Fd.Close()
listener.Close()
_, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
}