forked from 0xPolygon/pbft-consensus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
actions.go
85 lines (70 loc) · 2.01 KB
/
actions.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
package e2e
import (
"log"
"math/rand"
"time"
"github.com/0xPolygon/pbft-consensus"
)
type RevertFunc func()
type FunctionalAction interface {
CanApply(c *Cluster) bool
Apply(c *Cluster) RevertFunc
}
// DropNodeAction encapsulates logic for dropping nodes action.
type DropNodeAction struct {
}
func (dn *DropNodeAction) CanApply(c *Cluster) bool {
runningNodes := len(c.GetRunningNodes())
if runningNodes <= 0 {
return false
}
maxFaultyNodes := pbft.MaxFaultyNodes(len(c.nodes))
remainingNodes := runningNodes - 1
return remainingNodes >= maxFaultyNodes
}
func (dn *DropNodeAction) Apply(c *Cluster) RevertFunc {
runningNodes := c.GetRunningNodes()
nodeToStop := runningNodes[rand.Intn(len(runningNodes))]
log.Printf("Dropping node: '%s'.", nodeToStop)
c.StopNode(nodeToStop.name)
return func() {
log.Printf("Reverting stopped node %v\n", nodeToStop.name)
nodeToStop.Start()
}
}
type PartitionAction struct {
}
func (action *PartitionAction) CanApply(_ *Cluster) bool {
return true
}
func (action *PartitionAction) Apply(c *Cluster) RevertFunc {
c.lock.Lock()
defer c.lock.Unlock()
hook := newPartitionTransport(500 * time.Millisecond)
// create 2 partition with random number of nodes
// minority with less than quorum size nodes and majority with the rest of the nodes
quorumSize := pbft.QuorumSize(len(c.nodes))
var minorityPartition []string
var majorityPartition []string
minorityPartitionSize := rand.Intn(quorumSize + 1)
i := 0
for n := range c.nodes {
if i < minorityPartitionSize {
minorityPartition = append(minorityPartition, n)
i++
} else {
majorityPartition = append(majorityPartition, n)
}
}
log.Printf("Partitions ratio %d/%d, [%v], [%v]\n", len(majorityPartition), len(minorityPartition), majorityPartition, minorityPartition)
hook.Partition(minorityPartition, majorityPartition)
c.SetHook(hook)
return func() {
c.lock.Lock()
defer c.lock.Unlock()
log.Println("Reverting partitions.")
if tHook := c.transport.getHook(); tHook != nil {
tHook.Reset()
}
}
}