-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquorum_test.go
268 lines (215 loc) · 6.78 KB
/
quorum_test.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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package gonsensus
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"log"
"sync"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
)
func TestQuorum(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
testCtx := &quorumTestContext{
t: t,
mockS3: NewMockS3Client(),
quorumSize: 3,
elected: make(chan struct{}, 1),
demoted: make(chan struct{}, 1),
}
manager := testCtx.setupManager()
var wGroup sync.WaitGroup
testCtx.startManager(ctx, manager, &wGroup)
testCtx.waitForElection()
// Add delay after election before registration
time.Sleep(1 * time.Second)
if err := testCtx.registerAndVerifyObservers(ctx, manager); err != nil {
t.Fatalf("failed to register and verify observers: %v", err)
}
testCtx.runHeartbeats(ctx, manager)
testCtx.simulateQuorumLoss(ctx, manager)
// Cleanup
cancel()
wGroup.Wait()
}
type quorumTestContext struct {
t *testing.T
mockS3 *MockS3Client
quorumSize int
elected chan struct{}
demoted chan struct{}
}
func (tc *quorumTestContext) setupManager() *Manager {
manager, err := NewManager(tc.mockS3, "test-bucket", Config{
TTL: 2 * time.Second,
PollInterval: 500 * time.Millisecond,
NodeID: "test-node-1",
LockPrefix: "locks/",
QuorumSize: tc.quorumSize,
})
if err != nil {
tc.t.Fatalf("failed to create manager: %v", err)
}
manager.SetCallbacks(
func(_ context.Context) error {
tc.elected <- struct{}{}
return nil
},
func(_ context.Context) {
tc.demoted <- struct{}{}
},
)
return manager
}
func (tc *quorumTestContext) startManager(ctx context.Context, manager *Manager, wg *sync.WaitGroup) {
wg.Add(1)
go func() {
defer wg.Done()
err := manager.Run(ctx)
if err != nil && !errors.Is(err, context.Canceled) &&
!errors.Is(err, context.DeadlineExceeded) &&
!errors.Is(err, ErrLostQuorum) {
tc.t.Errorf("unexpected error from Run: %v", err)
}
}()
}
func (tc *quorumTestContext) waitForElection() {
select {
case <-tc.elected:
log.Printf("DEBUG: Leader elected, proceeding with test")
case <-time.After(3 * time.Second):
tc.t.Fatal("leader election timed out")
}
}
func (tc *quorumTestContext) registerObserverWithRetry(ctx context.Context, manager *Manager, nodeID string) error {
for range 5 {
if err := manager.RegisterObserver(ctx, nodeID, nil); err == nil {
return nil
}
time.Sleep(100 * time.Millisecond)
}
return ErrFailedToRegisterObserver
}
func (tc *quorumTestContext) runHeartbeats(ctx context.Context, manager *Manager) {
heartbeatCtx, stopHeartbeats := context.WithCancel(ctx)
var heartbeatWg sync.WaitGroup
tc.startObserverHeartbeats(heartbeatCtx, manager, &heartbeatWg)
time.Sleep(3 * time.Second)
// Verify with retries
if err := tc.verifyObserverCount(ctx, manager, tc.quorumSize); err != nil {
tc.t.Fatalf("failed to verify observers after heartbeats: %v", err)
}
stopHeartbeats()
heartbeatWg.Wait()
}
func (tc *quorumTestContext) startObserverHeartbeats(ctx context.Context, manager *Manager, wGroup *sync.WaitGroup) {
for i := 1; i <= tc.quorumSize; i++ {
nodeID := fmt.Sprintf("test-node-%d", i)
wGroup.Add(1)
go tc.runObserverHeartbeat(ctx, manager, nodeID, wGroup)
}
}
func (tc *quorumTestContext) runObserverHeartbeat(ctx context.Context, manager *Manager,
nodeID string, wg *sync.WaitGroup) {
defer wg.Done()
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
if err := manager.UpdateHeartbeat(ctx, nodeID); err != nil {
if !errors.Is(err, context.Canceled) {
tc.t.Logf("heartbeat update failed for %s: %v", nodeID, err)
}
}
}
}
}
func (tc *quorumTestContext) simulateQuorumLoss(ctx context.Context, manager *Manager) {
lockInfo := tc.getLockInfo(ctx, manager)
tc.markObserversInactive(lockInfo)
tc.updateLockWithInactiveObservers(ctx, lockInfo)
tc.waitForDemotion(ctx, manager)
}
func (tc *quorumTestContext) getLockInfo(ctx context.Context, manager *Manager) *LockInfo {
lockInfo, err := manager.GetLockInfo(ctx)
if err != nil {
tc.t.Fatalf("%s: %v", ErrFailedToGetLockInfo, err)
}
return lockInfo
}
func (tc *quorumTestContext) markObserversInactive(lockInfo *LockInfo) {
veryOldTime := time.Now().Add(-60 * time.Second)
for nodeID := range lockInfo.Observers {
observer := lockInfo.Observers[nodeID]
observer.LastHeartbeat = veryOldTime
observer.IsActive = false
lockInfo.Observers[nodeID] = observer
}
}
func (tc *quorumTestContext) updateLockWithInactiveObservers(ctx context.Context, lockInfo *LockInfo) {
lockData, err := json.Marshal(lockInfo)
if err != nil {
tc.t.Fatalf("%s: %v", ErrFailedToMarshalLockInfo, err)
}
_, err = tc.mockS3.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String("test-bucket"),
Key: aws.String("locks/leader"),
Body: bytes.NewReader(lockData),
ContentType: aws.String(jsonContentType),
})
if err != nil {
tc.t.Fatalf("failed to update lock info: %v", err)
}
}
func (tc *quorumTestContext) waitForDemotion(ctx context.Context, manager *Manager) {
select {
case <-tc.demoted:
log.Printf("DEBUG: Leader successfully demoted after losing quorum")
case <-time.After(3 * time.Second):
activeCount, _ := manager.GetActiveObservers(ctx)
tc.t.Fatalf("leader failed to step down after losing quorum (active observers: %d)", activeCount)
}
}
func (tc *quorumTestContext) registerAndVerifyObservers(ctx context.Context, manager *Manager) error {
// Register observers one at a time with verification
for iter := 1; iter <= tc.quorumSize; iter++ {
nodeID := fmt.Sprintf("test-node-%d", iter)
// Register with retry
if err := tc.registerObserverWithRetry(ctx, manager, nodeID); err != nil {
return fmt.Errorf("%w: %s", ErrFailedToRegisterObserver, nodeID)
}
// Verify after each registration
if err := tc.verifyObserverCount(ctx, manager, iter); err != nil {
return fmt.Errorf("%w: failed to verify observer count after registering %s", err, nodeID)
}
// Add delay between registrations
time.Sleep(500 * time.Millisecond)
}
return nil
}
func (tc *quorumTestContext) verifyObserverCount(ctx context.Context, manager *Manager, expectedCount int) error {
// Retry verification multiple times
for iter := range 10 {
activeCount, err := manager.GetActiveObservers(ctx)
if err == nil && activeCount == expectedCount {
tc.t.Logf("Successfully verified %d observers", activeCount)
return nil
}
if err != nil {
tc.t.Logf("Retry %d: Error getting active observers: %v", iter, err)
} else {
tc.t.Logf("Retry %d: Expected %d observers, got %d", iter, expectedCount, activeCount)
}
time.Sleep(200 * time.Millisecond)
}
return fmt.Errorf("%w", errFailedToVerifyObserverCount)
}