-
Notifications
You must be signed in to change notification settings - Fork 2
/
bootstrap_service_server.go
42 lines (37 loc) · 1.37 KB
/
bootstrap_service_server.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
package main
import (
"context"
"log"
"github.com/priyangshupal/grpc-raft-consensus/pb"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type BootstrapServiceServer struct {
pb.UnimplementedBootstrapServiceServer
raftServer *RaftServer
}
func NewBootstrapServiceServer(s *RaftServer) *BootstrapServiceServer {
return &BootstrapServiceServer{raftServer: s}
}
func (s *BootstrapServiceServer) AddReplica(ctx context.Context, addrInfo *pb.AddrInfo) (*pb.AddrInfoStatus, error) {
log.Printf("[%s] received (addReplica) request from [%s]\n", s.raftServer.Transport.Addr(), addrInfo.Addr)
if ok := s.raftServer.ReplicaConnMap[addrInfo.Addr]; ok != nil {
// raft server already present
log.Printf("raft server [%s] present in replicaConnMap", addrInfo.Addr)
return &pb.AddrInfoStatus{IsAdded: true}, nil
}
// raft server not present in replicaConnMap,
// create a new connection and add it
conn, err := grpc.NewClient(
addrInfo.Addr,
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
log.Printf("[%s] error while creating gRPC client to [%s]\n", s.raftServer.Transport.Addr(), addrInfo.Addr)
return &pb.AddrInfoStatus{IsAdded: false}, err
}
s.raftServer.ReplicaConnMapLock.Lock()
s.raftServer.ReplicaConnMap[addrInfo.Addr] = conn
s.raftServer.ReplicaConnMapLock.Unlock()
return &pb.AddrInfoStatus{IsAdded: true}, nil
}