-
Notifications
You must be signed in to change notification settings - Fork 1
/
node_peer.go
91 lines (74 loc) · 1.87 KB
/
node_peer.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
package rafting
import (
"context"
"fmt"
"time"
pb "github.com/danielgatis/go-rafting/protobuf"
"github.com/hashicorp/raft"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type peer struct {
id string
addr string
port int32
}
func getPeers(addrs []string) []peer {
peers := make([]peer, 0)
for _, addr := range addrs {
p, err := getPeer(addr)
if err != nil {
continue
}
peers = append(peers, peer{
id: p.Id,
addr: addr,
port: p.Port,
})
}
return peers
}
func getPeer(addr string) (*pb.GetDetailsResponse, error) {
var opt grpc.DialOption = grpc.EmptyDialOption{}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
conn, err := grpc.DialContext(ctx, addr, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock(), opt)
if err != nil {
return nil, fmt.Errorf(`grpc.Dial(...): %w`, err)
}
defer conn.Close()
client := pb.NewRaftingServiceClient(conn)
response, err := client.GetDetails(context.Background(), &pb.GetDetailsRequest{})
if err != nil {
return nil, fmt.Errorf(`client.GetDetails(...): %w`, err)
}
return response, nil
}
func remPeer(n *Node, details []peer) {
for _, server := range n.raft.GetConfiguration().Configuration().Servers {
found := false
for _, detail := range details {
if string(server.Address) == detail.addr || string(server.ID) == detail.id {
found = true
break
}
}
if !found {
n.raft.RemoveServer(server.ID, 0, 0)
}
}
}
func addPeer(n *Node, details []peer) {
for _, detail := range details {
found := false
for _, server := range n.raft.GetConfiguration().Configuration().Servers {
if string(server.Address) == detail.addr || string(server.ID) == detail.id {
found = true
break
}
}
if !found {
n.raft.AddVoter(raft.ServerID(detail.id), raft.ServerAddress(detail.addr), 0, 0)
}
}
}