forked from tonistiigi/fsutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
receive_test.go
468 lines (395 loc) · 10.1 KB
/
receive_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
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
package fsutil
import (
"bytes"
"context"
"crypto/sha256"
"hash"
"io"
"os"
"path/filepath"
"sync"
"testing"
"time"
"github.com/opencontainers/go-digest"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/tonistiigi/fsutil/types"
"golang.org/x/sync/errgroup"
)
func TestInvalidExcludePatterns(t *testing.T) {
d, err := tmpDir(changeStream([]string{
"ADD foo file data1",
}))
assert.NoError(t, err)
defer os.RemoveAll(d)
dest := t.TempDir()
ts := newNotificationBuffer()
chs := &changes{fn: ts.HandleChange}
eg, ctx := errgroup.WithContext(context.Background())
s1, s2 := sockPairProto(ctx)
eg.Go(func() error {
defer s1.(*fakeConnProto).closeSend()
err := Send(ctx, s1, NewFS(d, &WalkOpt{ExcludePatterns: []string{"!"}}), nil)
assert.Contains(t, err.Error(), "invalid excludepatterns")
return err
})
eg.Go(func() error {
err := Receive(ctx, s2, dest, ReceiveOpt{
NotifyHashed: chs.HandleChange,
ContentHasher: simpleSHA256Hasher,
})
assert.Contains(t, err.Error(), "error from sender:")
assert.Contains(t, err.Error(), "invalid excludepatterns")
return err
})
errCh := make(chan error)
go func() {
errCh <- eg.Wait()
}()
select {
case <-time.After(15 * time.Second):
t.Fatal("timeout")
case err = <-errCh:
assert.Contains(t, err.Error(), "invalid excludepatterns")
}
}
func TestCopyWithSubDir(t *testing.T) {
requiresRoot(t)
d, err := tmpDir(changeStream([]string{
"ADD foo dir",
"ADD foo/bar file data1",
}))
assert.NoError(t, err)
defer os.RemoveAll(d)
dest := t.TempDir()
eg, ctx := errgroup.WithContext(context.Background())
s1, s2 := sockPairProto(ctx)
eg.Go(func() error {
defer s1.(*fakeConnProto).closeSend()
subdir, err := SubDirFS([]Dir{{FS: NewFS(d, &WalkOpt{}), Stat: types.Stat{Path: "sub", Mode: uint32(os.ModeDir | 0755)}}})
if err != nil {
return err
}
return Send(ctx, s1, subdir, nil)
})
eg.Go(func() error {
return Receive(ctx, s2, dest, ReceiveOpt{})
})
err = eg.Wait()
assert.NoError(t, err)
dt, err := os.ReadFile(filepath.Join(dest, "sub/foo/bar"))
assert.NoError(t, err)
assert.Equal(t, "data1", string(dt))
}
func TestCopySwitchDirToFile(t *testing.T) {
d, err := tmpDir(changeStream([]string{
"ADD foo file data1",
}))
assert.NoError(t, err)
defer os.RemoveAll(d)
dest, err := tmpDir(changeStream([]string{
"ADD foo dir",
"ADD foo/bar dile data2",
}))
assert.NoError(t, err)
defer os.RemoveAll(d)
copy := func(src, dest string) (*changes, error) {
ts := newNotificationBuffer()
chs := &changes{fn: ts.HandleChange}
eg, ctx := errgroup.WithContext(context.Background())
s1, s2 := sockPairProto(ctx)
eg.Go(func() error {
defer s1.(*fakeConnProto).closeSend()
return Send(ctx, s1, NewFS(src, &WalkOpt{
Map: func(_ string, s *types.Stat) MapResult {
s.Uid = 0
s.Gid = 0
return MapResultKeep
},
}), nil)
})
eg.Go(func() error {
return Receive(ctx, s2, dest, ReceiveOpt{
NotifyHashed: chs.HandleChange,
ContentHasher: simpleSHA256Hasher,
Filter: func(_ string, s *types.Stat) bool {
s.Uid = uint32(os.Getuid())
s.Gid = uint32(os.Getgid())
return true
},
})
})
if err := eg.Wait(); err != nil {
return nil, err
}
return chs, nil
}
chs, err := copy(d, dest)
require.NoError(t, err)
k, ok := chs.c["foo"]
require.True(t, ok)
require.Equal(t, k, ChangeKindAdd)
require.Equal(t, len(chs.c), 1)
b := &bytes.Buffer{}
err = Walk(context.Background(), dest, nil, bufWalk(b))
assert.NoError(t, err)
assert.Equal(t, string(b.Bytes()), `file foo
`)
}
func TestCopySimple(t *testing.T) {
d, err := tmpDir(changeStream([]string{
"ADD foo file data1",
"ADD foo2 file dat2",
"ADD zzz dir",
"ADD zzz/aa file data3",
"ADD zzz/bb dir",
"ADD zzz/bb/cc dir",
"ADD zzz/bb/cc/dd symlink ../../",
"ADD zzz.aa zzdata",
}))
assert.NoError(t, err)
defer os.RemoveAll(d)
dest := t.TempDir()
ts := newNotificationBuffer()
chs := &changes{fn: ts.HandleChange}
eg, ctx := errgroup.WithContext(context.Background())
s1, s2 := sockPairProto(ctx)
tm := time.Now().Truncate(time.Hour)
eg.Go(func() error {
defer s1.(*fakeConnProto).closeSend()
return Send(ctx, s1, NewFS(d, &WalkOpt{
Map: func(_ string, s *types.Stat) MapResult {
s.Uid = 0
s.Gid = 0
return MapResultKeep
},
}), nil)
})
eg.Go(func() error {
return Receive(ctx, s2, dest, ReceiveOpt{
NotifyHashed: chs.HandleChange,
ContentHasher: simpleSHA256Hasher,
Filter: func(p string, s *types.Stat) bool {
s.Uid = uint32(os.Getuid())
s.Gid = uint32(os.Getgid())
s.ModTime = tm.UnixNano()
return true
},
})
})
assert.NoError(t, eg.Wait())
b := &bytes.Buffer{}
err = Walk(context.Background(), dest, nil, bufWalk(b))
assert.NoError(t, err)
assert.Equal(t, string(b.Bytes()), `file foo
file foo2
dir zzz
file zzz/aa
dir zzz/bb
dir zzz/bb/cc
symlink:../../ zzz/bb/cc/dd
file zzz.aa
`)
dt, err := os.ReadFile(filepath.Join(dest, "zzz/aa"))
assert.NoError(t, err)
assert.Equal(t, "data3", string(dt))
dt, err = os.ReadFile(filepath.Join(dest, "foo2"))
assert.NoError(t, err)
assert.Equal(t, "dat2", string(dt))
fi, err := os.Stat(filepath.Join(dest, "foo2"))
assert.NoError(t, err)
assert.Equal(t, tm, fi.ModTime())
h, ok := ts.Hash("zzz/aa")
assert.True(t, ok)
assert.Equal(t, digest.Digest("sha256:99b6ef96ee0572b5b3a4eb28f00b715d820bfd73836e59cc1565e241f4d1bb2f"), h)
h, ok = ts.Hash("foo2")
assert.True(t, ok)
assert.Equal(t, digest.Digest("sha256:dd2529f7749ba45ea55de3b2e10086d6494cc45a94e57650c2882a6a14b4ff32"), h)
h, ok = ts.Hash("zzz/bb/cc/dd")
assert.True(t, ok)
assert.Equal(t, digest.Digest("sha256:eca07e8f2d09bd574ea2496312e6de1685ef15b8e6a49a534ed9e722bcac8adc"), h)
k, ok := chs.c["zzz/aa"]
assert.Equal(t, ok, true)
assert.Equal(t, k, ChangeKindAdd)
err = os.WriteFile(filepath.Join(d, "zzz/bb/cc/foo"), []byte("data5"), 0600)
assert.NoError(t, err)
err = os.RemoveAll(filepath.Join(d, "foo2"))
assert.NoError(t, err)
chs = &changes{fn: ts.HandleChange}
eg, ctx = errgroup.WithContext(context.Background())
s1, s2 = sockPairProto(ctx)
eg.Go(func() error {
defer s1.(*fakeConnProto).closeSend()
return Send(ctx, s1, NewFS(d, &WalkOpt{
Map: func(_ string, s *types.Stat) MapResult {
s.Uid = 0
s.Gid = 0
return MapResultKeep
},
}), nil)
})
eg.Go(func() error {
return Receive(ctx, s2, dest, ReceiveOpt{
NotifyHashed: chs.HandleChange,
ContentHasher: simpleSHA256Hasher,
Filter: func(_ string, s *types.Stat) bool {
s.Uid = uint32(os.Getuid())
s.Gid = uint32(os.Getgid())
s.ModTime = tm.UnixNano()
return true
},
})
})
assert.NoError(t, eg.Wait())
b = &bytes.Buffer{}
err = Walk(context.Background(), dest, nil, bufWalk(b))
assert.NoError(t, err)
assert.Equal(t, string(b.Bytes()), `file foo
dir zzz
file zzz/aa
dir zzz/bb
dir zzz/bb/cc
symlink:../../ zzz/bb/cc/dd
file zzz/bb/cc/foo
file zzz.aa
`)
dt, err = os.ReadFile(filepath.Join(dest, "zzz/bb/cc/foo"))
assert.NoError(t, err)
assert.Equal(t, "data5", string(dt))
h, ok = ts.Hash("zzz/bb/cc/dd")
assert.True(t, ok)
assert.Equal(t, digest.Digest("sha256:eca07e8f2d09bd574ea2496312e6de1685ef15b8e6a49a534ed9e722bcac8adc"), h)
h, ok = ts.Hash("zzz/bb/cc/foo")
assert.True(t, ok)
assert.Equal(t, digest.Digest("sha256:cd14a931fc2e123ded338093f2864b173eecdee578bba6ec24d0724272326c3a"), h)
_, ok = ts.Hash("foo2")
assert.False(t, ok)
k, ok = chs.c["foo2"]
assert.Equal(t, ok, true)
assert.Equal(t, k, ChangeKindDelete)
k, ok = chs.c["zzz/bb/cc/foo"]
assert.Equal(t, ok, true)
assert.Equal(t, k, ChangeKindAdd)
_, ok = chs.c["zzz/aa"]
assert.Equal(t, ok, false)
_, ok = chs.c["zzz.aa"]
assert.Equal(t, ok, false)
}
func sockPairProto(ctx context.Context) (Stream, Stream) {
c1 := make(chan []byte, 32)
c2 := make(chan []byte, 32)
return &fakeConnProto{ctx, c1, c2}, &fakeConnProto{ctx, c2, c1}
}
//nolint:unused
type fakeConn struct {
ctx context.Context
recvChan chan *types.Packet
sendChan chan *types.Packet
}
//nolint:unused
func (fc *fakeConn) Context() context.Context {
return fc.ctx
}
//nolint:unused
func (fc *fakeConn) RecvMsg(m interface{}) error {
p, ok := m.(*types.Packet)
if !ok {
return errors.Errorf("invalid msg: %#v", m)
}
select {
case <-fc.ctx.Done():
return fc.ctx.Err()
case p2 := <-fc.recvChan:
*p = *p2
return nil
}
}
//nolint:unused
func (fc *fakeConn) SendMsg(m interface{}) error {
p, ok := m.(*types.Packet)
if !ok {
return errors.Errorf("invalid msg: %#v", m)
}
p2 := *p
p2.Data = append([]byte{}, p2.Data...)
select {
case <-fc.ctx.Done():
return fc.ctx.Err()
case fc.sendChan <- &p2:
return nil
}
}
type fakeConnProto struct {
ctx context.Context
recvChan chan []byte
sendChan chan []byte
}
func (fc *fakeConnProto) Context() context.Context {
return fc.ctx
}
func (fc *fakeConnProto) RecvMsg(m interface{}) error {
p, ok := m.(*types.Packet)
if !ok {
return errors.Errorf("invalid msg: %#v", m)
}
select {
case <-fc.ctx.Done():
return fc.ctx.Err()
case dt, ok := <-fc.recvChan:
if !ok {
return io.EOF
}
return p.Unmarshal(dt)
}
}
func (fc *fakeConnProto) SendMsg(m interface{}) error {
p, ok := m.(*types.Packet)
if !ok {
return errors.Errorf("invalid msg: %#v", m)
}
dt, err := p.Marshal()
if err != nil {
return err
}
select {
case <-fc.ctx.Done():
return fc.ctx.Err()
case fc.sendChan <- dt:
return nil
}
}
func (fc *fakeConnProto) closeSend() {
close(fc.sendChan)
}
type changes struct {
c map[string]ChangeKind
fn ChangeFunc
mu sync.Mutex
}
func (c *changes) HandleChange(kind ChangeKind, p string, fi os.FileInfo, err error) error {
c.mu.Lock()
if c.c == nil {
c.c = make(map[string]ChangeKind)
}
c.c[p] = kind
c.mu.Unlock()
return c.fn(kind, p, fi, err)
}
func simpleSHA256Hasher(s *types.Stat) (hash.Hash, error) {
h := sha256.New()
ss := *s
ss.ModTime = 0
// Unlike Linux, on FreeBSD's stat() call returns -1 in st_rdev for regular files
ss.Devminor = 0
ss.Devmajor = 0
if os.FileMode(ss.Mode)&os.ModeSymlink != 0 {
ss.Mode = ss.Mode | 0777
}
dt, err := ss.Marshal()
if err != nil {
return nil, err
}
h.Write(dt)
return h, nil
}