-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessage.go
176 lines (151 loc) · 4.54 KB
/
message.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
package bullyelection
import (
"bytes"
"context"
"encoding/json"
"io"
"sync"
"time"
"github.com/pkg/errors"
)
var (
bufferPool = &sync.Pool{
New: func() any {
return bytes.NewBuffer(make([]byte, 0, 1024))
},
}
)
type nodeMessageType uint8
const (
ElectionMessage nodeMessageType = iota + 1
AnswerMessage
CoordinatorMessage
TransferLeadershipMessage
)
func (m nodeMessageType) String() string {
switch m {
case ElectionMessage:
return "msg<Election>"
case AnswerMessage:
return "msg<Answer>"
case CoordinatorMessage:
return "msg<Coordinator>"
case TransferLeadershipMessage:
return "msg<TransferLeadership>"
}
return "unknown message"
}
type nodeMessage struct {
Type nodeMessageType `json:"type"`
NodeID string `json:"node-id"`
NodeAddr string `json:"node-addr"`
}
func marshalNodeMessage(out io.Writer, msgType nodeMessageType, nodeID, addr string) error {
if err := json.NewEncoder(out).Encode(nodeMessage{msgType, nodeID, addr}); err != nil {
return errors.WithStack(err)
}
return nil
}
func unmarshalNodeMessage(in io.Reader) (nodeMessage, error) {
msg := nodeMessage{}
if err := json.NewDecoder(in).Decode(&msg); err != nil {
return nodeMessage{}, errors.WithStack(err)
}
return msg, nil
}
func (b *Bully) sendMessage(targetNodeID string, t nodeMessageType) error {
buf := bufferPool.Get().(*bytes.Buffer)
defer bufferPool.Put(buf)
buf.Reset()
if err := marshalNodeMessage(buf, t, b.node.ID(), b.fulladdress()); err != nil {
return errors.WithStack(err)
}
return b.send(targetNodeID, buf.Bytes())
}
func (b *Bully) sendElectionMessage(targetNodeID string) error {
return b.sendMessage(targetNodeID, ElectionMessage)
}
func (b *Bully) sendAnswerMessage(targetNodeID string) error {
return b.sendMessage(targetNodeID, AnswerMessage)
}
func (b *Bully) sendCoordinatorMessage(targetNodeID string) error {
return b.sendMessage(targetNodeID, CoordinatorMessage)
}
func (b *Bully) sendTransferLeaderMessage(targetNodeID string) error {
return b.sendMessage(targetNodeID, TransferLeadershipMessage)
}
func (b *Bully) readNodeMessageLoop(ctx context.Context, ch chan []byte, evtCh chan *nodeEventMsg) {
defer b.wg.Done()
dumpNodes := func() {
for _, n := range b.listNodes() {
b.opt.logger.Printf("debug: ID:%s(%s:%d) isVoter:%v isLeader:%v", n.ID(), n.Addr(), n.Port(), n.IsVoter(), n.IsLeader())
}
}
for {
select {
case <-ctx.Done():
return
case data := <-ch:
msg, err := unmarshalNodeMessage(bytes.NewReader(data))
if err != nil {
b.opt.onErrorFunc(errors.Wrapf(err, "recv data: %s", data))
continue
}
switch msg.Type {
case ElectionMessage:
b.opt.logger.Printf("info: election message: %s", msg.NodeID)
if err := b.sendAnswerMessage(msg.NodeID); err != nil {
// It will automatically reply, so there may be cases where it tries to send to a NodeID
// that is not yet included in Members(), and it is ok to ignore it.
if errors.Is(err, ErrNodeNotFound) != true {
b.opt.onErrorFunc(errors.Wrapf(err, "send answer(%s)", msg.NodeID))
continue
}
}
case AnswerMessage:
b.opt.logger.Printf("info: answer message: %s", msg.NodeID)
b.mu.Lock()
b.electionCancel()
b.electionCancel = nopCancelFunc()
b.mu.Unlock()
b.clearLeaderID()
if err := b.updateNode(); err != nil {
b.opt.onErrorFunc(errors.Wrapf(err, "clear leader(%s)", msg.NodeID))
continue
}
case CoordinatorMessage:
b.opt.logger.Printf("info: coordinator message: %s", msg.NodeID)
b.setLeaderID(msg.NodeID)
if err := b.updateNode(); err != nil {
b.opt.onErrorFunc(errors.Wrapf(err, "update leader(%s)", msg.NodeID))
continue
}
dumpNodes()
evtMsg := &nodeEventMsg{ElectionEvent, msg.NodeID, msg.NodeAddr, true}
select {
case evtCh <- evtMsg:
// ok
case <-time.After(b.opt.retryNodeEventTimeout):
b.opt.logger.Printf("warn: evtCh maybe hangup(election), drop msg: %+v", evtMsg)
}
if b.waitElection != nil {
select {
case b.waitElection <- struct{}{}:
// ok
default:
b.opt.logger.Printf("warn: waitElection maybe hangup or no reader, drop")
}
}
case TransferLeadershipMessage:
b.opt.logger.Printf("info: transfer_leadership message: %s", msg.NodeID)
evtMsg := &nodeEventMsg{TransferLeadershipEvent, msg.NodeID, msg.NodeAddr, true}
select {
case evtCh <- evtMsg:
// ok
case <-time.After(b.opt.retryNodeEventTimeout):
b.opt.logger.Printf("warn: evtCh maybe hangup(transfer_leadership), drop msg: %+v", msg)
}
}
}
}
}