-
Notifications
You must be signed in to change notification settings - Fork 6
/
sync.go
572 lines (507 loc) · 17.7 KB
/
sync.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
package logstream
import (
"context"
"errors"
"fmt"
"sync"
"time"
"go.uber.org/multierr"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/kakao/varlog/internal/storage"
"github.com/kakao/varlog/pkg/rpc"
"github.com/kakao/varlog/pkg/types"
"github.com/kakao/varlog/pkg/verrors"
"github.com/kakao/varlog/proto/snpb"
"github.com/kakao/varlog/proto/varlogpb"
)
type syncTracker struct {
syncRange struct {
first varlogpb.LogSequenceNumber
last varlogpb.LogSequenceNumber
}
mu sync.Mutex
cursor varlogpb.LogEntryMeta
}
func newSyncTracker(first varlogpb.LogSequenceNumber, last varlogpb.LogSequenceNumber) *syncTracker {
st := &syncTracker{}
st.syncRange.first = first
st.syncRange.last = last
return st
}
func (st *syncTracker) toSyncStatus() *snpb.SyncStatus {
st.mu.Lock()
defer st.mu.Unlock()
return &snpb.SyncStatus{
State: snpb.SyncStateInProgress,
First: snpb.SyncPosition{
LLSN: st.syncRange.first.LLSN,
GLSN: st.syncRange.first.GLSN,
},
Last: snpb.SyncPosition{
LLSN: st.syncRange.last.LLSN,
GLSN: st.syncRange.last.GLSN,
},
Current: snpb.SyncPosition{
LLSN: st.cursor.LLSN,
GLSN: st.cursor.GLSN,
},
}
}
func (st *syncTracker) setCursor(cursor varlogpb.LogEntryMeta) {
st.mu.Lock()
defer st.mu.Unlock()
st.cursor = cursor
}
func (lse *Executor) Sync(ctx context.Context, dstReplica varlogpb.LogStreamReplica) (*snpb.SyncStatus, error) {
lse.inflight.Add(1)
defer lse.inflight.Add(-1)
lse.muAdmin.Lock()
defer lse.muAdmin.Unlock()
if state := lse.esm.load(); state != executorStateSealed {
if state == executorStateClosed {
return nil, fmt.Errorf("log stream: sync: %w", verrors.ErrClosed)
}
return nil, fmt.Errorf("log stream: sync: invalid state %d: %w", state, verrors.ErrInvalid)
}
if st, ok := lse.sts[dstReplica.StorageNodeID]; ok {
return st.toSyncStatus(), nil
}
localLWM, localHWM, _ := lse.lsc.localWatermarks()
// The committedLLSNEnd is types.MinLLSN if the result of ReadCommitContext
// is storage.ErrNoCommitContext, since it means this log stream has not
// received a commit message from the metadata repository yet.
committedLLSNEnd := types.MinLLSN
if cc, err := lse.stg.ReadCommitContext(); err == nil {
committedLLSNEnd = cc.CommittedLLSNBegin + types.LLSN(cc.CommittedGLSNEnd-cc.CommittedGLSNBegin)
} else if err != storage.ErrNoCommitContext {
return nil, status.Errorf(codes.Internal, "sync: %s", err.Error())
}
rpcConn, err := rpc.NewConn(ctx, dstReplica.Address)
if err != nil {
return nil, err
}
sc := newSyncClient(syncClientConfig{
dstReplica: dstReplica,
rpcConn: rpcConn,
lse: lse,
logger: lse.logger.Named("sync client").With(zap.String("dst", dstReplica.String())),
})
defer func() {
if err != nil {
err = multierr.Append(err, sc.close())
}
}()
syncRange, err := sc.syncInit(ctx, snpb.SyncRange{
FirstLLSN: localLWM.LLSN,
LastLLSN: localHWM.LLSN,
}, committedLLSNEnd-1)
if err != nil {
if status.Code(err) == codes.AlreadyExists {
err = nil
_ = sc.close()
return &snpb.SyncStatus{
State: snpb.SyncStateComplete,
First: snpb.SyncPosition{
LLSN: localLWM.LLSN,
GLSN: localLWM.GLSN,
},
Last: snpb.SyncPosition{
LLSN: localHWM.LLSN,
GLSN: localHWM.GLSN,
},
}, nil
}
return nil, err
}
var first, last varlogpb.LogSequenceNumber
if !syncRange.FirstLLSN.Invalid() {
logEntry, err := lse.stg.Read(storage.AtLLSN(syncRange.FirstLLSN))
if err != nil {
return nil, err
}
first = varlogpb.LogSequenceNumber{LLSN: logEntry.LLSN, GLSN: logEntry.GLSN}
}
if !syncRange.LastLLSN.Invalid() {
logEntry, err := lse.stg.Read(storage.AtLLSN(syncRange.LastLLSN))
if err != nil {
return nil, err
}
last = varlogpb.LogSequenceNumber{LLSN: logEntry.LLSN, GLSN: logEntry.GLSN}
}
// make tracker
st := newSyncTracker(first, last)
lse.sts[dstReplica.StorageNodeID] = st
_, _ = lse.syncRunner.Run(func(ctx context.Context) {
snid := sc.dstReplica.StorageNodeID
defer func() {
lse.muAdmin.Lock()
delete(lse.sts, snid)
lse.muAdmin.Unlock()
}()
lse.syncLoop(ctx, sc, st)
})
ss := st.toSyncStatus()
ss.State = snpb.SyncStateStart
return ss, nil
}
func (lse *Executor) syncLoop(_ context.Context, sc *syncClient, st *syncTracker) {
var (
err error
stream snpb.Replicator_SyncReplicateStreamClient
cc storage.CommitContext
sr *SubscribeResult
)
defer func() {
if stream != nil {
_, errStream := stream.CloseAndRecv()
err = multierr.Append(err, errStream)
}
if err == nil {
lse.logger.Info("sync completed", zap.String("status", st.toSyncStatus().String()))
} else {
lse.logger.Error("could not sync", zap.Error(err))
}
_ = sc.close()
}()
stream, err = sc.rpcClient.SyncReplicateStream(context.Background())
if err != nil {
return
}
req := &snpb.SyncReplicateRequest{
ClusterID: sc.lse.cid,
Source: sc.srcReplica,
Destination: sc.dstReplica,
}
// NOTE: When the destination has all log entries but a commit context,
// the syncRange.first is invalid because Sync does not look at the
// syncRange.first.
if !st.syncRange.first.Invalid() && st.syncRange.first.GLSN <= st.syncRange.last.GLSN {
sr, err = lse.SubscribeWithGLSN(st.syncRange.first.GLSN, st.syncRange.last.GLSN+1)
if err != nil {
err = fmt.Errorf("scan: %w", err)
return
}
for le := range sr.Result() {
req.Payload.LogEntry = &le
// TODO: Configure syncReplicate timeout
err = stream.SendMsg(req)
if err != nil {
err = fmt.Errorf("sync replicate: log entry %+v: %w", le.LogEntryMeta, err)
sr.Stop()
return
}
st.setCursor(le.LogEntryMeta)
}
sr.Stop()
err = sr.Err()
if err != nil {
err = fmt.Errorf("scan: %w", err)
return
}
}
cc, err = lse.stg.ReadCommitContext()
if err != nil {
err = fmt.Errorf("commit context: %w", err)
return
}
if !st.syncRange.first.LLSN.Invalid() {
// If the first LLSN of the sync range is invalid, there isn't a log entry to copy.
lastCommittedLLSN := cc.CommittedLLSNBegin + types.LLSN(cc.CommittedGLSNEnd-cc.CommittedGLSNBegin) - 1
if lastCommittedLLSN != st.syncRange.last.LLSN {
err = fmt.Errorf("commit context: invalid LLSN: %+v", cc)
}
if cc.CommittedGLSNEnd-1 != st.syncRange.last.GLSN {
err = fmt.Errorf("commit context: invalid GLSN: %+v", cc)
}
if err != nil {
return
}
}
req.Payload.LogEntry = nil
req.Payload.CommitContext = &varlogpb.CommitContext{
Version: cc.Version,
HighWatermark: cc.HighWatermark,
CommittedGLSNBegin: cc.CommittedGLSNBegin,
CommittedGLSNEnd: cc.CommittedGLSNEnd,
CommittedLLSNBegin: cc.CommittedLLSNBegin,
}
err = stream.SendMsg(req)
}
func (lse *Executor) SyncInit(_ context.Context, srcReplica varlogpb.LogStreamReplica, srcRange snpb.SyncRange, srcLastCommittedLLSN types.LLSN) (syncRange snpb.SyncRange, err error) {
lse.inflight.Add(1)
defer lse.inflight.Add(-1)
lse.muAdmin.Lock()
defer lse.muAdmin.Unlock()
err = srcRange.Validate()
if err != nil {
err = status.Error(codes.InvalidArgument, err.Error())
return
}
if !srcRange.LastLLSN.Invalid() && srcRange.LastLLSN != srcLastCommittedLLSN {
err = status.Errorf(codes.InvalidArgument, "unmatched llsn: the last of range %d, the last committed llsn %d", srcRange.LastLLSN, srcLastCommittedLLSN)
return
}
if state := lse.esm.load(); state != executorStateSealing {
if state == executorStateClosed {
err = fmt.Errorf("log stream: sync init: %w", verrors.ErrClosed)
return
}
if state != executorStateLearning {
err = fmt.Errorf("log stream: sync init: invalid state %d: %w", state, verrors.ErrInvalid)
return
}
if elapsed := time.Since(lse.dstSyncInfo.lastSyncTime); elapsed < lse.syncTimeout {
err = fmt.Errorf("log stream: sync init: learning in-progress %s", elapsed)
return
}
// syncTimeout is expired.
lse.esm.store(executorStateSealing)
}
_, _, uncommittedBegin, invalid := lse.lsc.reportCommitBase()
uncommittedLLSNBegin, _ := uncommittedBegin.LLSN, uncommittedBegin.GLSN
dstLastCommittedLLSN := uncommittedLLSNBegin - 1
if !srcRange.LastLLSN.Invalid() && srcRange.LastLLSN < dstLastCommittedLLSN {
lse.logger.Panic("sync init: destination of sync has too many logs",
zap.String("src_range", srcRange.String()),
zap.Uint64("last_committed_llsn", uint64(dstLastCommittedLLSN)),
)
}
lwm, hwm, _ := lse.lsc.localWatermarks()
// NOTE: When the replica has all log entries, it returns its range of logs and non-error results.
// In this case, this replica remains executorStateSealing.
// Breaking change: previously it returns ErrExist when the replica has all log entries to replicate.
//
// The last committed LLSNs denoted by the commit context in the source and
// destination are the same, and the local high watermarks in both replicas
// are also the same. Therefore, synchronization is not necessary between
// them. Even though the local low watermarks differ, they will be the same
// by Trim operation.
if dstLastCommittedLLSN == srcLastCommittedLLSN && hwm.LLSN == srcRange.LastLLSN && !invalid {
return snpb.SyncRange{}, status.Errorf(codes.AlreadyExists, "already synchronized")
}
// The log stream replica will not send a report to the metadata
// repository after changing its state to learning.
// FIXME(jun): It should be necessary to have a mechanism to expire long-time sync init state.
if !lse.esm.compareAndSwap(executorStateSealing, executorStateLearning) {
err = fmt.Errorf("log stream: sync init: invalid state %d: %w", lse.esm.load(), verrors.ErrInvalid)
return
}
trimGLSN := types.InvalidGLSN
alreadySynchronized := false
switch {
case srcRange.FirstLLSN.Invalid() && srcRange.LastLLSN.Invalid():
if srcLastCommittedLLSN < dstLastCommittedLLSN {
lse.logger.Panic("sync init: destination of sync had too many logs",
zap.Any("src_last_committed_llsn", srcLastCommittedLLSN),
zap.Any("dst_last_committed_llsn", dstLastCommittedLLSN),
)
} else if srcLastCommittedLLSN == dstLastCommittedLLSN && !invalid {
alreadySynchronized = true
}
// The source replica does not have log entries when both the FirstLLSN
// and LastLLSN of the srcRange are InvalidLLSNs. Therefore, the
// destination replica must remove all log entries.
trimGLSN = types.MaxGLSN
lwm = varlogpb.LogSequenceNumber{LLSN: types.InvalidLLSN, GLSN: types.InvalidGLSN}
uncommittedBegin = varlogpb.LogSequenceNumber{
LLSN: srcLastCommittedLLSN + 1,
GLSN: types.InvalidGLSN, // It is set to InvalidGLSN since it cannot be known.
}
syncRange = snpb.SyncRange{
FirstLLSN: types.InvalidLLSN,
LastLLSN: types.InvalidLLSN,
}
case srcRange.FirstLLSN < lwm.LLSN:
// The destination replica has a higher LowWatermark than the FirstLLSN
// of the SyncRange sent from the source replica, meaning the
// destination replica might have already been trimmed.
// To simplify the synchronization process, log entries in the
// destination replica will be cut, and then, the log entries will be
// copied from the source to the destination.
trimGLSN = types.MaxGLSN
lwm = varlogpb.LogSequenceNumber{LLSN: types.InvalidLLSN, GLSN: types.InvalidGLSN}
uncommittedBegin = varlogpb.LogSequenceNumber{
LLSN: srcRange.FirstLLSN,
GLSN: types.InvalidGLSN, // It is set to InvalidGLSN since it cannot be known.
}
syncRange = snpb.SyncRange{
FirstLLSN: srcRange.FirstLLSN,
LastLLSN: srcRange.LastLLSN,
}
case srcRange.FirstLLSN == lwm.LLSN:
// The destination replica must not remove log entries; therefore, it
// does not need to change the local low watermark.
// no need to trim
trimGLSN = types.InvalidGLSN
syncRange = snpb.SyncRange{
FirstLLSN: dstLastCommittedLLSN + 1,
LastLLSN: srcRange.LastLLSN,
}
case lwm.LLSN < srcRange.FirstLLSN && srcRange.FirstLLSN <= dstLastCommittedLLSN:
// The destination replica has to trim log entries lower than the
// FirstLLSN of the SyncRange because the source replica did.
// The local low watermark of the destination replica also has to be
// updated.
var entry varlogpb.LogEntry
entry, err = lse.stg.Read(storage.AtLLSN(srcRange.FirstLLSN - 1))
if err != nil {
err = fmt.Errorf("log stream: sync init: cannot find trim position: %w", err)
lse.esm.store(executorStateSealing)
return
}
trimGLSN = entry.GLSN
entry, err = lse.stg.Read(storage.AtLLSN(srcRange.FirstLLSN))
if err != nil {
err = fmt.Errorf("log stream: sync init: cannot find new lwm after trim: %w", err)
lse.esm.store(executorStateSealing)
return
}
lwm = varlogpb.LogSequenceNumber{
LLSN: entry.LLSN,
GLSN: entry.GLSN,
}
syncRange = snpb.SyncRange{
FirstLLSN: dstLastCommittedLLSN + 1,
LastLLSN: srcRange.LastLLSN,
}
default: // dstLastCommittedLLSN < srcRange.FirstLLSN
// All log entries in the destination replica should be removed since
// the log entries in the source replica have already been removed. So
// the local low watermark in the destination replica has to be
// changed.
trimGLSN = types.MaxGLSN
lwm = varlogpb.LogSequenceNumber{LLSN: types.InvalidLLSN, GLSN: types.InvalidGLSN}
uncommittedBegin = varlogpb.LogSequenceNumber{
LLSN: srcRange.FirstLLSN,
GLSN: types.InvalidGLSN, // It is set to InvalidGLSN since it cannot be known.
}
syncRange = snpb.SyncRange{
FirstLLSN: srcRange.FirstLLSN,
LastLLSN: srcRange.LastLLSN,
}
}
// It is unnecessary to copy log entries if FirstLLSN is greater than
// LastLLSN, and it has to copy only the commit context.
if syncRange.FirstLLSN > syncRange.LastLLSN {
syncRange = snpb.SyncRange{
FirstLLSN: types.InvalidLLSN,
LastLLSN: types.InvalidLLSN,
}
}
if !trimGLSN.Invalid() {
err = lse.stg.Trim(trimGLSN)
if err != nil && !errors.Is(err, storage.ErrNoLogEntry) {
err = fmt.Errorf("log stream: sync init: remove trimmed log entries: %w", err)
lse.esm.store(executorStateSealing)
return
}
lse.lsc.setLocalLowWatermark(lwm)
}
if alreadySynchronized {
lse.esm.store(executorStateSealing)
return snpb.SyncRange{}, status.Errorf(codes.AlreadyExists, "already synchronized")
}
// NOTE: Invalid reportCommitBase makes the report of the log
// stream replica meaningless.
// The LLSN of uncommittedBegin indicates a sequence number of the
// following log entry copied from a source replica.
// Invalid GLSN of uncommittedBegin makes the local high watermark of the
// replica invalid.
lse.lsc.storeReportCommitBase(types.InvalidVersion, types.InvalidGLSN, uncommittedBegin, true /*invalid*/)
// learning
lse.resetInternalState(dstLastCommittedLLSN, !lse.isPrimary())
lse.dstSyncInfo.lastSyncTime = time.Now()
lse.dstSyncInfo.srcReplica = srcReplica.StorageNodeID
return syncRange, nil
}
func (lse *Executor) SyncReplicate(_ context.Context, srcReplica varlogpb.LogStreamReplica, payload snpb.SyncPayload) (err error) {
lse.inflight.Add(1)
defer lse.inflight.Add(-1)
lse.muAdmin.Lock()
defer lse.muAdmin.Unlock()
if state := lse.esm.load(); state != executorStateLearning {
if state == executorStateClosed {
return fmt.Errorf("log stream: sync replicate: %w", verrors.ErrClosed)
}
return fmt.Errorf("log stream: sync replicate: invalid state %d: %w", state, verrors.ErrInvalid)
}
if lse.dstSyncInfo.srcReplica != srcReplica.StorageNodeID {
return fmt.Errorf("log stream: sync replicate: incorrect source replica: %s", srcReplica.String())
}
if payload.LogEntry == nil && payload.CommitContext == nil {
lse.esm.store(executorStateSealing)
return fmt.Errorf("log stream: sync replicate: empty payload")
}
done := false
batch := lse.stg.NewAppendBatch()
defer func() {
_ = batch.Close()
if err != nil || done {
lse.esm.store(executorStateSealing)
}
}()
ver, hwm, uncommittedBegin, invalid := lse.lsc.reportCommitBase()
logEntry := payload.LogEntry
if logEntry != nil {
if logEntry.LLSN != uncommittedBegin.LLSN {
err = fmt.Errorf("log stream: sync replicate: unexpected log entry: expected_llsn=%v, actual_llsn=%v", uncommittedBegin.LLSN, logEntry.LLSN)
return err
}
err = batch.SetLogEntry(logEntry.LLSN, logEntry.GLSN, logEntry.Data)
if err != nil {
return err
}
if ce := lse.logger.Check(zap.DebugLevel, "log stream: sync replicate: copy"); ce != nil {
ce.Write(zap.String("log entry", logEntry.String()))
}
uncommittedBegin = varlogpb.LogSequenceNumber{
LLSN: logEntry.LLSN + 1,
GLSN: logEntry.GLSN + 1, // It might not be exact.
}
invalid = true
}
if cc := payload.CommitContext; cc != nil {
lastLLSN := cc.CommittedLLSNBegin + types.LLSN(cc.CommittedGLSNEnd-cc.CommittedGLSNBegin) - 1
if lastLLSN != uncommittedBegin.LLSN-1 {
err = fmt.Errorf("log stream: sync replicate: unexpected commit context: expected_last_llsn=%v, actual_last_llsn=%v", uncommittedBegin.LLSN-1, lastLLSN)
return err
}
err = batch.SetCommitContext(storage.CommitContext{
Version: cc.Version,
HighWatermark: cc.HighWatermark,
CommittedGLSNBegin: cc.CommittedGLSNBegin,
CommittedGLSNEnd: cc.CommittedGLSNEnd,
CommittedLLSNBegin: cc.CommittedLLSNBegin,
})
if err != nil {
return err
}
if ce := lse.logger.Check(zap.DebugLevel, "log stream: sync replicate: copy"); ce != nil {
ce.Write(zap.String("commit context", cc.String()))
}
ver = cc.Version
hwm = cc.HighWatermark
uncommittedBegin = varlogpb.LogSequenceNumber{
LLSN: cc.CommittedLLSNBegin + types.LLSN(cc.CommittedGLSNEnd-cc.CommittedGLSNBegin),
GLSN: cc.CommittedGLSNEnd,
}
invalid = false
done = true
}
err = batch.Apply()
if err != nil {
return err
}
if logEntry != nil {
lse.lsc.localLWM.CompareAndSwap(varlogpb.LogSequenceNumber{}, varlogpb.LogSequenceNumber{
LLSN: logEntry.LLSN,
GLSN: logEntry.GLSN,
})
}
lse.lsc.storeReportCommitBase(ver, hwm, uncommittedBegin, invalid)
lse.lsc.uncommittedLLSNEnd.Store(uncommittedBegin.LLSN)
lse.dstSyncInfo.lastSyncTime = time.Now()
return nil
}