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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
|
// Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package p9test
import (
"bytes"
"fmt"
"io"
"math/rand"
"os"
"reflect"
"strings"
"syscall"
"testing"
"time"
"github.com/golang/mock/gomock"
"gvisor.dev/gvisor/pkg/fd"
"gvisor.dev/gvisor/pkg/p9"
"gvisor.dev/gvisor/pkg/sync"
)
func TestPanic(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
// Create a new root.
d := h.NewDirectory(nil)(nil)
defer d.Close() // Needed manually.
h.Attacher.EXPECT().Attach().Return(d, nil).Do(func() {
// Panic here, and ensure that we get back EFAULT.
panic("handler")
})
// Attach to the client.
if _, err := c.Attach("/"); err != syscall.EFAULT {
t.Fatalf("got attach err %v, want EFAULT", err)
}
}
func TestAttachNoLeak(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
// Create a new root.
d := h.NewDirectory(nil)(nil)
h.Attacher.EXPECT().Attach().Return(d, nil).Times(1)
// Attach to the client.
f, err := c.Attach("/")
if err != nil {
t.Fatalf("got attach err %v, want nil", err)
}
// Don't close the file. This should be closed automatically when the
// client disconnects. The mock asserts that everything is closed
// exactly once. This statement just removes the unused variable error.
_ = f
}
func TestBadAttach(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
// Return an error on attach.
h.Attacher.EXPECT().Attach().Return(nil, syscall.EINVAL).Times(1)
// Attach to the client.
if _, err := c.Attach("/"); err != syscall.EINVAL {
t.Fatalf("got attach err %v, want syscall.EINVAL", err)
}
}
func TestWalkAttach(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
// Create a new root.
d := h.NewDirectory(map[string]Generator{
"a": h.NewDirectory(map[string]Generator{
"b": h.NewFile(),
}),
})(nil)
h.Attacher.EXPECT().Attach().Return(d, nil).Times(1)
// Attach to the client as a non-root, and ensure that the walk above
// occurs as expected. We should get back b, and all references should
// be dropped when the file is closed.
f, err := c.Attach("/a/b")
if err != nil {
t.Fatalf("got attach err %v, want nil", err)
}
defer f.Close()
// Check that's a regular file.
if _, _, attr, err := f.GetAttr(p9.AttrMaskAll()); err != nil {
t.Errorf("got err %v, want nil", err)
} else if !attr.Mode.IsRegular() {
t.Errorf("got mode %v, want regular file", err)
}
}
// newTypeMap returns a new type map dictionary.
func newTypeMap(h *Harness) map[string]Generator {
return map[string]Generator{
"directory": h.NewDirectory(map[string]Generator{}),
"file": h.NewFile(),
"symlink": h.NewSymlink(),
"block-device": h.NewBlockDevice(),
"character-device": h.NewCharacterDevice(),
"named-pipe": h.NewNamedPipe(),
"socket": h.NewSocket(),
}
}
// newRoot returns a new root filesystem.
//
// This is set up in a deterministic way for testing most operations.
//
// The represented file system looks like:
// - file
// - symlink
// - directory
// ...
// + one
// - file
// - symlink
// - directory
// ...
// + two
// - file
// - symlink
// - directory
// ...
// + three
// - file
// - symlink
// - directory
// ...
func newRoot(h *Harness, c *p9.Client) (*Mock, p9.File) {
root := newTypeMap(h)
one := newTypeMap(h)
two := newTypeMap(h)
three := newTypeMap(h)
one["two"] = h.NewDirectory(two) // Will be nested in one.
root["one"] = h.NewDirectory(one) // Top level.
root["three"] = h.NewDirectory(three) // Alternate top-level.
// Create a new root.
rootBackend := h.NewDirectory(root)(nil)
h.Attacher.EXPECT().Attach().Return(rootBackend, nil)
// Attach to the client.
r, err := c.Attach("/")
if err != nil {
h.t.Fatalf("got attach err %v, want nil", err)
}
return rootBackend, r
}
func allInvalidNames(from string) []string {
return []string{
from + "/other",
from + "/..",
from + "/.",
from + "/",
"other/" + from,
"/" + from,
"./" + from,
"../" + from,
".",
"..",
"/",
"",
}
}
func TestWalkInvalid(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
// Run relevant tests.
for name := range newTypeMap(h) {
// These are all the various ways that one might attempt to
// construct compound paths. They should all be rejected, as
// any compound that contains a / is not allowed, as well as
// the singular paths of '.' and '..'.
if _, _, err := root.Walk([]string{".", name}); err != syscall.EINVAL {
t.Errorf("Walk through . %s wanted EINVAL, got %v", name, err)
}
if _, _, err := root.Walk([]string{"..", name}); err != syscall.EINVAL {
t.Errorf("Walk through . %s wanted EINVAL, got %v", name, err)
}
if _, _, err := root.Walk([]string{name, "."}); err != syscall.EINVAL {
t.Errorf("Walk through %s . wanted EINVAL, got %v", name, err)
}
if _, _, err := root.Walk([]string{name, ".."}); err != syscall.EINVAL {
t.Errorf("Walk through %s .. wanted EINVAL, got %v", name, err)
}
for _, invalidName := range allInvalidNames(name) {
if _, _, err := root.Walk([]string{invalidName}); err != syscall.EINVAL {
t.Errorf("Walk through %s wanted EINVAL, got %v", invalidName, err)
}
}
wantErr := syscall.EINVAL
if name == "directory" {
// We can attempt a walk through a directory. However,
// we should never see a file named "other", so we
// expect this to return ENOENT.
wantErr = syscall.ENOENT
}
if _, _, err := root.Walk([]string{name, "other"}); err != wantErr {
t.Errorf("Walk through %s/other wanted %v, got %v", name, wantErr, err)
}
// Do a successful walk.
_, f, err := root.Walk([]string{name})
if err != nil {
t.Errorf("Walk to %s wanted nil, got %v", name, err)
}
defer f.Close()
local := h.Pop(f)
// Check that the file matches.
_, localMask, localAttr, localErr := local.GetAttr(p9.AttrMaskAll())
if _, mask, attr, err := f.GetAttr(p9.AttrMaskAll()); mask != localMask || attr != localAttr || err != localErr {
t.Errorf("GetAttr got (%v, %v, %v), wanted (%v, %v, %v)",
mask, attr, err, localMask, localAttr, localErr)
}
// Ensure we can't walk backwards.
if _, _, err := f.Walk([]string{"."}); err != syscall.EINVAL {
t.Errorf("Walk through %s/. wanted EINVAL, got %v", name, err)
}
if _, _, err := f.Walk([]string{".."}); err != syscall.EINVAL {
t.Errorf("Walk through %s/.. wanted EINVAL, got %v", name, err)
}
}
}
// fileGenerator is a function to generate files via walk or create.
//
// Examples are:
// - walkHelper
// - walkAndOpenHelper
// - createHelper
type fileGenerator func(*Harness, string, p9.File) (*Mock, *Mock, p9.File)
// walkHelper walks to the given file.
//
// The backends of the parent and walked file are returned, as well as the
// walked client file.
func walkHelper(h *Harness, name string, dir p9.File) (parentBackend *Mock, walkedBackend *Mock, walked p9.File) {
_, parent, err := dir.Walk(nil)
if err != nil {
h.t.Fatalf("Walk(nil) got err %v, want nil", err)
}
defer parent.Close()
parentBackend = h.Pop(parent)
_, walked, err = parent.Walk([]string{name})
if err != nil {
h.t.Fatalf("Walk(%s) got err %v, want nil", name, err)
}
walkedBackend = h.Pop(walked)
return parentBackend, walkedBackend, walked
}
// walkAndOpenHelper additionally opens the walked file, if possible.
func walkAndOpenHelper(h *Harness, name string, dir p9.File) (*Mock, *Mock, p9.File) {
parentBackend, walkedBackend, walked := walkHelper(h, name, dir)
if p9.CanOpen(walkedBackend.Attr.Mode) {
// Open for all file types that we can. We stick to a read-only
// open here because directories may not be opened otherwise.
walkedBackend.EXPECT().Open(p9.ReadOnly).Times(1)
if _, _, _, err := walked.Open(p9.ReadOnly); err != nil {
h.t.Errorf("got open err %v, want nil", err)
}
} else {
// ... or assert an error for others.
if _, _, _, err := walked.Open(p9.ReadOnly); err != syscall.EINVAL {
h.t.Errorf("got open err %v, want EINVAL", err)
}
}
return parentBackend, walkedBackend, walked
}
// createHelper creates the given file and returns the parent directory,
// created file and client file, which must be closed when done.
func createHelper(h *Harness, name string, dir p9.File) (*Mock, *Mock, p9.File) {
// Clone the directory first, since Create replaces the existing file.
// We change the type after calling create.
_, dirThenFile, err := dir.Walk(nil)
if err != nil {
h.t.Fatalf("got walk err %v, want nil", err)
}
// Create a new server-side file. On the server-side, the a new file is
// returned from a create call. The client will reuse the same file,
// but we still expect the normal chain of closes. This complicates
// things a bit because the "parent" will always chain to the cloned
// dir above.
dirBackend := h.Pop(dirThenFile) // New backend directory.
newFile := h.NewFile()(dirBackend) // New file with backend parent.
dirBackend.EXPECT().Create(name, gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, newFile, newFile.QID, uint32(0), nil)
// Create via the client.
_, dirThenFile, _, _, err = dirThenFile.Create(name, p9.ReadOnly, 0, 0, 0)
if err != nil {
h.t.Fatalf("got create err %v, want nil", err)
}
// Ensure subsequent walks succeed.
dirBackend.AddChild(name, h.NewFile())
return dirBackend, newFile, dirThenFile
}
// deprecatedRemover allows us to access the deprecated Remove operation within
// the p9.File client object.
type deprecatedRemover interface {
Remove() error
}
// checkDeleted asserts that relevant methods fail for an unlinked file.
//
// This function will close the file at the end.
func checkDeleted(h *Harness, file p9.File) {
defer file.Close() // See doc.
if _, _, _, err := file.Open(p9.ReadOnly); err != syscall.EINVAL {
h.t.Errorf("open while deleted, got %v, want EINVAL", err)
}
if _, _, _, _, err := file.Create("created", p9.ReadOnly, 0, 0, 0); err != syscall.EINVAL {
h.t.Errorf("create while deleted, got %v, want EINVAL", err)
}
if _, err := file.Symlink("old", "new", 0, 0); err != syscall.EINVAL {
h.t.Errorf("symlink while deleted, got %v, want EINVAL", err)
}
// N.B. This link is technically invalid, but if a call to link is
// actually made in the backend then the mock will panic.
if err := file.Link(file, "new"); err != syscall.EINVAL {
h.t.Errorf("link while deleted, got %v, want EINVAL", err)
}
if err := file.RenameAt("src", file, "dst"); err != syscall.EINVAL {
h.t.Errorf("renameAt while deleted, got %v, want EINVAL", err)
}
if err := file.UnlinkAt("file", 0); err != syscall.EINVAL {
h.t.Errorf("unlinkAt while deleted, got %v, want EINVAL", err)
}
if err := file.Rename(file, "dst"); err != syscall.EINVAL {
h.t.Errorf("rename while deleted, got %v, want EINVAL", err)
}
if _, err := file.Readlink(); err != syscall.EINVAL {
h.t.Errorf("readlink while deleted, got %v, want EINVAL", err)
}
if _, err := file.Mkdir("dir", p9.ModeDirectory, 0, 0); err != syscall.EINVAL {
h.t.Errorf("mkdir while deleted, got %v, want EINVAL", err)
}
if _, err := file.Mknod("dir", p9.ModeDirectory, 0, 0, 0, 0); err != syscall.EINVAL {
h.t.Errorf("mknod while deleted, got %v, want EINVAL", err)
}
if _, err := file.Readdir(0, 1); err != syscall.EINVAL {
h.t.Errorf("readdir while deleted, got %v, want EINVAL", err)
}
if _, err := file.Connect(p9.ConnectFlags(0)); err != syscall.EINVAL {
h.t.Errorf("connect while deleted, got %v, want EINVAL", err)
}
// The remove method is technically deprecated, but we want to ensure
// that it still checks for deleted appropriately. We must first clone
// the file because remove is equivalent to close.
_, newFile, err := file.Walk(nil)
if err == syscall.EBUSY {
// We can't walk from here because this reference is open
// already. Okay, we will also have unopened cases through
// TestUnlink, just skip the remove operation for now.
return
} else if err != nil {
h.t.Fatalf("clone failed, got %v, want nil", err)
}
if err := newFile.(deprecatedRemover).Remove(); err != syscall.EINVAL {
h.t.Errorf("remove while deleted, got %v, want EINVAL", err)
}
}
// deleter is a function to remove a file.
type deleter func(parent p9.File, name string) error
// unlinkAt is a deleter.
func unlinkAt(parent p9.File, name string) error {
// Call unlink. Note that a filesystem may normally impose additional
// constaints on unlinkat success, such as ensuring that a directory is
// empty, requiring AT_REMOVEDIR in flags to remove a directory, etc.
// None of that is required internally (entire trees can be marked
// deleted when this operation succeeds), so the mock will succeed.
return parent.UnlinkAt(name, 0)
}
// remove is a deleter.
func remove(parent p9.File, name string) error {
// See notes above re: remove.
_, newFile, err := parent.Walk([]string{name})
if err != nil {
// Should not be expected.
return err
}
// Do the actual remove.
if err := newFile.(deprecatedRemover).Remove(); err != nil {
return err
}
// Ensure that the remove closed the file.
if err := newFile.(deprecatedRemover).Remove(); err != syscall.EBADF {
return syscall.EBADF // Propagate this code.
}
return nil
}
// unlinkHelper unlinks the noted path, and ensures that all relevant
// operations on that path, acquired from multiple paths, start failing.
func unlinkHelper(h *Harness, root p9.File, targetNames []string, targetGen fileGenerator, deleteFn deleter) {
// name is the file to be unlinked.
name := targetNames[len(targetNames)-1]
// Walk to the directory containing the target.
_, parent, err := root.Walk(targetNames[:len(targetNames)-1])
if err != nil {
h.t.Fatalf("got walk err %v, want nil", err)
}
defer parent.Close()
parentBackend := h.Pop(parent)
// Walk to or generate the target file.
_, _, target := targetGen(h, name, parent)
defer checkDeleted(h, target)
// Walk to a second reference.
_, second, err := parent.Walk([]string{name})
if err != nil {
h.t.Fatalf("got walk err %v, want nil", err)
}
defer checkDeleted(h, second)
// Walk to a third reference, from the start.
_, third, err := root.Walk(targetNames)
if err != nil {
h.t.Fatalf("got walk err %v, want nil", err)
}
defer checkDeleted(h, third)
// This will be translated in the backend to an unlinkat.
parentBackend.EXPECT().UnlinkAt(name, uint32(0)).Return(nil)
// Actually perform the deletion.
if err := deleteFn(parent, name); err != nil {
h.t.Fatalf("got delete err %v, want nil", err)
}
}
func unlinkTest(t *testing.T, targetNames []string, targetGen fileGenerator) {
t.Run(fmt.Sprintf("unlinkAt(%s)", strings.Join(targetNames, "/")), func(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
unlinkHelper(h, root, targetNames, targetGen, unlinkAt)
})
t.Run(fmt.Sprintf("remove(%s)", strings.Join(targetNames, "/")), func(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
unlinkHelper(h, root, targetNames, targetGen, remove)
})
}
func TestUnlink(t *testing.T) {
// Unlink all files.
for name := range newTypeMap(nil) {
unlinkTest(t, []string{name}, walkHelper)
unlinkTest(t, []string{name}, walkAndOpenHelper)
unlinkTest(t, []string{"one", name}, walkHelper)
unlinkTest(t, []string{"one", name}, walkAndOpenHelper)
unlinkTest(t, []string{"one", "two", name}, walkHelper)
unlinkTest(t, []string{"one", "two", name}, walkAndOpenHelper)
}
// Unlink a directory.
unlinkTest(t, []string{"one"}, walkHelper)
unlinkTest(t, []string{"one"}, walkAndOpenHelper)
unlinkTest(t, []string{"one", "two"}, walkHelper)
unlinkTest(t, []string{"one", "two"}, walkAndOpenHelper)
// Unlink created files.
unlinkTest(t, []string{"created"}, createHelper)
unlinkTest(t, []string{"one", "created"}, createHelper)
unlinkTest(t, []string{"one", "two", "created"}, createHelper)
}
func TestUnlinkAtInvalid(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
for name := range newTypeMap(nil) {
for _, invalidName := range allInvalidNames(name) {
if err := root.UnlinkAt(invalidName, 0); err != syscall.EINVAL {
t.Errorf("got %v for name %q, want EINVAL", err, invalidName)
}
}
}
}
// expectRenamed asserts an ordered sequence of rename calls, based on all the
// elements in elements being the source, and the first element therein
// changing to dstName, parented at dstParent.
func expectRenamed(file *Mock, elements []string, dstParent *Mock, dstName string) *gomock.Call {
if len(elements) > 0 {
// Recurse to the parent, if necessary.
call := expectRenamed(file.parent, elements[:len(elements)-1], dstParent, dstName)
// Recursive case: this element is unchanged, but should have
// it's hook called after the parent.
return file.EXPECT().Renamed(file.parent, elements[len(elements)-1]).Do(func(p p9.File, _ string) {
file.parent = p.(*Mock)
}).After(call)
}
// Base case: this is the changed element.
return file.EXPECT().Renamed(dstParent, dstName).Do(func(p p9.File, name string) {
file.parent = p.(*Mock)
})
}
// renamer is a rename function.
type renamer func(h *Harness, srcParent, dstParent p9.File, origName, newName string, selfRename bool) error
// renameAt is a renamer.
func renameAt(_ *Harness, srcParent, dstParent p9.File, srcName, dstName string, selfRename bool) error {
return srcParent.RenameAt(srcName, dstParent, dstName)
}
// rename is a renamer.
func rename(h *Harness, srcParent, dstParent p9.File, srcName, dstName string, selfRename bool) error {
_, f, err := srcParent.Walk([]string{srcName})
if err != nil {
return err
}
defer f.Close()
if !selfRename {
backend := h.Pop(f)
backend.EXPECT().Renamed(gomock.Any(), dstName).Do(func(p p9.File, name string) {
backend.parent = p.(*Mock) // Required for close ordering.
})
}
return f.Rename(dstParent, dstName)
}
// renameHelper executes a rename, and asserts that all relevant elements
// receive expected notifications. If overwriting a file, this includes
// ensuring that the target has been appropriately marked as unlinked.
func renameHelper(h *Harness, root p9.File, srcNames []string, dstNames []string, target fileGenerator, renameFn renamer) {
// Walk to the directory containing the target.
srcQID, targetParent, err := root.Walk(srcNames[:len(srcNames)-1])
if err != nil {
h.t.Fatalf("got walk err %v, want nil", err)
}
defer targetParent.Close()
targetParentBackend := h.Pop(targetParent)
// Walk to or generate the target file.
_, targetBackend, src := target(h, srcNames[len(srcNames)-1], targetParent)
defer src.Close()
// Walk to a second reference.
_, second, err := targetParent.Walk([]string{srcNames[len(srcNames)-1]})
if err != nil {
h.t.Fatalf("got walk err %v, want nil", err)
}
defer second.Close()
secondBackend := h.Pop(second)
// Walk to a third reference, from the start.
_, third, err := root.Walk(srcNames)
if err != nil {
h.t.Fatalf("got walk err %v, want nil", err)
}
defer third.Close()
thirdBackend := h.Pop(third)
// Find the common suffix to identify the rename parent.
var (
renameDestPath []string
renameSrcPath []string
selfRename bool
)
for i := 1; i <= len(srcNames) && i <= len(dstNames); i++ {
if srcNames[len(srcNames)-i] != dstNames[len(dstNames)-i] {
// Take the full prefix of dstNames up until this
// point, including the first mismatched name. The
// first mismatch must be the renamed entry.
renameDestPath = dstNames[:len(dstNames)-i+1]
renameSrcPath = srcNames[:len(srcNames)-i+1]
// Does the renameDestPath fully contain the
// renameSrcPath here? If yes, then this is a mismatch.
// We can't rename the src to some subpath of itself.
if len(renameDestPath) > len(renameSrcPath) &&
reflect.DeepEqual(renameDestPath[:len(renameSrcPath)], renameSrcPath) {
renameDestPath = nil
renameSrcPath = nil
continue
}
break
}
}
if len(renameSrcPath) == 0 || len(renameDestPath) == 0 {
// This must be a rename to self, or a tricky look-alike. This
// happens iff we fail to find a suitable divergence in the two
// paths. It's a true self move if the path length is the same.
renameDestPath = dstNames
renameSrcPath = srcNames
selfRename = len(srcNames) == len(dstNames)
}
// Walk to the source parent.
_, srcParent, err := root.Walk(renameSrcPath[:len(renameSrcPath)-1])
if err != nil {
h.t.Fatalf("got walk err %v, want nil", err)
}
defer srcParent.Close()
srcParentBackend := h.Pop(srcParent)
// Walk to the destination parent.
_, dstParent, err := root.Walk(renameDestPath[:len(renameDestPath)-1])
if err != nil {
h.t.Fatalf("got walk err %v, want nil", err)
}
defer dstParent.Close()
dstParentBackend := h.Pop(dstParent)
// expectedErr is the result of the rename operation.
var expectedErr error
// Walk to the target file, if one exists.
dstQID, dst, err := root.Walk(renameDestPath)
if err == nil {
if !selfRename && srcQID[0].Type == dstQID[0].Type {
// If there is a destination file, and is it of the
// same type as the source file, then we expect the
// rename to succeed. We expect the destination file to
// be deleted, so we run a deletion test on it in this
// case.
defer checkDeleted(h, dst)
} else {
if !selfRename {
// If the type is different than the
// destination, then we expect the rename to
// fail. We expect ensure that this is
// returned.
expectedErr = syscall.EINVAL
} else {
// This is the file being renamed to itself.
// This is technically allowed and a no-op, but
// all the triggers will fire.
}
dst.Close()
}
}
dstName := renameDestPath[len(renameDestPath)-1] // Renamed element.
srcName := renameSrcPath[len(renameSrcPath)-1] // Renamed element.
if expectedErr == nil && !selfRename {
// Expect all to be renamed appropriately. Note that if this is
// a final file being renamed, then we expect the file to be
// called with the new parent. If not, then we expect the
// rename hook to be called, but the parent will remain
// unchanged.
elements := srcNames[len(renameSrcPath):]
expectRenamed(targetBackend, elements, dstParentBackend, dstName)
expectRenamed(secondBackend, elements, dstParentBackend, dstName)
expectRenamed(thirdBackend, elements, dstParentBackend, dstName)
// The target parent has also been opened, and may be moved
// directly or indirectly.
if len(elements) > 1 {
expectRenamed(targetParentBackend, elements[:len(elements)-1], dstParentBackend, dstName)
}
}
// Expect the rename if it's not the same file. Note that like unlink,
// renames are always translated to the at variant in the backend.
if !selfRename {
srcParentBackend.EXPECT().RenameAt(srcName, dstParentBackend, dstName).Return(expectedErr)
}
// Perform the actual rename; everything has been lined up.
if err := renameFn(h, srcParent, dstParent, srcName, dstName, selfRename); err != expectedErr {
h.t.Fatalf("got rename err %v, want %v", err, expectedErr)
}
}
func renameTest(t *testing.T, srcNames []string, dstNames []string, target fileGenerator) {
t.Run(fmt.Sprintf("renameAt(%s->%s)", strings.Join(srcNames, "/"), strings.Join(dstNames, "/")), func(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
renameHelper(h, root, srcNames, dstNames, target, renameAt)
})
t.Run(fmt.Sprintf("rename(%s->%s)", strings.Join(srcNames, "/"), strings.Join(dstNames, "/")), func(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
renameHelper(h, root, srcNames, dstNames, target, rename)
})
}
func TestRename(t *testing.T) {
// In-directory rename, simple case.
for name := range newTypeMap(nil) {
// Within the root.
renameTest(t, []string{name}, []string{"renamed"}, walkHelper)
renameTest(t, []string{name}, []string{"renamed"}, walkAndOpenHelper)
// Within a subdirectory.
renameTest(t, []string{"one", name}, []string{"one", "renamed"}, walkHelper)
renameTest(t, []string{"one", name}, []string{"one", "renamed"}, walkAndOpenHelper)
}
// ... with created files.
renameTest(t, []string{"created"}, []string{"renamed"}, createHelper)
renameTest(t, []string{"one", "created"}, []string{"one", "renamed"}, createHelper)
// Across directories.
for name := range newTypeMap(nil) {
// Down one level.
renameTest(t, []string{"one", name}, []string{"one", "two", "renamed"}, walkHelper)
renameTest(t, []string{"one", name}, []string{"one", "two", "renamed"}, walkAndOpenHelper)
// Up one level.
renameTest(t, []string{"one", "two", name}, []string{"one", "renamed"}, walkHelper)
renameTest(t, []string{"one", "two", name}, []string{"one", "renamed"}, walkAndOpenHelper)
// Across at the same level.
renameTest(t, []string{"one", name}, []string{"three", "renamed"}, walkHelper)
renameTest(t, []string{"one", name}, []string{"three", "renamed"}, walkAndOpenHelper)
}
// ... with created files.
renameTest(t, []string{"one", "created"}, []string{"one", "two", "renamed"}, createHelper)
renameTest(t, []string{"one", "two", "created"}, []string{"one", "renamed"}, createHelper)
renameTest(t, []string{"one", "created"}, []string{"three", "renamed"}, createHelper)
// Renaming parents.
for name := range newTypeMap(nil) {
// Rename a parent.
renameTest(t, []string{"one", name}, []string{"renamed", name}, walkHelper)
renameTest(t, []string{"one", name}, []string{"renamed", name}, walkAndOpenHelper)
// Rename a super parent.
renameTest(t, []string{"one", "two", name}, []string{"renamed", name}, walkHelper)
renameTest(t, []string{"one", "two", name}, []string{"renamed", name}, walkAndOpenHelper)
}
// ... with created files.
renameTest(t, []string{"one", "created"}, []string{"renamed", "created"}, createHelper)
renameTest(t, []string{"one", "two", "created"}, []string{"renamed", "created"}, createHelper)
// Over existing files, including itself.
for name := range newTypeMap(nil) {
for other := range newTypeMap(nil) {
// Overwrite the noted file (may be itself).
renameTest(t, []string{"one", name}, []string{"one", other}, walkHelper)
renameTest(t, []string{"one", name}, []string{"one", other}, walkAndOpenHelper)
// Overwrite other files in another directory.
renameTest(t, []string{"one", name}, []string{"one", "two", other}, walkHelper)
renameTest(t, []string{"one", name}, []string{"one", "two", other}, walkAndOpenHelper)
}
// Overwrite by moving the parent.
renameTest(t, []string{"three", name}, []string{"one", name}, walkHelper)
renameTest(t, []string{"three", name}, []string{"one", name}, walkAndOpenHelper)
// Create over the types.
renameTest(t, []string{"one", "created"}, []string{"one", name}, createHelper)
renameTest(t, []string{"one", "created"}, []string{"one", "two", name}, createHelper)
renameTest(t, []string{"three", "created"}, []string{"one", name}, createHelper)
}
}
func TestRenameInvalid(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
for name := range newTypeMap(nil) {
for _, invalidName := range allInvalidNames(name) {
if err := root.Rename(root, invalidName); err != syscall.EINVAL {
t.Errorf("got %v for name %q, want EINVAL", err, invalidName)
}
}
}
}
func TestRenameAtInvalid(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
for name := range newTypeMap(nil) {
for _, invalidName := range allInvalidNames(name) {
if err := root.RenameAt(invalidName, root, "okay"); err != syscall.EINVAL {
t.Errorf("got %v for name %q, want EINVAL", err, invalidName)
}
if err := root.RenameAt("okay", root, invalidName); err != syscall.EINVAL {
t.Errorf("got %v for name %q, want EINVAL", err, invalidName)
}
}
}
}
// TestRenameSecondOrder tests that indirect rename targets continue to receive
// Renamed calls after a rename of its renamed parent. i.e.,
//
// 1. Create /one/file
// 2. Create /directory
// 3. Rename /one -> /directory/one
// 4. Rename /directory -> /three/foo
// 5. file from (1) should still receive Renamed.
//
// This is a regression test for b/135219260.
func TestRenameSecondOrder(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
rootBackend, root := newRoot(h, c)
defer root.Close()
// Walk to /one.
_, oneBackend, oneFile := walkHelper(h, "one", root)
defer oneFile.Close()
// Walk to and generate /one/file.
//
// walkHelper re-walks to oneFile, so we need the second backend,
// which will also receive Renamed calls.
oneSecondBackend, fileBackend, fileFile := walkHelper(h, "file", oneFile)
defer fileFile.Close()
// Walk to and generate /directory.
_, directoryBackend, directoryFile := walkHelper(h, "directory", root)
defer directoryFile.Close()
// Rename /one to /directory/one.
rootBackend.EXPECT().RenameAt("one", directoryBackend, "one").Return(nil)
expectRenamed(oneBackend, []string{}, directoryBackend, "one")
expectRenamed(oneSecondBackend, []string{}, directoryBackend, "one")
expectRenamed(fileBackend, []string{}, oneBackend, "file")
if err := renameAt(h, root, directoryFile, "one", "one", false); err != nil {
h.t.Fatalf("got rename err %v, want nil", err)
}
// Walk to /three.
_, threeBackend, threeFile := walkHelper(h, "three", root)
defer threeFile.Close()
// Rename /directory to /three/foo.
rootBackend.EXPECT().RenameAt("directory", threeBackend, "foo").Return(nil)
expectRenamed(directoryBackend, []string{}, threeBackend, "foo")
expectRenamed(oneBackend, []string{}, directoryBackend, "one")
expectRenamed(oneSecondBackend, []string{}, directoryBackend, "one")
expectRenamed(fileBackend, []string{}, oneBackend, "file")
if err := renameAt(h, root, threeFile, "directory", "foo", false); err != nil {
h.t.Fatalf("got rename err %v, want nil", err)
}
}
func TestReadlink(t *testing.T) {
for name := range newTypeMap(nil) {
t.Run(name, func(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
// Walk to the file normally.
_, f, err := root.Walk([]string{name})
if err != nil {
t.Fatalf("walk failed: got %v, wanted nil", err)
}
defer f.Close()
backend := h.Pop(f)
const symlinkTarget = "symlink-target"
if backend.Attr.Mode.IsSymlink() {
// This should only go through on symlinks.
backend.EXPECT().Readlink().Return(symlinkTarget, nil)
}
// Attempt a Readlink operation.
target, err := f.Readlink()
if err != nil && err != syscall.EINVAL {
t.Errorf("readlink got %v, wanted EINVAL", err)
} else if err == nil && target != symlinkTarget {
t.Errorf("readlink got %v, wanted %v", target, symlinkTarget)
}
})
}
}
// fdTest is a wrapper around operations that may send file descriptors. This
// asserts that the file descriptors are working as intended.
func fdTest(t *testing.T, sendFn func(*fd.FD) *fd.FD) {
// Create a pipe that we can read from.
r, w, err := os.Pipe()
if err != nil {
t.Fatalf("unable to create pipe: %v", err)
}
defer r.Close()
defer w.Close()
// Attempt to send the write end.
wFD, err := fd.NewFromFile(w)
if err != nil {
t.Fatalf("unable to convert file: %v", err)
}
defer wFD.Close() // This is a copy.
// Send wFD and receive newFD.
newFD := sendFn(wFD)
defer newFD.Close()
// Attempt to write.
const message = "hello"
if _, err := newFD.Write([]byte(message)); err != nil {
t.Fatalf("write got %v, wanted nil", err)
}
// Should see the message on our end.
buffer := []byte(message)
if _, err := io.ReadFull(r, buffer); err != nil {
t.Fatalf("read got %v, wanted nil", err)
}
if string(buffer) != message {
t.Errorf("got message %v, wanted %v", string(buffer), message)
}
}
func TestConnect(t *testing.T) {
for name := range newTypeMap(nil) {
t.Run(name, func(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
// Walk to the file normally.
_, backend, f := walkHelper(h, name, root)
defer f.Close()
// Catch all the non-socket cases.
if !backend.Attr.Mode.IsSocket() {
// This has been set up to fail if Connect is called.
if _, err := f.Connect(p9.ConnectFlags(0)); err != syscall.EINVAL {
t.Errorf("connect got %v, wanted EINVAL", err)
}
return
}
// Ensure the fd exchange works.
fdTest(t, func(send *fd.FD) *fd.FD {
backend.EXPECT().Connect(p9.ConnectFlags(0)).Return(send, nil)
recv, err := backend.Connect(p9.ConnectFlags(0))
if err != nil {
t.Fatalf("connect got %v, wanted nil", err)
}
return recv
})
})
}
}
func TestReaddir(t *testing.T) {
for name := range newTypeMap(nil) {
t.Run(name, func(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
// Walk to the file normally.
_, backend, f := walkHelper(h, name, root)
defer f.Close()
// Catch all the non-directory cases.
if !backend.Attr.Mode.IsDir() {
// This has also been set up to fail if Readdir is called.
if _, err := f.Readdir(0, 1); err != syscall.EINVAL {
t.Errorf("readdir got %v, wanted EINVAL", err)
}
return
}
// Ensure that readdir works for directories.
if _, err := f.Readdir(0, 1); err != syscall.EINVAL {
t.Errorf("readdir got %v, wanted EINVAL", err)
}
if _, _, _, err := f.Open(p9.ReadWrite); err != syscall.EISDIR {
t.Errorf("readdir got %v, wanted EISDIR", err)
}
if _, _, _, err := f.Open(p9.WriteOnly); err != syscall.EISDIR {
t.Errorf("readdir got %v, wanted EISDIR", err)
}
backend.EXPECT().Open(p9.ReadOnly).Times(1)
if _, _, _, err := f.Open(p9.ReadOnly); err != nil {
t.Errorf("readdir got %v, wanted nil", err)
}
backend.EXPECT().Readdir(uint64(0), uint32(1)).Times(1)
if _, err := f.Readdir(0, 1); err != nil {
t.Errorf("readdir got %v, wanted nil", err)
}
})
}
}
func TestOpen(t *testing.T) {
type openTest struct {
name string
flags p9.OpenFlags
err error
match func(p9.FileMode) bool
}
cases := []openTest{
{
name: "not-openable-read-only",
flags: p9.ReadOnly,
err: syscall.EINVAL,
match: func(mode p9.FileMode) bool { return !p9.CanOpen(mode) },
},
{
name: "not-openable-write-only",
flags: p9.WriteOnly,
err: syscall.EINVAL,
match: func(mode p9.FileMode) bool { return !p9.CanOpen(mode) },
},
{
name: "not-openable-read-write",
flags: p9.ReadWrite,
err: syscall.EINVAL,
match: func(mode p9.FileMode) bool { return !p9.CanOpen(mode) },
},
{
name: "directory-read-only",
flags: p9.ReadOnly,
err: nil,
match: func(mode p9.FileMode) bool { return mode.IsDir() },
},
{
name: "directory-read-write",
flags: p9.ReadWrite,
err: syscall.EISDIR,
match: func(mode p9.FileMode) bool { return mode.IsDir() },
},
{
name: "directory-write-only",
flags: p9.WriteOnly,
err: syscall.EISDIR,
match: func(mode p9.FileMode) bool { return mode.IsDir() },
},
{
name: "read-only",
flags: p9.ReadOnly,
err: nil,
match: func(mode p9.FileMode) bool { return p9.CanOpen(mode) },
},
{
name: "write-only",
flags: p9.WriteOnly,
err: nil,
match: func(mode p9.FileMode) bool { return p9.CanOpen(mode) && !mode.IsDir() },
},
{
name: "read-write",
flags: p9.ReadWrite,
err: nil,
match: func(mode p9.FileMode) bool { return p9.CanOpen(mode) && !mode.IsDir() },
},
{
name: "directory-read-only-truncate",
flags: p9.ReadOnly | p9.OpenTruncate,
err: syscall.EISDIR,
match: func(mode p9.FileMode) bool { return mode.IsDir() },
},
{
name: "read-only-truncate",
flags: p9.ReadOnly | p9.OpenTruncate,
err: nil,
match: func(mode p9.FileMode) bool { return p9.CanOpen(mode) && !mode.IsDir() },
},
{
name: "write-only-truncate",
flags: p9.WriteOnly | p9.OpenTruncate,
err: nil,
match: func(mode p9.FileMode) bool { return p9.CanOpen(mode) && !mode.IsDir() },
},
{
name: "read-write-truncate",
flags: p9.ReadWrite | p9.OpenTruncate,
err: nil,
match: func(mode p9.FileMode) bool { return p9.CanOpen(mode) && !mode.IsDir() },
},
}
// Open(flags OpenFlags) (*fd.FD, QID, uint32, error)
// - only works on Regular, NamedPipe, BLockDevice, CharacterDevice
// - returning a file works as expected
for name := range newTypeMap(nil) {
for _, tc := range cases {
t.Run(fmt.Sprintf("%s-%s", tc.name, name), func(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
// Walk to the file normally.
_, backend, f := walkHelper(h, name, root)
defer f.Close()
// Does this match the case?
if !tc.match(backend.Attr.Mode) {
t.SkipNow()
}
// Ensure open-required operations fail.
if _, err := f.ReadAt([]byte("hello"), 0); err != syscall.EINVAL {
t.Errorf("readAt got %v, wanted EINVAL", err)
}
if _, err := f.WriteAt(make([]byte, 6), 0); err != syscall.EINVAL {
t.Errorf("writeAt got %v, wanted EINVAL", err)
}
if err := f.FSync(); err != syscall.EINVAL {
t.Errorf("fsync got %v, wanted EINVAL", err)
}
if _, err := f.Readdir(0, 1); err != syscall.EINVAL {
t.Errorf("readdir got %v, wanted EINVAL", err)
}
// Attempt the given open.
if tc.err != nil {
// We expect an error, just test and return.
if _, _, _, err := f.Open(tc.flags); err != tc.err {
t.Fatalf("open with flags %v got %v, want %v", tc.flags, err, tc.err)
}
return
}
// Run an FD test, since we expect success.
fdTest(t, func(send *fd.FD) *fd.FD {
backend.EXPECT().Open(tc.flags).Return(send, p9.QID{}, uint32(0), nil).Times(1)
recv, _, _, err := f.Open(tc.flags)
if err != tc.err {
t.Fatalf("open with flags %v got %v, want %v", tc.flags, err, tc.err)
}
return recv
})
// If the open was successful, attempt another one.
if _, _, _, err := f.Open(tc.flags); err != syscall.EINVAL {
t.Errorf("second open with flags %v got %v, want EINVAL", tc.flags, err)
}
// Ensure that all illegal operations fail.
if _, _, err := f.Walk(nil); err != syscall.EINVAL && err != syscall.EBUSY {
t.Errorf("walk got %v, wanted EINVAL or EBUSY", err)
}
if _, _, _, _, err := f.WalkGetAttr(nil); err != syscall.EINVAL && err != syscall.EBUSY {
t.Errorf("walkgetattr got %v, wanted EINVAL or EBUSY", err)
}
})
}
}
}
func TestClose(t *testing.T) {
type closeTest struct {
name string
closeFn func(backend *Mock, f p9.File) error
}
cases := []closeTest{
{
name: "close",
closeFn: func(_ *Mock, f p9.File) error {
return f.Close()
},
},
{
name: "remove",
closeFn: func(backend *Mock, f p9.File) error {
// Allow the rename call in the parent, automatically translated.
backend.parent.EXPECT().UnlinkAt(gomock.Any(), gomock.Any()).Times(1)
return f.(deprecatedRemover).Remove()
},
},
{
name: "setAttrClose",
closeFn: func(backend *Mock, f p9.File) error {
valid := p9.SetAttrMask{ATime: true}
attr := p9.SetAttr{ATimeSeconds: 1, ATimeNanoSeconds: 2}
backend.EXPECT().SetAttr(valid, attr).Times(1)
return f.SetAttrClose(valid, attr)
},
},
}
for name := range newTypeMap(nil) {
for _, tc := range cases {
t.Run(fmt.Sprintf("%s(%s)", tc.name, name), func(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
// Walk to the file normally.
_, backend, f := walkHelper(h, name, root)
// Close via the prescribed method.
if err := tc.closeFn(backend, f); err != nil {
t.Fatalf("closeFn failed: %v", err)
}
// Everything should fail with EBADF.
if _, _, err := f.Walk(nil); err != syscall.EBADF {
t.Errorf("walk got %v, wanted EBADF", err)
}
if _, err := f.StatFS(); err != syscall.EBADF {
t.Errorf("statfs got %v, wanted EBADF", err)
}
if _, _, _, err := f.GetAttr(p9.AttrMaskAll()); err != syscall.EBADF {
t.Errorf("getattr got %v, wanted EBADF", err)
}
if err := f.SetAttr(p9.SetAttrMask{}, p9.SetAttr{}); err != syscall.EBADF {
t.Errorf("setattrk got %v, wanted EBADF", err)
}
if err := f.Rename(root, "new-name"); err != syscall.EBADF {
t.Errorf("rename got %v, wanted EBADF", err)
}
if err := f.Close(); err != syscall.EBADF {
t.Errorf("close got %v, wanted EBADF", err)
}
if _, _, _, err := f.Open(p9.ReadOnly); err != syscall.EBADF {
t.Errorf("open got %v, wanted EBADF", err)
}
if _, err := f.ReadAt([]byte("hello"), 0); err != syscall.EBADF {
t.Errorf("readAt got %v, wanted EBADF", err)
}
if _, err := f.WriteAt(make([]byte, 6), 0); err != syscall.EBADF {
t.Errorf("writeAt got %v, wanted EBADF", err)
}
if err := f.FSync(); err != syscall.EBADF {
t.Errorf("fsync got %v, wanted EBADF", err)
}
if _, _, _, _, err := f.Create("new-file", p9.ReadWrite, 0, 0, 0); err != syscall.EBADF {
t.Errorf("create got %v, wanted EBADF", err)
}
if _, err := f.Mkdir("new-directory", 0, 0, 0); err != syscall.EBADF {
t.Errorf("mkdir got %v, wanted EBADF", err)
}
if _, err := f.Symlink("old-name", "new-name", 0, 0); err != syscall.EBADF {
t.Errorf("symlink got %v, wanted EBADF", err)
}
if err := f.Link(root, "new-name"); err != syscall.EBADF {
t.Errorf("link got %v, wanted EBADF", err)
}
if _, err := f.Mknod("new-block-device", 0, 0, 0, 0, 0); err != syscall.EBADF {
t.Errorf("mknod got %v, wanted EBADF", err)
}
if err := f.RenameAt("old-name", root, "new-name"); err != syscall.EBADF {
t.Errorf("renameAt got %v, wanted EBADF", err)
}
if err := f.UnlinkAt("name", 0); err != syscall.EBADF {
t.Errorf("unlinkAt got %v, wanted EBADF", err)
}
if _, err := f.Readdir(0, 1); err != syscall.EBADF {
t.Errorf("readdir got %v, wanted EBADF", err)
}
if _, err := f.Readlink(); err != syscall.EBADF {
t.Errorf("readlink got %v, wanted EBADF", err)
}
if err := f.Flush(); err != syscall.EBADF {
t.Errorf("flush got %v, wanted EBADF", err)
}
if _, _, _, _, err := f.WalkGetAttr(nil); err != syscall.EBADF {
t.Errorf("walkgetattr got %v, wanted EBADF", err)
}
if _, err := f.Connect(p9.ConnectFlags(0)); err != syscall.EBADF {
t.Errorf("connect got %v, wanted EBADF", err)
}
})
}
}
}
// onlyWorksOnOpenThings is a helper test method for operations that should
// only work on files that have been explicitly opened.
func onlyWorksOnOpenThings(h *Harness, t *testing.T, name string, root p9.File, mode p9.OpenFlags, expectedErr error, fn func(backend *Mock, f p9.File, shouldSucceed bool) error) {
// Walk to the file normally.
_, backend, f := walkHelper(h, name, root)
defer f.Close()
// Does it work before opening?
if err := fn(backend, f, false); err != syscall.EINVAL {
t.Errorf("operation got %v, wanted EINVAL", err)
}
// Is this openable?
if !p9.CanOpen(backend.Attr.Mode) {
return // Nothing to do.
}
// If this is a directory, we can't handle writing.
if backend.Attr.Mode.IsDir() && (mode == p9.ReadWrite || mode == p9.WriteOnly) {
return // Skip.
}
// Open the file.
backend.EXPECT().Open(mode)
if _, _, _, err := f.Open(mode); err != nil {
t.Fatalf("open got %v, wanted nil", err)
}
// Attempt the operation.
if err := fn(backend, f, expectedErr == nil); err != expectedErr {
t.Fatalf("operation got %v, wanted %v", err, expectedErr)
}
}
func TestRead(t *testing.T) {
type readTest struct {
name string
mode p9.OpenFlags
err error
}
cases := []readTest{
{
name: "read-only",
mode: p9.ReadOnly,
err: nil,
},
{
name: "read-write",
mode: p9.ReadWrite,
err: nil,
},
{
name: "write-only",
mode: p9.WriteOnly,
err: syscall.EPERM,
},
}
for name := range newTypeMap(nil) {
for _, tc := range cases {
t.Run(fmt.Sprintf("%s-%s", tc.name, name), func(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
const message = "hello"
onlyWorksOnOpenThings(h, t, name, root, tc.mode, tc.err, func(backend *Mock, f p9.File, shouldSucceed bool) error {
if !shouldSucceed {
_, err := f.ReadAt([]byte(message), 0)
return err
}
// Prepare for the call to readAt in the backend.
backend.EXPECT().ReadAt(gomock.Any(), uint64(0)).Do(func(p []byte, offset uint64) {
copy(p, message)
}).Return(len(message), nil)
// Make the client call.
p := make([]byte, 2*len(message)) // Double size.
n, err := f.ReadAt(p, 0)
// Sanity check result.
if err != nil {
return err
}
if n != len(message) {
t.Fatalf("message length incorrect, got %d, want %d", n, len(message))
}
if !bytes.Equal(p[:n], []byte(message)) {
t.Fatalf("message incorrect, got %v, want %v", p, []byte(message))
}
return nil // Success.
})
})
}
}
}
func TestWrite(t *testing.T) {
type writeTest struct {
name string
mode p9.OpenFlags
err error
}
cases := []writeTest{
{
name: "read-only",
mode: p9.ReadOnly,
err: syscall.EPERM,
},
{
name: "read-write",
mode: p9.ReadWrite,
err: nil,
},
{
name: "write-only",
mode: p9.WriteOnly,
err: nil,
},
}
for name := range newTypeMap(nil) {
for _, tc := range cases {
t.Run(fmt.Sprintf("%s-%s", tc.name, name), func(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
const message = "hello"
onlyWorksOnOpenThings(h, t, name, root, tc.mode, tc.err, func(backend *Mock, f p9.File, shouldSucceed bool) error {
if !shouldSucceed {
_, err := f.WriteAt([]byte(message), 0)
return err
}
// Prepare for the call to readAt in the backend.
var output []byte // Saved by Do below.
backend.EXPECT().WriteAt(gomock.Any(), uint64(0)).Do(func(p []byte, offset uint64) {
output = p
}).Return(len(message), nil)
// Make the client call.
n, err := f.WriteAt([]byte(message), 0)
// Sanity check result.
if err != nil {
return err
}
if n != len(message) {
t.Fatalf("message length incorrect, got %d, want %d", n, len(message))
}
if !bytes.Equal(output, []byte(message)) {
t.Fatalf("message incorrect, got %v, want %v", output, []byte(message))
}
return nil // Success.
})
})
}
}
}
func TestFSync(t *testing.T) {
for name := range newTypeMap(nil) {
for _, mode := range []p9.OpenFlags{p9.ReadOnly, p9.WriteOnly, p9.ReadWrite} {
t.Run(fmt.Sprintf("%s-%s", mode, name), func(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
onlyWorksOnOpenThings(h, t, name, root, mode, nil, func(backend *Mock, f p9.File, shouldSucceed bool) error {
if shouldSucceed {
backend.EXPECT().FSync().Times(1)
}
return f.FSync()
})
})
}
}
}
func TestFlush(t *testing.T) {
for name := range newTypeMap(nil) {
t.Run(name, func(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
_, backend, f := walkHelper(h, name, root)
defer f.Close()
backend.EXPECT().Flush()
f.Flush()
})
}
}
// onlyWorksOnDirectories is a helper test method for operations that should
// only work on unopened directories, such as create, mkdir and symlink.
func onlyWorksOnDirectories(h *Harness, t *testing.T, name string, root p9.File, fn func(backend *Mock, f p9.File, shouldSucceed bool) error) {
// Walk to the file normally.
_, backend, f := walkHelper(h, name, root)
defer f.Close()
// Only directories support mknod.
if !backend.Attr.Mode.IsDir() {
if err := fn(backend, f, false); err != syscall.EINVAL {
t.Errorf("operation got %v, wanted EINVAL", err)
}
return // Nothing else to do.
}
// Should succeed.
if err := fn(backend, f, true); err != nil {
t.Fatalf("operation got %v, wanted nil", err)
}
// Open the directory.
backend.EXPECT().Open(p9.ReadOnly).Times(1)
if _, _, _, err := f.Open(p9.ReadOnly); err != nil {
t.Fatalf("open got %v, wanted nil", err)
}
// Should not work again.
if err := fn(backend, f, false); err != syscall.EINVAL {
t.Fatalf("operation got %v, wanted EINVAL", err)
}
}
func TestCreate(t *testing.T) {
for name := range newTypeMap(nil) {
t.Run(name, func(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
onlyWorksOnDirectories(h, t, name, root, func(backend *Mock, f p9.File, shouldSucceed bool) error {
if !shouldSucceed {
_, _, _, _, err := f.Create("new-file", p9.ReadWrite, 0, 1, 2)
return err
}
// If the create is going to succeed, then we
// need to create a new backend file, and we
// clone to ensure that we don't close the
// original.
_, newF, err := f.Walk(nil)
if err != nil {
t.Fatalf("clone got %v, wanted nil", err)
}
defer newF.Close()
newBackend := h.Pop(newF)
// Run a regular FD test to validate that path.
fdTest(t, func(send *fd.FD) *fd.FD {
// Return the send FD on success.
newFile := h.NewFile()(backend) // New file with the parent backend.
newBackend.EXPECT().Create("new-file", p9.ReadWrite, p9.FileMode(0), p9.UID(1), p9.GID(2)).Return(send, newFile, p9.QID{}, uint32(0), nil)
// Receive the fd back.
recv, _, _, _, err := newF.Create("new-file", p9.ReadWrite, 0, 1, 2)
if err != nil {
t.Fatalf("create got %v, wanted nil", err)
}
return recv
})
// The above will fail via normal test flow, so
// we can assume that it passed.
return nil
})
})
}
}
func TestCreateInvalid(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
for name := range newTypeMap(nil) {
for _, invalidName := range allInvalidNames(name) {
if _, _, _, _, err := root.Create(invalidName, p9.ReadWrite, 0, 0, 0); err != syscall.EINVAL {
t.Errorf("got %v for name %q, want EINVAL", err, invalidName)
}
}
}
}
func TestMkdir(t *testing.T) {
for name := range newTypeMap(nil) {
t.Run(name, func(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
onlyWorksOnDirectories(h, t, name, root, func(backend *Mock, f p9.File, shouldSucceed bool) error {
if shouldSucceed {
backend.EXPECT().Mkdir("new-directory", p9.FileMode(0), p9.UID(1), p9.GID(2))
}
_, err := f.Mkdir("new-directory", 0, 1, 2)
return err
})
})
}
}
func TestMkdirInvalid(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
for name := range newTypeMap(nil) {
for _, invalidName := range allInvalidNames(name) {
if _, err := root.Mkdir(invalidName, 0, 0, 0); err != syscall.EINVAL {
t.Errorf("got %v for name %q, want EINVAL", err, invalidName)
}
}
}
}
func TestSymlink(t *testing.T) {
for name := range newTypeMap(nil) {
t.Run(name, func(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
onlyWorksOnDirectories(h, t, name, root, func(backend *Mock, f p9.File, shouldSucceed bool) error {
if shouldSucceed {
backend.EXPECT().Symlink("old-name", "new-name", p9.UID(1), p9.GID(2))
}
_, err := f.Symlink("old-name", "new-name", 1, 2)
return err
})
})
}
}
func TestSyminkInvalid(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
for name := range newTypeMap(nil) {
for _, invalidName := range allInvalidNames(name) {
// We need only test for invalid names in the new name,
// the target can be an arbitrary string and we don't
// need to sanity check it.
if _, err := root.Symlink("old-name", invalidName, 0, 0); err != syscall.EINVAL {
t.Errorf("got %v for name %q, want EINVAL", err, invalidName)
}
}
}
}
func TestLink(t *testing.T) {
for name := range newTypeMap(nil) {
t.Run(name, func(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
onlyWorksOnDirectories(h, t, name, root, func(backend *Mock, f p9.File, shouldSucceed bool) error {
if shouldSucceed {
backend.EXPECT().Link(gomock.Any(), "new-link")
}
return f.Link(f, "new-link")
})
})
}
}
func TestLinkInvalid(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
for name := range newTypeMap(nil) {
for _, invalidName := range allInvalidNames(name) {
if err := root.Link(root, invalidName); err != syscall.EINVAL {
t.Errorf("got %v for name %q, want EINVAL", err, invalidName)
}
}
}
}
func TestMknod(t *testing.T) {
for name := range newTypeMap(nil) {
t.Run(name, func(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
onlyWorksOnDirectories(h, t, name, root, func(backend *Mock, f p9.File, shouldSucceed bool) error {
if shouldSucceed {
backend.EXPECT().Mknod("new-block-device", p9.FileMode(0), uint32(1), uint32(2), p9.UID(3), p9.GID(4)).Times(1)
}
_, err := f.Mknod("new-block-device", 0, 1, 2, 3, 4)
return err
})
})
}
}
// concurrentFn is a specification of a concurrent operation. This is used to
// drive the concurrency tests below.
type concurrentFn struct {
name string
match func(p9.FileMode) bool
op func(h *Harness, backend *Mock, f p9.File, callback func())
}
func concurrentTest(t *testing.T, name string, fn1, fn2 concurrentFn, sameDir, expectedOkay bool) {
var (
names1 []string
names2 []string
)
if sameDir {
// Use the same file one directory up.
names1, names2 = []string{"one", name}, []string{"one", name}
} else {
// For different directories, just use siblings.
names1, names2 = []string{"one", name}, []string{"three", name}
}
t.Run(fmt.Sprintf("%s(%v)+%s(%v)", fn1.name, names1, fn2.name, names2), func(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
// Walk to both files as given.
_, f1, err := root.Walk(names1)
if err != nil {
t.Fatalf("error walking, got %v, want nil", err)
}
defer f1.Close()
b1 := h.Pop(f1)
_, f2, err := root.Walk(names2)
if err != nil {
t.Fatalf("error walking, got %v, want nil", err)
}
defer f2.Close()
b2 := h.Pop(f2)
// Are these a good match for the current test case?
if !fn1.match(b1.Attr.Mode) {
t.SkipNow()
}
if !fn2.match(b2.Attr.Mode) {
t.SkipNow()
}
// Construct our "concurrency creator".
in1 := make(chan struct{}, 1)
in2 := make(chan struct{}, 1)
var top sync.WaitGroup
var fns sync.WaitGroup
defer top.Wait()
top.Add(2) // Accounting for below.
defer fns.Done()
fns.Add(1) // See line above; released before top.Wait.
go func() {
defer top.Done()
fn1.op(h, b1, f1, func() {
in1 <- struct{}{}
fns.Wait()
})
}()
go func() {
defer top.Done()
fn2.op(h, b2, f2, func() {
in2 <- struct{}{}
fns.Wait()
})
}()
// Compute a reasonable timeout. If we expect the operation to hang,
// give it 10 milliseconds before we assert that it's fine. After all,
// there will be a lot of these tests. If we don't expect it to hang,
// give it a full minute, since the machine could be slow.
timeout := 10 * time.Millisecond
if expectedOkay {
timeout = 1 * time.Minute
}
// Read the first channel.
var second chan struct{}
select {
case <-in1:
second = in2
case <-in2:
second = in1
}
// Catch concurrency.
select {
case <-second:
// We finished successful. Is this good? Depends on the
// expected result.
if !expectedOkay {
t.Errorf("%q and %q proceeded concurrently!", fn1.name, fn2.name)
}
case <-time.After(timeout):
// Great, things did not proceed concurrently. Is that what we
// expected?
if expectedOkay {
t.Errorf("%q and %q hung concurrently!", fn1.name, fn2.name)
}
}
})
}
func randomFileName() string {
return fmt.Sprintf("%x", rand.Int63())
}
func TestConcurrency(t *testing.T) {
readExclusive := []concurrentFn{
{
// N.B. We can't explicitly check WalkGetAttr behavior,
// but we rely on the fact that the internal code paths
// are the same.
name: "walk",
match: func(mode p9.FileMode) bool { return mode.IsDir() },
op: func(h *Harness, backend *Mock, f p9.File, callback func()) {
// See the documentation of WalkCallback.
// Because walk is actually implemented by the
// mock, we need a special place for this
// callback.
//
// Note that a clone actually locks the parent
// node. So we walk from this node to test
// concurrent operations appropriately.
backend.WalkCallback = func() error {
callback()
return nil
}
f.Walk([]string{randomFileName()}) // Won't exist.
},
},
{
name: "fsync",
match: func(mode p9.FileMode) bool { return p9.CanOpen(mode) },
op: func(h *Harness, backend *Mock, f p9.File, callback func()) {
backend.EXPECT().Open(gomock.Any())
backend.EXPECT().FSync().Do(func() {
callback()
})
f.Open(p9.ReadOnly) // Required.
f.FSync()
},
},
{
name: "readdir",
match: func(mode p9.FileMode) bool { return mode.IsDir() },
op: func(h *Harness, backend *Mock, f p9.File, callback func()) {
backend.EXPECT().Open(gomock.Any())
backend.EXPECT().Readdir(gomock.Any(), gomock.Any()).Do(func(uint64, uint32) {
callback()
})
f.Open(p9.ReadOnly) // Required.
f.Readdir(0, 1)
},
},
{
name: "readlink",
match: func(mode p9.FileMode) bool { return mode.IsSymlink() },
op: func(h *Harness, backend *Mock, f p9.File, callback func()) {
backend.EXPECT().Readlink().Do(func() {
callback()
})
f.Readlink()
},
},
{
name: "connect",
match: func(mode p9.FileMode) bool { return mode.IsSocket() },
op: func(h *Harness, backend *Mock, f p9.File, callback func()) {
backend.EXPECT().Connect(gomock.Any()).Do(func(p9.ConnectFlags) {
callback()
})
f.Connect(0)
},
},
{
name: "open",
match: func(mode p9.FileMode) bool { return p9.CanOpen(mode) },
op: func(h *Harness, backend *Mock, f p9.File, callback func()) {
backend.EXPECT().Open(gomock.Any()).Do(func(p9.OpenFlags) {
callback()
})
f.Open(p9.ReadOnly)
},
},
{
name: "flush",
match: func(mode p9.FileMode) bool { return true },
op: func(h *Harness, backend *Mock, f p9.File, callback func()) {
backend.EXPECT().Flush().Do(func() {
callback()
})
f.Flush()
},
},
}
writeExclusive := []concurrentFn{
{
// N.B. We can't really check getattr. But this is an
// extremely low-risk function, it seems likely that
// this check is paranoid anyways.
name: "setattr",
match: func(mode p9.FileMode) bool { return true },
op: func(h *Harness, backend *Mock, f p9.File, callback func()) {
backend.EXPECT().SetAttr(gomock.Any(), gomock.Any()).Do(func(p9.SetAttrMask, p9.SetAttr) {
callback()
})
f.SetAttr(p9.SetAttrMask{}, p9.SetAttr{})
},
},
{
name: "unlinkAt",
match: func(mode p9.FileMode) bool { return mode.IsDir() },
op: func(h *Harness, backend *Mock, f p9.File, callback func()) {
backend.EXPECT().UnlinkAt(gomock.Any(), gomock.Any()).Do(func(string, uint32) {
callback()
})
f.UnlinkAt(randomFileName(), 0)
},
},
{
name: "mknod",
match: func(mode p9.FileMode) bool { return mode.IsDir() },
op: func(h *Harness, backend *Mock, f p9.File, callback func()) {
backend.EXPECT().Mknod(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Do(func(string, p9.FileMode, uint32, uint32, p9.UID, p9.GID) {
callback()
})
f.Mknod(randomFileName(), 0, 0, 0, 0, 0)
},
},
{
name: "link",
match: func(mode p9.FileMode) bool { return mode.IsDir() },
op: func(h *Harness, backend *Mock, f p9.File, callback func()) {
backend.EXPECT().Link(gomock.Any(), gomock.Any()).Do(func(p9.File, string) {
callback()
})
f.Link(f, randomFileName())
},
},
{
name: "symlink",
match: func(mode p9.FileMode) bool { return mode.IsDir() },
op: func(h *Harness, backend *Mock, f p9.File, callback func()) {
backend.EXPECT().Symlink(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Do(func(string, string, p9.UID, p9.GID) {
callback()
})
f.Symlink(randomFileName(), randomFileName(), 0, 0)
},
},
{
name: "mkdir",
match: func(mode p9.FileMode) bool { return mode.IsDir() },
op: func(h *Harness, backend *Mock, f p9.File, callback func()) {
backend.EXPECT().Mkdir(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Do(func(string, p9.FileMode, p9.UID, p9.GID) {
callback()
})
f.Mkdir(randomFileName(), 0, 0, 0)
},
},
{
name: "create",
match: func(mode p9.FileMode) bool { return mode.IsDir() },
op: func(h *Harness, backend *Mock, f p9.File, callback func()) {
// Return an error for the creation operation, as this is the simplest.
backend.EXPECT().Create(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil, p9.QID{}, uint32(0), syscall.EINVAL).Do(func(string, p9.OpenFlags, p9.FileMode, p9.UID, p9.GID) {
callback()
})
f.Create(randomFileName(), p9.ReadOnly, 0, 0, 0)
},
},
}
globalExclusive := []concurrentFn{
{
name: "remove",
match: func(mode p9.FileMode) bool { return mode.IsDir() },
op: func(h *Harness, backend *Mock, f p9.File, callback func()) {
// Remove operates on a locked parent. So we
// add a child, walk to it and call remove.
// Note that because this operation can operate
// concurrently with itself, we need to
// generate a random file name.
randomFile := randomFileName()
backend.AddChild(randomFile, h.NewFile())
defer backend.RemoveChild(randomFile)
_, file, err := f.Walk([]string{randomFile})
if err != nil {
h.t.Fatalf("walk got %v, want nil", err)
}
// Remove is automatically translated to the parent.
backend.EXPECT().UnlinkAt(gomock.Any(), gomock.Any()).Do(func(string, uint32) {
callback()
})
// Remove is also a close.
file.(deprecatedRemover).Remove()
},
},
{
name: "rename",
match: func(mode p9.FileMode) bool { return mode.IsDir() },
op: func(h *Harness, backend *Mock, f p9.File, callback func()) {
// Similarly to remove, because we need to
// operate on a child, we allow a walk.
randomFile := randomFileName()
backend.AddChild(randomFile, h.NewFile())
defer backend.RemoveChild(randomFile)
_, file, err := f.Walk([]string{randomFile})
if err != nil {
h.t.Fatalf("walk got %v, want nil", err)
}
defer file.Close()
fileBackend := h.Pop(file)
// Rename is automatically translated to the parent.
backend.EXPECT().RenameAt(gomock.Any(), gomock.Any(), gomock.Any()).Do(func(string, p9.File, string) {
callback()
})
// Attempt the rename.
fileBackend.EXPECT().Renamed(gomock.Any(), gomock.Any())
file.Rename(f, randomFileName())
},
},
{
name: "renameAt",
match: func(mode p9.FileMode) bool { return mode.IsDir() },
op: func(h *Harness, backend *Mock, f p9.File, callback func()) {
backend.EXPECT().RenameAt(gomock.Any(), gomock.Any(), gomock.Any()).Do(func(string, p9.File, string) {
callback()
})
// Attempt the rename. There are no active fids
// with this name, so we don't need to expect
// Renamed hooks on anything.
f.RenameAt(randomFileName(), f, randomFileName())
},
},
}
for _, fn1 := range readExclusive {
for _, fn2 := range readExclusive {
for name := range newTypeMap(nil) {
// Everything should be able to proceed in parallel.
concurrentTest(t, name, fn1, fn2, true, true)
concurrentTest(t, name, fn1, fn2, false, true)
}
}
}
for _, fn1 := range append(readExclusive, writeExclusive...) {
for _, fn2 := range writeExclusive {
for name := range newTypeMap(nil) {
// Only cross-directory functions should proceed in parallel.
concurrentTest(t, name, fn1, fn2, true, false)
concurrentTest(t, name, fn1, fn2, false, true)
}
}
}
for _, fn1 := range append(append(readExclusive, writeExclusive...), globalExclusive...) {
for _, fn2 := range globalExclusive {
for name := range newTypeMap(nil) {
// Nothing should be able to run in parallel.
concurrentTest(t, name, fn1, fn2, true, false)
concurrentTest(t, name, fn1, fn2, false, false)
}
}
}
}
func TestReadWriteConcurrent(t *testing.T) {
h, c := NewHarness(t)
defer h.Finish()
_, root := newRoot(h, c)
defer root.Close()
const (
instances = 10
iterations = 10000
dataSize = 1024
)
var (
dataSets [instances][dataSize]byte
backends [instances]*Mock
files [instances]p9.File
)
// Walk to the file normally.
for i := 0; i < instances; i++ {
_, backends[i], files[i] = walkHelper(h, "file", root)
defer files[i].Close()
}
// Open the files.
for i := 0; i < instances; i++ {
backends[i].EXPECT().Open(p9.ReadWrite)
if _, _, _, err := files[i].Open(p9.ReadWrite); err != nil {
t.Fatalf("open got %v, wanted nil", err)
}
}
// Initialize random data for each instance.
for i := 0; i < instances; i++ {
if _, err := rand.Read(dataSets[i][:]); err != nil {
t.Fatalf("error initializing dataSet#%d, got %v", i, err)
}
}
// Define our random read/write mechanism.
randRead := func(h *Harness, backend *Mock, f p9.File, data, test []byte) {
// Prepare the backend.
backend.EXPECT().ReadAt(gomock.Any(), uint64(0)).Do(func(p []byte, offset uint64) {
if n := copy(p, data); n != len(data) {
// Note that we have to assert the result here, as the Return statement
// below cannot be dynamic: it will be bound before this call is made.
h.t.Errorf("wanted length %d, got %d", len(data), n)
}
}).Return(len(data), nil)
// Execute the read.
if n, err := f.ReadAt(test, 0); n != len(test) || err != nil {
t.Errorf("failed read: wanted (%d, nil), got (%d, %v)", len(test), n, err)
return // No sense doing check below.
}
if !bytes.Equal(test, data) {
t.Errorf("data integrity failed during read") // Not as expected.
}
}
randWrite := func(h *Harness, backend *Mock, f p9.File, data []byte) {
// Prepare the backend.
backend.EXPECT().WriteAt(gomock.Any(), uint64(0)).Do(func(p []byte, offset uint64) {
if !bytes.Equal(p, data) {
h.t.Errorf("data integrity failed during write") // Not as expected.
}
}).Return(len(data), nil)
// Execute the write.
if n, err := f.WriteAt(data, 0); n != len(data) || err != nil {
t.Errorf("failed read: wanted (%d, nil), got (%d, %v)", len(data), n, err)
}
}
randReadWrite := func(n int, h *Harness, backend *Mock, f p9.File, data []byte) {
test := make([]byte, len(data))
for i := 0; i < n; i++ {
if rand.Intn(2) == 0 {
randRead(h, backend, f, data, test)
} else {
randWrite(h, backend, f, data)
}
}
}
// Start reading and writing.
var wg sync.WaitGroup
for i := 0; i < instances; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
randReadWrite(iterations, h, backends[i], files[i], dataSets[i][:])
}(i)
}
wg.Wait()
}
|