-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathreplicator.go
More file actions
294 lines (259 loc) · 7.9 KB
/
replicator.go
File metadata and controls
294 lines (259 loc) · 7.9 KB
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
// Copyright 2017, The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE.md file.
package main
import (
"bytes"
"fmt"
"io"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/dsnet/golib/unitconv"
"tailscale.com/syncs"
"tailscale.com/tstime/rate"
)
// replicaManager is responsible for sending snapshots from one target
// and receiving them at another target.
type replicaManager struct {
zs *zsyncer
srcDataset dataset
dstDatasets []dataset
sendFlags []string
recvFlags []string
initRecvFlags []string
signal chan struct{}
timer *time.Timer
statuses []replicationStatus // len(statuses) == len(dst)
}
type replicationStatus struct {
atomicMu sync.Mutex // held while mutating multiple fields together
started syncs.AtomicValue[time.Time]
finished syncs.AtomicValue[time.Time]
transferByteRate rate.Value
transferredBytes atomic.Int64
estimatedBytes atomic.Int64
faultReason syncs.AtomicValue[string]
}
func (zs *zsyncer) RegisterReplicaManager(src dataset, dsts []dataset, sendFlags, recvFlags, initRecvFlags []string) {
rm := &replicaManager{
zs: zs,
srcDataset: src,
dstDatasets: dsts,
sendFlags: sendFlags,
recvFlags: recvFlags,
initRecvFlags: initRecvFlags,
signal: make(chan struct{}, 1),
timer: time.NewTimer(0),
statuses: make([]replicationStatus, len(dsts)),
}
id := src.DatasetPath()
if _, ok := zs.replicaManagers[id]; ok {
zs.log.Fatalf("%s already registered", id)
}
zs.replicaManagers[id] = rm
}
func (rm *replicaManager) Run() {
var retryDelay time.Duration
var attempts int
for {
select {
case <-rm.signal:
case <-rm.timer.C:
case <-rm.zs.ctx.Done():
return
}
attempts++
var replicated, failed bool
for i := range rm.dstDatasets {
rm.replicate(i, attempts, &replicated, &failed)
}
if failed {
retryDelay = timeoutAfter(retryDelay)
rm.timer.Reset(retryDelay)
} else {
retryDelay = 0
attempts = 0
rm.timer.Stop()
}
// Signal the snapshot manager to delete synced snapshots.
if replicated {
trySignal(rm.zs.snapshotManagers[rm.srcDataset.DatasetPath()].signal)
}
}
}
func (rm *replicaManager) replicate(idx, attempts int, replicated, failed *bool) {
// Acquire the semaphore to limit number of concurrent transfers.
select {
case rm.zs.replSema <- struct{}{}:
defer func() { <-rm.zs.replSema }()
case <-rm.zs.ctx.Done():
return
}
src, dst := rm.srcDataset, rm.dstDatasets[idx]
defer recoverError(func(err error) {
if xerr, ok := err.(exitError); ok {
subject := fmt.Sprintf("Replication failure from %q to %q", src.DatasetPath(), src.DatasetPath())
if merr := sendEmail(rm.zs.smtp, subject, "<pre>"+xerr.Error()+"</pre>"); merr != nil {
rm.zs.log.Printf("unable to send email: %v", merr)
}
}
rm.zs.log.Printf("dataset %s: replication error (attempt %d): %v", dst.DatasetPath(), attempts, err)
*failed = true
})
// Open an executor for the source and destination dataset.
srcExec := mustGet(openExecutor(rm.zs.ctx, src.target))
defer srcExec.Close()
dstExec := mustGet(openExecutor(rm.zs.ctx, dst.target))
defer dstExec.Close()
// Resume a partial receive if there is a token.
s, err := dstExec.Exec("zfs", "get", "-H", "-o", "value", "receive_resume_token", dst.name)
if tok := strings.TrimSpace(s); err == nil && len(tok) > 1 {
rm.transfer(idx, transferArgs{
Mode: "partial",
SrcLabel: src.DatasetPath(),
DstLabel: dst.DatasetPath(),
SendArgs: zsendArgs("-t", tok),
RecvArgs: zrecvArgs(rm.recvFlags, dst.name),
SrcExec: srcExec, DstExec: dstExec,
})
*replicated = true
}
for {
// Obtain a list of source and destination snapshots.
srcSnapshots := mustGet(listSnapshots(srcExec, src.name))
if len(srcSnapshots) == 0 {
return
} else {
src.latestSnapshot.Store(srcSnapshots[len(srcSnapshots)-1])
}
dstSnapshots, err := listSnapshots(dstExec, dst.name)
if xerr, ok := err.(exitError); ok && strings.Contains(xerr.Stderr, "does not exist") {
err = nil
}
mustDo(err)
// Clone first snapshot if destination has no snapshots.
if len(dstSnapshots) == 0 {
rm.transfer(idx, transferArgs{
Mode: "initial",
SrcLabel: src.SnapshotPath(srcSnapshots[0]),
DstLabel: dst.DatasetPath(),
SendArgs: zsendArgs(rm.sendFlags, src.SnapshotName(srcSnapshots[0])),
RecvArgs: zrecvArgs(rm.initRecvFlags, dst.name),
SrcExec: srcExec, DstExec: dstExec,
})
*replicated = true
continue
} else {
dst.latestSnapshot.Store(dstSnapshots[len(dstSnapshots)-1])
}
// Use last destination snapshot for incremental send.
ss := dstSnapshots[len(dstSnapshots)-1]
i := findString(srcSnapshots, ss)
if i < 0 {
mustDo(fmt.Errorf("snapshot %s does not exist", src.SnapshotPath(ss)))
}
if i+1 == len(srcSnapshots) {
return
}
// TODO: If one of destination datasets is on localhost and
// it is already up-to-date, then use that as the source rather than
// the real source to avoid double bandwidth usage.
// Perform incremental transfer for all snapshots.
rm.transfer(idx, transferArgs{
Mode: "incremental",
SrcLabel: src.SnapshotPath(srcSnapshots[i+1]),
DstLabel: dst.SnapshotPath(srcSnapshots[i]),
SendArgs: zsendArgs(rm.sendFlags, "-i",
src.SnapshotName(srcSnapshots[i]), src.SnapshotName(srcSnapshots[i+1])),
RecvArgs: zrecvArgs(rm.recvFlags, dst.name),
SrcExec: srcExec, DstExec: dstExec,
})
*replicated = true
}
}
type transferArgs struct {
Mode, SrcLabel, DstLabel string
SendArgs, RecvArgs []string
SrcExec, DstExec *executor
}
func (rm *replicaManager) transfer(idx int, args transferArgs) {
// Update status for the latest transfer operation.
status := &rm.statuses[idx]
status.atomicMu.Lock()
status.started.Store(time.Now())
status.finished.Store(time.Time{})
status.transferByteRate.UnmarshalJSON([]byte("{}"))
status.transferredBytes.Store(0)
status.estimatedBytes.Store(0)
status.faultReason.Store("")
status.atomicMu.Unlock()
defer func() { status.finished.Store(time.Now()) }()
// Best-effort estimate at total size.
var sizeBuf bytes.Buffer
drySendArgs := slices.Insert(slices.Clone(args.SendArgs), 2, "-nP")
args.SrcExec.ExecStream(nil, &sizeBuf, drySendArgs...)
for _, line := range strings.Split(sizeBuf.String(), "\n") {
name, value, ok := strings.Cut(strings.TrimSpace(line), "\t")
if ok && name == "size" {
if size, err := strconv.ParseUint(value, 10, 64); err == nil {
status.estimatedBytes.Store(int64(size))
}
}
}
// Perform actual transfer.
now := time.Now()
rm.zs.log.Printf("transferring %s: %s -> %s", args.Mode, args.SrcLabel, args.DstLabel)
r, w := io.Pipe()
defer r.Close()
defer w.Close()
w2 := funcWriter(func(b []byte) (int, error) {
n, err := w.Write(b)
status.transferredBytes.Add(int64(n))
status.transferByteRate.Add(float64(n))
return n, err
})
errc := make(chan error, 2)
go func() {
err := args.SrcExec.ExecStream(nil, w2, args.SendArgs...)
w.CloseWithError(err)
errc <- err
}()
go func() {
err := args.DstExec.ExecStream(r, nil, args.RecvArgs...)
r.CloseWithError(err)
errc <- err
}()
for range 2 {
if err := <-errc; err != nil {
status.faultReason.Store(err.Error())
mustDo(err)
}
}
n := status.transferredBytes.Load()
d := time.Now().Sub(now).Truncate(time.Second)
rm.zs.log.Printf("transfer complete (copied %vB in %v) to destination: %s",
unitconv.FormatPrefix(float64(n), unitconv.IEC, 1), d, args.DstLabel)
}
func zsendArgs(xs ...any) []string {
return flattenArgs(append([]any{"zfs", "send"}, xs...)...)
}
func zrecvArgs(xs ...any) []string {
return flattenArgs(append([]any{"zfs", "recv"}, xs...)...)
}
func flattenArgs(xs ...any) (out []string) {
for _, x := range xs {
switch x := x.(type) {
case string:
out = append(out, x)
case []string:
out = append(out, x...)
default:
panic(fmt.Sprintf("unknown value: %#v", x))
}
}
return out
}