File: testsm.py

package info (click to toggle)
xcp-storage-managers 0.1.1-3
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 3,476 kB
  • sloc: python: 28,696; sh: 7,282; ansic: 1,507; xml: 853; makefile: 252
file content (2171 lines) | stat: -rwxr-xr-x 70,485 bytes parent folder | download
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
#!/usr/bin/python

import re
import os
import sys
import time
import getopt
import traceback
import random

import tutil
import storagemanager

sys.path.append("/usr/lib/xcp/sm")
from ipc import IPCFlag
import LVHDSR
import lvhdutil
import util

CREATE_SIZES = [
        1 * tutil.MiB, 
        10 * tutil.MiB,
        100 * tutil.MiB,
        1024 * tutil.MiB,
        10 * tutil.GiB ]

SNAPSHOT_NUM_ITERS = 4
SNAPSHOT_SIZES = [
        10 * tutil.MiB,
        10 * tutil.GiB ]

RESIZE_START_SIZE = 10 * tutil.MiB
RESIZE_SIZES = [
        17 * tutil.MiB,
         3 * tutil.GiB,
        10 * tutil.GiB ]
RESIZE_SNAPSHOTS = 3
RESIZE_PREFILL_SIZES = [
        512,
        6 * tutil.MiB ]

VDI_SIZE_DEFAULT = 1 * tutil.GiB
COALESCE_RND_SIZE = 10 * tutil.GiB
COALESCE_RND_ITERS = 4
COALESCE_RND_WFRAQ = 0.01

# don't run disktest in "basic" mode on VDI's larger than this size (to save 
# time)
MAX_DISKTEST_SIZE = 1 * tutil.GiB

LOG_FILE = "/tmp/testsm.log"

VHD_SIZE_INCREMENT = (2 * tutil.MiB)
LVM_SIZE_INCREMENT = (4 * tutil.MiB)

MGT_LV_NAME = "MGT"
MGT_LV_SIZE = LVM_SIZE_INCREMENT

NUM_RETRIES = 300
RETRY_PERIOD = 3

RESIZE_FIST_POINTS = [
        "vhd_fail_resize_begin",
        "vhd_fail_resize_data",
        "vhd_fail_resize_metadata",
        "vhd_fail_resize_end" ]

SNAPSHOT_FIST_POINTS = { # map the FIST points to whether the op succeeds
        "LVHDRT_clone_vdi_after_create_journal": False,
        "LVHDRT_clone_vdi_after_shrink_parent": False,
        "LVHDRT_clone_vdi_after_lvcreate": False,
        "LVHDRT_clone_vdi_after_first_snap": False,
        "LVHDRT_clone_vdi_after_second_snap": True,
        "LVHDRT_clone_vdi_after_parent_hidden": True,
        "LVHDRT_clone_vdi_after_parent_ro": True,
        "LVHDRT_clone_vdi_before_remove_journal": True }

SNAPSHOT_RECOVERY_FIST_POINTS = [
        "LVHDRT_clone_vdi_before_undo_clone",
        "LVHDRT_clone_vdi_after_undo_clone" ]

COALEAF_FIST_POINTS = { # map the FIST points to whether the coalesce succeeds
        "LVHDRT_coaleaf_before_coalesce": False,
        "LVHDRT_coaleaf_after_coalesce": False,
        "LVHDRT_coaleaf_one_renamed": False,
        "LVHDRT_coaleaf_both_renamed": False,
        "LVHDRT_coaleaf_after_vdirec": False,
        "LVHDRT_coaleaf_before_delete": False,
        "LVHDRT_coaleaf_after_delete": True,
        "LVHDRT_coaleaf_before_remove_j": True }

COALEAF_RECOVERY_FIST_POINTS = [
        "LVHDRT_coaleaf_undo_after_rename",
        "LVHDRT_coaleaf_undo_after_rename2",
        "LVHDRT_coaleaf_undo_after_refcount",
        "LVHDRT_coaleaf_undo_after_deflate",
        "LVHDRT_coaleaf_undo_end",
        "LVHDRT_coaleaf_finish_after_inflate",
        "LVHDRT_coaleaf_finish_end" ]

COALEAF_CONCURRENCY_FIST_POINTS = [
        "LVHDRT_coaleaf_delay_1",
        "LVHDRT_coaleaf_delay_2",
        "LVHDRT_coaleaf_delay_3" ]

logger = None
vmDom0 = { "master": None, "slave": None }
thisHost = "master"
srType = ""
testMode = ""
testNum = 0
skipTo = 0
stopAfter = 100000

sm = None

FULL_BLOCK_SIZE = 2 * tutil.MiB
PART_BLOCK_SIZE = 15 * tutil.KiB
CHAR_SEQ = "".join([chr(x) for x in range(256)])
CHAR_SEQ_REV = "".join([chr(x) for x in range(255, -1, -1)])
BUF_PATTERN = CHAR_SEQ + CHAR_SEQ
BUF_PATTERN_REV = CHAR_SEQ_REV + CHAR_SEQ_REV
BUF_ZEROS = "\0" * 512

class TestException(Exception):
    pass

class StopRequest(Exception):
    pass

def assertEqual(val1, val2):
    assertRel("eq", val1, val2)

def assertRel(rel, val1, val2):
    if rel == "eq":
        if val1 != val2:
            raise TestException("%s != %s" % (val1, val2))
    elif rel == "ne":
        if val1 == val2:
            raise TestException("%s == %s" % (val1, val2))
    elif rel == "gt":
        if val1 <= val2:
            raise TestException("%s <= %s" % (val1, val2))
    elif rel == "ge":
        if val1 < val2:
            raise TestException("%s < %s" % (val1, val2))
    elif rel == "lt":
        if val1 >= val2:
            raise TestException("%s >= %s" % (val1, val2))
    elif rel == "le":
        if val1 > val2:
            raise TestException("%s > %s" % (val1, val2))
    else:
        raise TestException("Invalid rel: %s" % rel)

def setFistPoint(point, active):
    args = {"fistPoint": point, "active": active}
    ret = sm.onMaster("testing-hooks", "setFistPoint", args)
    if ret != "True":
        raise TestException("ERROR setting FIST point %s to %s" % \
                (point, active))

def stop(msg = None):
    """Call this function to stop the test suite at any chosen point"""
    text = ""
    if msg:
        text = msg
    raise StopRequest(text)

def pause(msg = None):
    """Call this function to pause the test suite at any chosen point and wait
    for the user to press enter"""
    if msg:
        logger.log("\n\n* * * %s: Press Enter to continue..." % msg, 0)
    else:
        logger.log("\n\n* * * Pausing test, press enter to continue...", 0)
    garbage = raw_input()

def _disableCommand(cmd, success):
    if not tutil.pathExists(cmd):
        raise TestException("Command not found: %s" % cmd)
    if success:
        cmdFake = "/bin/true"
    else:
        cmdFake = "/bin/false"
    cmdBackup = "%s.orig" % cmd
    if not tutil.pathExists(cmdBackup):
        os.rename(cmd, cmdBackup)
    os.unlink(cmd)
    os.symlink(cmdFake, cmd)

def _enableCommand(cmd):
    cmdBackup = "%s.orig" % cmd
    if not tutil.pathExists(cmdBackup):
        raise TestException("Command had not been disabled: %s" % cmd)
    os.unlink(cmd)
    os.symlink(cmdBackup, cmd)

def _nextTest(description, incremement = True):
    global testNum
    text = "[  -] "
    if incremement:
        testNum += 1
        text = "[%3d] " % testNum
    if testNum >= stopAfter + 1:
        stop("After test %d" % (testNum - 1))
    run = testNum >= skipTo
    if not run:
        text = "[skipping] " + text
    logger.log(text + description, 0)
    return run

def _findTargetSR(srType):
    sr = None
    srList = sm.findSR(srType)
    if len(srList) == 0:
        raise TestException("No SR of type '%s' found" % srType)
    elif len(srList) == 1:
        sr = srList[0]
    elif len(srList) > 1:
        sr = sm.getDefaultSR(sm)
        if sm.srTypes[sr] != srType:
            sr = None
            for candidate in srList:
                if len(sm.findThisPBD(candidate)) > 0:
                    sr = candidate
                    break
        if not sr:
            raise TestException("No SRs of type %s found on this host" % srType)
    logger.log("Target SR: %s" % sr, 0)
    if len(sm.getVDIs(sr)) > 0:
        raise TestException("Target SR not empty")
    return sr

def _createSpaceHogFile(sr, allocSize):
    BS = 4 * tutil.KiB
    srDir = sm.getPathSR(sr)
    fn = "%s/space.hog" % srDir
    numBlocks = allocSize / BS
    logger.log("Creating a space hog file %s (%d blocks)" % (fn, numBlocks), 2)
    f = open(fn, 'w')
    for i in range(numBlocks):
        f.seek(i * BS)
        f.write(BUF_ZEROS)
    f.close()

def _destroySpaceHogFile(sr):
    srDir = sm.getPathSR(sr)
    fn = "%s/space.hog" % srDir
    os.unlink(fn)

def leaveFreeSpace(sr, space):
    info = sm.getInfoSR(sr)
    totalSize = int(info["physical-size"])
    currUtiln = int(info["physical-utilisation"])
    allocSize = totalSize - currUtiln - space
    assert(allocSize > 0)
    if srType == "lvhd":
        vdi = sm.createVDI(sr, allocSize, True)
    else:
        _createSpaceHogFile(sr, allocSize)
    sm.refreshSR(sr)
    info = sm.getInfoSR(sr)
    totalSize = int(info["physical-size"])
    currUtiln = int(info["physical-utilisation"])
    freeSpace = totalSize - currUtiln
    logger.log("Left free space in SR: %d (asked: %d)" % (freeSpace, space), 2)
    return freeSpace

def getNumFiles(sr):
    if srType == "lvhd":
        cmd = "lvs VG_XenStorage-%s --noheadings | grep -v %s | wc -l" % \
                (sr, MGT_LV_NAME)
        text = tutil.execCmd(cmd, 0, logger, storagemanager.LOG_LEVEL_SUB)
        return int(text) 
    else:
        files = os.listdir("/var/run/sr-mount/%s" % sr)
        num = 0
        for file in files:
            if file.endswith(".vhd"):
                num += 1
        return num

def validateVHD(sr, vdi, live):
    vdis = sm.activateChain(sr, vdi)
    path = sm.getPathVDI(sr, vdi)
    cmd = "vhd-util check -n %s" % path
    if live:
        cmd += " -i"
    tutil.execCmd(cmd, 0, logger, storagemanager.LOG_LEVEL_CMD + 1)
    sm.deactivateVDIs(sr, vdis)

def checkSize(path, size):
    # stat # Note: stat doesn't work on block devices for some reason
    #statinfo = os.stat(path)
    #statSize = statinfo.st_size
    #if size != statSize:
    #    raise TestException("stat size (%s) %d != %d (expected)" % \
    #            (statinfo, statSize, size))

    # sysfs
    devName = path.split("/")[-1]
    f = open("/sys/block/%s/size" % devName, 'r')
    line = f.readline().strip()
    sysfsSize = int(line) * 512
    if size != sysfsSize:
        raise TestException("sysfs size %d != %d (expected)" % \
                (sysfsSize, size))

    # fdisk
    fdiskSize = -1
    cmd = "fdisk -l %s" % path
    stdout = tutil.execCmd(cmd, 0, logger, storagemanager.LOG_LEVEL_CMD)
    for line in stdout.split('\n'):
        m = re.match("^Disk [^,]+, (\d+) bytes", line)
        if m != None:
            fdiskSize = int(m.group(1))
    if size != fdiskSize:
        raise TestException("fdisk reported size %d != %d (expected)" % \
                (fdiskSize, size))

def _waitForGC(sr, numFiles, retries = NUM_RETRIES):
    """wait util there are at most numFiles LV's left"""
    kicked = False
    prevNum = 0
    i = 0
    while i < retries:
        num = getNumFiles(sr)
        logger.log("Waiting for GC to finish leave %d... (curr: %d, iter %d)" % \
                (numFiles, num, i), 3)
        if num <= numFiles:
            return
        if num < prevNum:
            i = 0 # only time out if GC is not making progress
            logger.log("Giving GC more time", 3)
        else:
            i += 1
            if i >= NUM_RETRIES / 2 and not kicked:
                logger.log("Kicking GC just in case")
                sm.refreshSR(sr)
                kicked = True
        prevNum = num
        time.sleep(RETRY_PERIOD)
    raise TestException("Timed out waiting for %d LV's to be left" % numFiles)

def _getThinProvisionFlag(srInfo):
    return (srInfo["sm-config"].get("allocation") and \
            srInfo["sm-config"]["allocation"] == "thin")

def _testAttachVDI(vdi, ro, vm = None):
    if not vm:
        vm = vmDom0[thisHost]
    sm.plugVDI(vdi, ro, vm)
    if vm == vmDom0[thisHost]:
        if not sm.getDevice(vdi):
            raise TestException("Failed to plug VDI %s" % vdi)
        info = sm.getInfoVDI(vdi)
        virtSize = int(info["virtual-size"])
        checkSize(_getDevice(vdi), virtSize)

def _getDevice(vdi):
    device = sm.getDevice(vdi)
    if not device:
        raise TestException("Device for VDI %s not found" % vdi)
    return device

def _testDetachVDI(vdi):
    sm.unplugVDI(vdi)

def _testCreateVDI(sr, size, raw):
    info = sm.getInfoSR(sr)
    srUtilisationBefore = int(info["physical-utilisation"])
    thinProvision = _getThinProvisionFlag(info)

    vdi = sm.createVDI(sr, size, raw)
    if not raw:
        validateVHD(sr, vdi, False)
    vdis = sm.getLeafVDIs(sr)

    if len(vdis) != len(sm.createdVDIs):
        raise TestException("Incorrect number of VDIs: %d (expected %d)" % \
                (len(vdis), len(sm.createdVDIs)))

    if not vdi in vdis:
        raise TestException("VDI not found in SR listing: %s != %s" % \
                (vdi, vdis[0]))

    info = sm.getInfoVDI(vdi)
    virtSize = int(info["virtual-size"])
    increment = VHD_SIZE_INCREMENT
    if raw:
        increment = LVM_SIZE_INCREMENT
    if size % increment:
        size = (size / increment + 1) * increment
    if size != virtSize:
        raise TestException("Virtual size doesn't match: requested=%d, got=%d"\
                % (size, virtSize))

    utilisation = int(info["physical-utilisation"])
    if raw:
        if utilisation != size:
            raise TestException("Physical utilisation invalid for RAW: %d" % \
                    utilisation)
    else:
        overhead = sm.getOverheadVHDEmpty(size)
        if srType == "lvhd":
            overhead = sm.getSizeLV(sm.getOverheadVHDEmpty(lvhdutil.MSIZE))
        expectedUtiln = overhead
        if srType == "lvhd":
            if not thinProvision:
                expectedUtiln = sm.getVHDLVSize(size)
            expectedUtiln = sm.getSizeLV(expectedUtiln)
        if (srType == "lvhd" and utilisation != expectedUtiln) or \
                (utilisation > expectedUtiln):
            raise TestException("Physical utilisation %d != %d (expected)" % \
                    (utilisation, expectedUtiln))

    # this test fails because SR utilisation isn't updated immediately
    #info = sm.getInfoSR(sr)
    #srUtilisationAfter = int(info["physical-utilisation"])
    #if srUtilisationAfter - srUtilisationBefore != utilisation:
    #    raise TestException("Incorrect SR utilisation: %d (expected: %d)" % \
    #            (srUtilisationAfter - srUtilisationBefore, utilisation))
    return vdi

def _testSnapshotVDI(sr, vdi, live, single = False):
    vdiSnap = sm.snapshotVDI(vdi, single)
    info = sm.getInfoVDI(vdiSnap)
    logger.log("snap info: %s" % info, 4)
    raw = False
    if srType == "lvhd":
        raw = (info["sm-config"]["vdi_type"] == "aio")
    if not (raw and single):
        validateVHD(sr, vdiSnap, live)
    if srType != "lvhd":
        sm.refreshSR(sr)
    virtSize = int(info["virtual-size"])
    utilisation = int(info["physical-utilisation"])
    if single:
        assertEqual(info["managed"], "false")
        assertEqual(info["read-only"], "true")
    else:
        assertEqual(info["managed"], "true")
        assertEqual(info["read-only"], "false")

    overhead = sm.getOverheadVHDEmpty(virtSize)
    if srType == "lvhd":
        overhead = sm.getOverheadVHDEmpty(lvhdutil.MSIZE)
    expectedUtiln = overhead
    #if not _getThinProvisionFlag(sm.getInfoSR(sr)):
    #   expectedUtiln += virtSize
    expectedUtiln = sm.getSizeLV(expectedUtiln)
    if srType == "lvhd":
        if single:
            assertRel("ge", utilisation, expectedUtiln)
        else:
            assertEqual(utilisation, expectedUtiln)
    return vdiSnap

def _checkActiveLVs(sr):
    for i in range(NUM_RETRIES):
        active = False
        proof = ""
        cmd = "lvs VG_XenStorage-%s --noheadings" % sr
        text = tutil.execCmd(cmd, 0, logger, storagemanager.LOG_LEVEL_CMD)
        for line in text.split('\n'):
            if not line.strip():
                continue
            if line.split()[2][4] == 'a':
                active = True
                proof = line
                break
        if not active:
            break
        logger.log("Waiting for LVs to be deactivated (%d)" % i)
        time.sleep(RETRY_PERIOD)
    if active:
        raise TestException("LV active when nothing attached: %s" % proof)

def _testDestroyAll(sr):
    logger.log("Destroy all VDIs", 1)
    sm.unplugAll()
    if srType == "lvhd":
        _checkActiveLVs(sr)
    sm.destroyAll()
    _waitForGC(sr, 0)
    sm.refreshSR(sr)
    vdis = sm.getVDIs(sr)
    if len(vdis) != 0:
        raise TestException("Non-zero number of VDIs: %d (%s)" % \
                (len(vdis), vdis))
    info = sm.getInfoSR(sr)
    srUtilisation = int(info["physical-utilisation"])
    if srType == "lvhd" and srUtilisation > MGT_LV_SIZE:
        raise TestException("Empty SR utilisation %d != 0" % srUtilisation)

def _testWrite(vdi, size, i, marker = "MARKER"):
    path = sm.getDevice(vdi)
    offset = i * VHD_SIZE_INCREMENT
    if offset + VHD_SIZE_INCREMENT > size:
        return
    logger.log("Writing to '%s', offset %d (i=%d)" % (path, offset, i), 2)
    try:
        f = open(path, "w")
        f.seek(offset)
        f.write("block %d (marker: %s)\n" % (i, marker))
        f.close()
    except IOError:
        raise TestException("Error writing to '%s'" % path)
    _testRead(vdi, size, i, False, marker)

def _testWritePattern(vdi, numBlocks, skipEvery, writeAmount, rev = False):
    path = sm.getDevice(vdi)
    try:
        buf = BUF_PATTERN
        if rev:
            buf = BUF_PATTERN_REV

        f = open(path, "w")
        block = 0
        while block < numBlocks:
            f.seek(block * VHD_SIZE_INCREMENT)
            logger.log("Writing to '%s', block=%d" % (path, block), 3)
            i = 0
            while i < writeAmount:
                f.write(buf)
                i += len(buf)
            block += 1 + skipEvery
        f.close()
    except IOError:
        raise TestException("Error writing to '%s'" % path)

def _testReadPattern(vdi, numBlocks, checkAll, skipEvery, writeAmount,
        allowEmpty = False, rev = False):
    path = sm.getDevice(vdi)
    bufExpected = BUF_PATTERN
    if rev:
        bufExpected = BUF_PATTERN_REV
    readAmount = writeAmount * 3
    if readAmount > FULL_BLOCK_SIZE:
        readAmount = FULL_BLOCK_SIZE
    try:
        f = open(path, "r")
        block = 0
        while block < numBlocks:
            logger.log("Reading '%s' to verify (block %d)" % (path, block), 3)
            f.seek(block * VHD_SIZE_INCREMENT)
            i = 0
            while i < readAmount:
                buf = f.read(len(bufExpected))
                expect = bufExpected
                if block % (skipEvery + 1): # did we write into this block?
                    expect = BUF_ZEROS
                if i >= writeAmount: # did we write at this offset?
                    expect = BUF_ZEROS
                if buf != expect:
                    if allowEmpty and buf == BUF_ZEROS:
                        logger.log("Allowing empty contents at %d+%d" % 
                                (block, i), 0)
                    else:
                        raise Exception("Readback mismatch! block = " + \
                                "%d, off = %d, expected '%s', got '%s'" % \
                                (block, i, expect, buf))
                i += len(buf)
            block += 1
            if not checkAll:
                block *= 2
        f.close()
    except IOError:
        raise TestException("Error reading '%s'" % path)

def _testAttachWrite(vdi, live, size, i, doAttach = False):
    if not live or doAttach:
        _testAttachVDI(vdi, False)
    _testWrite(vdi, size, i)
    if not live:
        _testDetachVDI(vdi)

def _testWriteRandom(vdi, size, fraq, i):
    path = sm.getDevice(vdi)
    seedMultiplier = 181
    cmd = "disktest write %s %s -r -p %d -s %s" % \
            (path, i, int(100 * fraq), i * seedMultiplier)
    text = tutil.execCmd(cmd, 0, logger, storagemanager.LOG_LEVEL_CMD)

def _getHash(vdi):
    path = sm.getDevice(vdi)
    cmd = "md5sum -b %s" % path
    text = tutil.execCmd(cmd, 0, logger, storagemanager.LOG_LEVEL_CMD)
    return text

def _testRead(vdi, size, i, all, marker = "MARKER"):
    path = sm.getDevice(vdi)
    #logger.log("Read '%s' to verify (block %d)" % (path, i), 2)
    vals = [i]
    if all:
        vals = range(i + 1)
    try:
        f = open(path, "r")
        for j in vals:
            logger.log("Read '%s' to verify (block %d)" % (path, j), 2)
            f.seek(j * VHD_SIZE_INCREMENT)
            expected = "block %d (marker: %s)\n" % (j, marker)
            text = f.read(len(expected))
            if text != expected:
                raise TestException("Contents mismatch: got: '%s', " \
                        "expected: '%s'" % (text, expected))
        f.close()
    except IOError:
        raise TestException("Error reading '%s'" % path)

def _runDiskTest(vdi):
    path = sm.getDevice(vdi)
    cmd = "disktest write %s 77" % (path)
    tutil.execCmd(cmd, 0, logger, storagemanager.LOG_LEVEL_CMD)
    cmd = "disktest verify %s 77" % (path)
    tutil.execCmd(cmd, 0, logger, storagemanager.LOG_LEVEL_CMD)

def _testMultiAttach(vdi, size):
    text = "Multiple attaches"
    if not _nextTest(text, False): return

    NUM_SIMULT_VBDS = 1 # TODO
    NUM_BLOCKS = 3
    _testAttachVDI(vdi, False)
    for i in range(NUM_BLOCKS):
        _testWrite(vdi, size, i)
    _testDetachVDI(vdi)
    _testAttachVDI(vdi, True)
    _testRead(vdi, size, NUM_BLOCKS - 1, True)
    _testDetachVDI(vdi)

def _testSnapshot(sr, raw, live, write, size, iters):
    text = "Snapshot of "
    if raw:
        text += "raw VDI, "
    else:
        text += "VHD VDI, "
    if live:
        text += "live, "
    else:
        text += "offline, "
    if write:
        text += "non-"
    text += "empty, size %d (%d times)" % (size, iters)
    if not _nextTest(text): return

    vdi = _testCreateVDI(sr, size, raw)
    if live or write:
        _testAttachVDI(vdi, False)
        if write:
            _testWrite(vdi, size, 0)
        if not live:
            _testDetachVDI(vdi)

    vdiClone = vdi
    for i in range(iters):
        logger.log("(iteration %d of %d)" % (i + 1, iters), 1)
        vdiClone = _testSnapshotVDI(sr, vdiClone, live)
        for ht in ["master", "slave"]:
            if not vmDom0[ht]:
                continue
            _testAttachVDI(vdiClone, False, vmDom0[ht])
            if write and ht == thisHost:
                _testWrite(vdiClone, size, i)
            if i == iters - 1 and ht == thisHost:
                if size <= MAX_DISKTEST_SIZE or testMode != "basic":
                    _runDiskTest(vdiClone)
            _testDetachVDI(vdiClone)
    if not live:
        _testAttachVDI(vdi, False)
        if size <= MAX_DISKTEST_SIZE or testMode != "basic":
            _runDiskTest(vdi)

    _testDetachVDI(vdi)
    _testDestroyAll(sr)

def _testSnapshotSingle(sr, raw, live, write, size):
    text = "Single snapshot of "
    if raw:
        text += "raw VDI, "
    else:
        text += "VHD VDI, "
    if live:
        text += "live, "
    else:
        text += "offline, "
    if write:
        text += "non-"
    text += "empty, size %d" % (size)
    if not _nextTest(text): return

    vdi = _testCreateVDI(sr, size, raw)
    if live or write:
        _testAttachVDI(vdi, False)
        if write:
            _testWrite(vdi, size, 0)
        if not live:
            _testDetachVDI(vdi)

    vdiClone = _testSnapshotVDI(sr, vdi, live, True)
    try:
        _testAttachVDI(vdiClone, False)
        raise TestException("Attach of single snapshot %s succeeded" % vdiClone)
    except:
        pass
    try:
        vdiClone2 = _testSnapshotVDI(sr, vdiClone, live)
        raise TestException("Snapshot of single snapshot %s succeeded" % vdiClone)
    except:
        pass

    if not live:
        _testAttachVDI(vdi, False)
        if size <= MAX_DISKTEST_SIZE or testMode != "basic":
            _runDiskTest(vdi)

    _testDetachVDI(vdi)
    _testDestroyAll(sr)

def _testSnapshotInsufficientSpace(sr):
    text = "Snapshot: try with insufficient space"
    if not _nextTest(text): return

    info = sm.getInfoSR(sr)
    totalSize = int(info["physical-size"])
    size = totalSize * 998 / 1000
    vdi = _testCreateVDI(sr, size, True)
    try:
        vdiClone = sm.snapshotVDI(vdi)
        if _getThinProvisionFlag(info):
            _testAttachVDI(vdi, True)
            _testAttachVDI(vdiClone, True)
            raise TestException("Snapshot attached with insufficient space")
        raise TestException("Snapshot created with insufficient space")
    except (storagemanager.SMException, tutil.CommandException):
        pass
    _testDestroyAll(sr)

def _testSnapshotClobberBase(sr):
    text = "Snapshot: try to clobber base copy"
    if not _nextTest(text): return

    vdi = _testCreateVDI(sr, 10 * tutil.MiB, False)
    vdiClone = _testSnapshotVDI(sr, vdi, False)

    vg = sm.getPathSR(sr)
    cmd = "lvs %s" % vg
    text = tutil.execCmd(cmd, 0, logger, storagemanager.LOG_LEVEL_SUB)
    baseVDIFile = ""
    for line in text.split('\n'):
        if not line:
            continue
        uuid = line.split()[0][len("VHD-"):]
        if uuid != vdi and uuid != vdiClone:
            baseVDIFile = os.path.join(vg, "VHD-%s" % uuid)
    if not baseVDIFile:
        raise TestException("Base copy VDI LV not found")

    cmd = "lvchange -ay %s" % baseVDIFile
    tutil.execCmd(cmd, 0, logger, storagemanager.LOG_LEVEL_CMD)
    if not tutil.pathExists(baseVDIFile):
        raise TestException("Base copy VDI file not found (%s)" % baseVDIFile)
    try:
        f = open(baseVDIFile, "w")
        f.write("This is a readonly VDI clobber test")
        f.close()
        raise TestException("Base copy is writable")
    except IOError:
        pass
    cmd = "lvchange -an %s" % baseVDIFile
    tutil.execCmd(cmd, 0, logger, storagemanager.LOG_LEVEL_CMD)
    _testDestroyAll(sr)

def _testSnapshotFIST_do(sr, vdi, fistPoint, single, live, recovery):
    logger.log("FIST point %s" % fistPoint, 2)
    setFistPoint(fistPoint, True)
    if recovery:
        for rfist in SNAPSHOT_RECOVERY_FIST_POINTS:
            setFistPoint(rfist, True)
    try:
        vdiClone = _testSnapshotVDI(sr, vdi, live, single)
        raise TestException("%s did not cause failure" % fistPoint)
    except:
        if recovery:
            try:
                sm.refreshSR(sr)
                raise TestException("Recovery succeeded with rfist-0")
            except:
                pass
            setFistPoint(SNAPSHOT_RECOVERY_FIST_POINTS[0], False)
            try:
                sm.refreshSR(sr)
                raise TestException("Recovery succeeded with rfist-1")
            except:
                pass
            setFistPoint(SNAPSHOT_RECOVERY_FIST_POINTS[1], False)
        sm.refreshSR(sr)
    setFistPoint(fistPoint, False)

def _testSnapshotFIST(sr, single, raw, live, complexity, recovery):
    """Complexity param: 
        0 - single node; 
        1 - node snapshotted once, leaf empty;
        2 - node snapshotted once, leaf non-empty
    """
    text = "Snapshot: FIST points, "
    if single:
        text += "single-snap, "
    else:
        text += "double-snap, "
    if raw:
        text += "raw VDI, "
    else:
        text += "VHD VDI, "
    if live:
        text += "live, "
    else:
        text += "offline, "
    text += "complexity: %d" % complexity
    if recovery:
        text += " + recovery FIST"
    if not _nextTest(text): return

    setFistPoint("LVHDRT_exit", True)

    i = 1
    vdi = _testCreateVDI(sr, VDI_SIZE_DEFAULT, raw)
    _testAttachWrite(vdi, live, VDI_SIZE_DEFAULT, i, True)
    vdi2 = None
    if complexity > 0:
        vdi2 = _testSnapshotVDI(sr, vdi, False)
        if complexity == 2:
            i += 1
            _testAttachWrite(vdi, live, VDI_SIZE_DEFAULT, i, True)
            _testAttachWrite(vdi2, live, VDI_SIZE_DEFAULT, i, True)

    for fistPoint, succeeds in SNAPSHOT_FIST_POINTS.iteritems():
        _testSnapshotFIST_do(sr, vdi, fistPoint, single, live, recovery)

        # smoke tests
        vdi3 = _testSnapshotVDI(sr, vdi, live)
        _testAttachWrite(vdi3, False, VDI_SIZE_DEFAULT, i + 1)
        sm.destroyVDI(vdi3)
        if complexity > 0:
            vdi4 = _testSnapshotVDI(sr, vdi2, live)
            _testAttachWrite(vdi4, False, VDI_SIZE_DEFAULT, i + 1)
            sm.destroyVDI(vdi4)
        expectedNumVDIs = 2
        newClone = None
        if not single and succeeds:
            # find the new clone
            newClone = None
            leaves = sm.getLeafVDIs(sr)
            for leaf in leaves:
                if leaf != vdi and (complexity == 0 or leaf != vdi2):
                    newClone = leaf
                    sm.learnVDI(newClone)
                    break
            _testAttachWrite(newClone, False, VDI_SIZE_DEFAULT, i)
        i += 1
        _testAttachWrite(vdi, live, VDI_SIZE_DEFAULT, i)
        if complexity > 0:
            _testAttachWrite(vdi2, live, VDI_SIZE_DEFAULT, i)
            expectedNumVDIs += 3 # middle nodes won't be coalesceable
        if not single and succeeds:
            sm.destroyVDI(newClone)
        _waitForGC(sr, expectedNumVDIs)

    _testDestroyAll(sr)

def _testResizePrefill(sr, writeAmount):
    text = "Resize: prefilled with %d bytes" % writeAmount
    if not _nextTest(text): return

    vdi = _testCreateVDI(sr, 20 * tutil.MiB, False)
    _testAttachVDI(vdi, False)
    device = _getDevice(vdi)
    logger.log("Writing %d bytes to '%s'" % (writeAmount, device), 2)
    try:
        f = open(device, 'w')
        for i in range(0, writeAmount, 512):
            buf = str(i) * (512 / len(str(i)))
            padding = 512 - len(buf)
            buf += ">" * padding
            f.write(buf)
        f.close()
    except IOError:
        raise TestException("Failed to write into '%s'" % device)
    _testDetachVDI(vdi)

    sm.resizeVDI(vdi, 10 * tutil.GiB, False)
    _testAttachVDI(vdi, False)
    device = _getDevice(vdi)
    logger.log("Reading %d bytes from '%s'" % (writeAmount, device), 2)
    try:
        f = open(device, 'r')
        for i in range(0, writeAmount, 512):
            buf = f.read(512)
            expect = str(i) * (512 / len(str(i)))
            padding = 512 - len(expect)
            expect += ">" * padding
            if buf != expect:
                raise TestException("Contents mismatch: got: '%s', " % buf + \
                        "expected: '%s' (i=%d)" % (expect, i))
        f.close()
    except IOError:
        raise TestException("Failed to read '%s'" % device)

    _testDestroyAll(sr)

def _testResizeShrink(sr):
    text = "Resize: try to shrink"
    if not _nextTest(text): return

    vdi = _testCreateVDI(sr, 100 * tutil.MiB, False)
    try:
        sm.resizeVDI(vdi, 90 * tutil.MiB, False)
        raise TestException("Shrinking succeeded")
    except (storagemanager.SMException, tutil.CommandException):
        pass
    _testDestroyAll(sr)

def _testResizeInsufficientSpace(sr):
    text = "Resize: try with insufficient space"
    if not _nextTest(text): return

    info = sm.getInfoSR(sr)
    totalSize = int(info["physical-size"])
    vdi = _testCreateVDI(sr, 100 * tutil.MiB, False)
    try:
        sm.resizeVDI(vdi, totalSize, False)
        if _getThinProvisionFlag(info):
            _testAttachVDI(vdi, True)
            raise TestException("Resized to over SR capacity & attached")
        raise TestException("Resized to over SR capacity")
    except (storagemanager.SMException, tutil.CommandException):
        pass
    _testDestroyAll(sr)

def _testResizeVDI(sr, vdi, raw, live, size, snaps):
    if live:
        _testAttachVDI(vdi, False)
    sm.resizeVDI(vdi, size, live)
    if not raw:
        validateVHD(sr, vdi, live)
    info = sm.getInfoVDI(vdi)
    vsize = int(info["virtual-size"])
    if vsize < size:
        raise TestException("VDI size %d != %d (expected)" % (vsize, size))
    size = vsize # size may be rounded up

    # for the live case, in order to verify the size, we have to refresh the 
    # device by doing detach-reattach
    if live:
        _testDetachVDI(vdi)
    _testAttachVDI(vdi, False)
    if size <= MAX_DISKTEST_SIZE or testMode != "basic":
        _runDiskTest(vdi)

    if not live:
        _testDetachVDI(vdi)

    if snaps:
        vdiClone = _testSnapshotVDI(sr, vdi, live)
        nextSize = size + 50 * tutil.MiB
        _testResizeVDI(sr, vdiClone, False, live, nextSize, snaps - 1)

    if live:
        _testDetachVDI(vdi)

def _testResize(sr, raw, live, snaps):
    text = "Resize: "
    if live:
        text += "live, "
    else:
        text += "offline, "
    if raw:
        text += "Raw VDI"
    else:
        text += "VHD VDI"
    text += ", with %d snapshots" % snaps
    text += " (%d sizes)" % len(RESIZE_SIZES)
    if not _nextTest(text): return

    vdi = _testCreateVDI(sr, RESIZE_START_SIZE, raw)

    for size in RESIZE_SIZES:
        logger.log("(size %d)" % size, 1)
        _testResizeVDI(sr, vdi, raw, live, size, snaps)

    _testDestroyAll(sr)

def _testCoalesce(sr, size, raw, live, num, sizeDiff):
    """Test coalesce with the parameters:
        size: the size of the base VDI
        raw: whether the base VDI is raw or not
        live: whether the base VDI will be attached at the time of coalesce
        num: number of "coalesceable" VDIs
        sizeDiff: how much larger each child is compared to its parent"""
    text = "Coalesce: "
    if live:
        text += "live, "
    else:
        text += "offline, "
    if raw:
        text += "Raw VDI"
    else:
        text += "VHD VDI"
    text += ", size %d, %d coalesceable, size delta %d" % (size, num, sizeDiff)
    if not _nextTest(text): return

    vdiBase = _testCreateVDI(sr, size, raw)
    _testAttachWrite(vdiBase, live, size, 0, True)
    
    for i in range(num + 1):
        logger.log("Snapshot %d of %d" % ((i + 1), (num + 1)), 2)
        vdiClone = _testSnapshotVDI(sr, vdiBase, live)
        if sizeDiff:
            info = sm.getInfoVDI(vdiBase)
            size = int(info["virtual-size"]) + sizeDiff
            sm.resizeVDI(vdiBase, size, live)
        _testAttachWrite(vdiBase, live, size, (i + 1))
        sm.destroyVDI(vdiClone)
    
    _waitForGC(sr, 2)

    _testAttachWrite(vdiBase, live, size, (num + 1))
    _testDestroyAll(sr)

def _testCoalesceRelinkNonleaf(sr, size, live):
    """Test coalesce where the children to be relinked are not leaf nodes"""
    text = "Coalesce relink-nonleaf: "
    if live:
        text += "live, "
    else:
        text += "offline, "
    text += "size %d" % size
    if not _nextTest(text): return

    raw = False
    vdiBase = _testCreateVDI(sr, size, raw)
    _testAttachWrite(vdiBase, live, size, 0, True)
    
    num = 4
    toDestroy = None
    for i in range(2, num + 1):
        logger.log("Snapshot %d/%d" % (i, num), 2)
        vdiClone = _testSnapshotVDI(sr, vdiBase, live)
        if i == 2:
            toDestroy = vdiClone
        _testAttachWrite(vdiBase, live, size, (i - 1))
        if i == 3:
            _testAttachWrite(vdiClone, False, size, (i - 1))
            _testSnapshotVDI(sr, vdiClone, live)
    
    sm.destroyVDI(toDestroy)
    _waitForGC(sr, num * 2 - 1)

    _testAttachWrite(vdiBase, live, size, num)
    _testDestroyAll(sr)

def _testCoalesceNonRoot(sr, size, live):
    """Test coalesce where non-root nodes are involved"""
    text = "Coalesce non-root: "
    if live:
        text += "live, "
    else:
        text += "offline, "
    text += "size %d" % size
    if not _nextTest(text): return

    raw = False
    vdiBase = _testCreateVDI(sr, size, raw)
    _testAttachWrite(vdiBase, live, size, 0, True)
    
    num = 6
    toDestroy = None
    for i in range(1, num + 1):
        logger.log("Snapshot %d/%d" % (i, num), 2)
        vdiClone = _testSnapshotVDI(sr, vdiBase, live)
        if i == 1:
            toDestroy = vdiClone
        elif i % 2:
            sm.destroyVDI(vdiClone)
        _testAttachWrite(vdiBase, live, size, (i - 1))
    
    sm.destroyVDI(toDestroy)
    _waitForGC(sr, num + 1)

    _testAttachWrite(vdiBase, live, size, num)
    _testDestroyAll(sr)

def _testCoalesceRandomIO(sr, size, raw):
    """Write to disk randomly at a sector granularity, take a snapshot, write
    more (to the child now) at a sector granularity, take a hash, coalesce,
    compare the hash"""
    text = "Coalesce: random IO (size %s), " % size
    if raw:
        text += "raw VDI"
    else:
        text += "VHD VDI"
    if not _nextTest(text): return

    vdiBase = _testCreateVDI(sr, size, raw)
    _testAttachVDI(vdiBase, False)
    _testWriteRandom(vdiBase, size, COALESCE_RND_WFRAQ, 0)
    vdiClonePrev = _testSnapshotVDI(sr, vdiBase, True)
    for i in range(COALESCE_RND_ITERS):
        logger.log("Iteration %d" % (i + 1), 2)
        _testWriteRandom(vdiBase, size, COALESCE_RND_WFRAQ, i + 1)
        vdiClone = _testSnapshotVDI(sr, vdiBase, True)
        sm.destroyVDI(vdiClonePrev)
        vdiClonePrev = vdiClone
        validateVHD(sr, vdiBase, True)
        hashBefore = _getHash(vdiBase)
        _waitForGC(sr, 3, 2000)
        validateVHD(sr, vdiBase, True)
        hashAfter = _getHash(vdiBase)
        if hashBefore != hashAfter:
            raise TestException("Hash mismatch after coalesce")

    _testDestroyAll(sr)

def _testLeafCoalesce(sr, raw, live, sizeDiff, writeBlocks):
    """Test the basic functionality of coalesce-leaf"""
    text = "Leaf-clsce: "
    if live:
        text += "live, "
    else:
        text += "offline, "
    if raw:
        text += "Raw VDI"
    else:
        text += "VHD VDI"
    text += ", size delta %d, write %d blocks" % (sizeDiff, writeBlocks)
    if not _nextTest(text): return

    size = 300 * tutil.MiB
    vdi = _testCreateVDI(sr, size, raw)
    _testAttachWrite(vdi, live, size, 0, True)
    clone = _testSnapshotVDI(sr, vdi, live)
    if sizeDiff:
        info = sm.getInfoVDI(vdi)
        size = int(info["virtual-size"]) + sizeDiff
        sm.resizeVDI(vdi, size, live)
    if not live:
        _testAttachVDI(vdi, False)
    for i in range(writeBlocks):
        _testWrite(vdi, size, i + 1)
    if not live:
        _testDetachVDI(vdi)
    sm.destroyVDI(clone)
    
    _waitForGC(sr, 1)

    _testAttachWrite(vdi, live, size, writeBlocks + 1)
    _testDestroyAll(sr)

def _testLeafCoalesceConcurrency1(sr, fistPoint, raw, live, action, write):
    text = "Leaf-clsce: pt %s concurrent '%s'" % (fistPoint[-1], action)
    if live:
        text += ", live"
    else:
        text += ", offline"
    if raw:
        text += ", raw VDI"
    else:
        text += ", VHD VDI"
    if write:
        text += ", write"
    else:
        text += ", no write"
    if not _nextTest(text): return

    setFistPoint("LVHDRT_exit", False)

    size = 10 * tutil.GiB
    vdi = _testCreateVDI(sr, size, raw)
    _testAttachWrite(vdi, live, size, 0, True)
    clone = _testSnapshotVDI(sr, vdi, live)
    if not live:
        _testAttachVDI(vdi, False)
    for i in range(200):
        _testWrite(vdi, size, i + 1)
    if not live:
        _testDetachVDI(vdi)
    setFistPoint(fistPoint, True)
    sm.destroyVDI(clone)
    for i in range(NUM_RETRIES):
        logger.log("Waiting to hit the FIST point... (%d)" % (i), 2)
        flags = sm.getParam("sr", sr, "other-config")
        if flags.get(fistPoint) and flags[fistPoint] == "active":
            break
        time.sleep(RETRY_PERIOD)

    if write:
        _testAttachWrite(vdi, live, size, 1, False)

    if action == "destroy":
        sm.destroyVDI(vdi)
    else:
        clone = _testSnapshotVDI(sr, vdi, live)
        if write:
            _testAttachWrite(vdi, live, size, 1, False)

    time.sleep(20)
    for i in range(NUM_RETRIES):
        logger.log("Waiting to pass the FIST point... (%d)" % (i), 2)
        flags = sm.getParam("sr", sr, "other-config")
        if not flags.get(fistPoint):
            break
        time.sleep(RETRY_PERIOD)
    if action == "destroy":
        _waitForGC(sr, 0)
    else:
        time.sleep(6)
        setFistPoint(fistPoint, False)
        sm.destroyVDI(clone)
        _waitForGC(sr, 1)
    _testDestroyAll(sr)

def _testLeafCoalesceConcurrency2(sr, raw, live, sizeDiff, action):
    text = "Leaf-clsce: serializ'n with '%s'" % action
    if live:
        text += ", live"
    else:
        text += ", offline"
    if raw:
        text += ", Raw VDI"
    else:
        text += ", VHD VDI"
    text += ", size delta %d" % (sizeDiff)
    if not _nextTest(text): return

    size = 10 * tutil.GiB
    vdi = _testCreateVDI(sr, size, raw)
    _testAttachWrite(vdi, live, size, 0, True)
    clone = _testSnapshotVDI(sr, vdi, live)
    if sizeDiff:
        info = sm.getInfoVDI(vdi)
        size = int(info["virtual-size"]) + sizeDiff
        sm.resizeVDI(vdi, size, live)
    if not live:
        _testAttachVDI(vdi, False)
    for i in range(200):
        _testWrite(vdi, size, i + 1)
    if not live:
        _testDetachVDI(vdi)
    sm.setParam("vdi", vdi, "other-config:leaf-coalesce", "force")
    sm.destroyVDI(clone)
    time.sleep(3)
    i = 0
    while True:
        i += 1
        if action == "attach":
            _testAttachVDI(vdi, False)
            _testDetachVDI(vdi)
        elif action == "snap":
            clone = _testSnapshotVDI(sr, vdi, live)
            sm.destroyVDI(clone)
            break
        elif action == "resize":
            sm.resizeVDI(vdi, size + i * 10 * tutil.MiB, live)
        elif action == "destroy":
            sm.destroyVDI(vdi)
            _waitForGC(sr, 0)
        num = getNumFiles(sr)
        logger.log("Iteration %d: see %d files" % (i, num), 2)
        if num <= 1:
            break
    
    _waitForGC(sr, 1)
    _testDestroyAll(sr)

def _testLeafCoalesceInsufficientSpace(sr, raw):
    """Test coalesce-leaf with insufficient space"""
    text = "Leaf-clsce: insufficient space"
    if raw:
        text += ", Raw VDI"
    else:
        text += ", VHD VDI"
    if not _nextTest(text): return

    freeSpace = leaveFreeSpace(sr, 1 * tutil.GiB)

    size = freeSpace * 0.4
    if size % LVM_SIZE_INCREMENT:
        size = (int(size / LVM_SIZE_INCREMENT) + 1) * LVM_SIZE_INCREMENT
    vdi = _testCreateVDI(sr, size, raw)
    _testAttachVDI(vdi, False)
    for i in range(size / VHD_SIZE_INCREMENT):
        _testWrite(vdi, size, i)
    _testDetachVDI(vdi)

    vdiClone = _testSnapshotVDI(sr, vdi, False)
    _testAttachVDI(vdi, False)
    for i in range(size / VHD_SIZE_INCREMENT):
        _testWrite(vdi, size, i)
    _testDetachVDI(vdi)

    flags = sm.getParam("vdi", vdi, "other-config")
    if flags.get("leaf-coalesce"):
        assertRel("ne", flags["leaf-coalesce"], "offline")
    sm.destroyVDI(vdiClone)

    success = False
    for i in range(NUM_RETRIES):
        time.sleep(RETRY_PERIOD)
        flags = sm.getParam("vdi", vdi, "other-config")
        if flags.get("leaf-coalesce") and flags["leaf-coalesce"] == "offline":
            success = True
            break
        logger.log("Waiting for GC to mark VDI...")
    assertEqual(success, True)

    sm.setParam("vdi", vdi, "other-config:leaf-coalesce", "force")
    sm.refreshSR(sr)
    _waitForGC(sr, 2) # incl. the space-hogging VDI

    _testAttachWrite(vdi, False, size, (size / VHD_SIZE_INCREMENT + 1))
    _testDestroyAll(sr)

def _testLeafCoalesceFIST(sr, raw, live, recovery):
    """Test coalesce-leaf failure cases"""
    text = "Leaf-clsce: FIST"
    if raw:
        text += ", raw VDI"
    else:
        text += ", VHD VDI"
    if live:
        text += ", live"
    else:
        text += ", offline"
    if recovery:
        text += " + recovery FIST"
    if not _nextTest(text): return

    vdiBase = _testCreateVDI(sr, COALESCE_RND_SIZE, raw)
    _testAttachWrite(vdiBase, live, COALESCE_RND_SIZE, 0, True)

    setFistPoint("LVHDRT_exit", True)
    setFistPoint("LVHDRT_coaleaf_stop_after_recovery", True)

    i = 1
    for fistPoint, succeeds in COALEAF_FIST_POINTS.iteritems():
        logger.log("FIST point %s" % fistPoint, 2)
        setFistPoint(fistPoint, True)
#TODO: recovery fist
        vdiClone = _testSnapshotVDI(sr, vdiBase, live)
        sm.destroyVDI(vdiClone)
        time.sleep(6)
        sm.refreshSR(sr)
        # by now GC should have attempted leaf-coalesce, failed on the FIST 
        # point, recovered, and in the case of undo, stopped without 
        # re-attempting leaf-coalesce
        setFistPoint(fistPoint, False)
        if succeeds:
            _waitForGC(sr, 1)
        else:
            _waitForGC(sr, 2)
            _testAttachWrite(vdiBase, live, COALESCE_RND_SIZE, i)
            sm.setParam("vdi", vdiBase, "other-config:leaf-coalesce", "force")
            sm.refreshSR(sr)
            _waitForGC(sr, 1)
        assertEqual(getNumFiles(sr), 1)
        _testAttachWrite(vdiBase, live, COALESCE_RND_SIZE, i)
        i += 1

    _testDestroyAll(sr)

def _testJournalResize(sr, oldSize, newSize, fistPoint):
    """Test VHD-resize journal-based reverts"""
    text = "VHD-journal: %s resize %d -> %d" % (fistPoint, oldSize, newSize)
    if not _nextTest(text): return
    vdi = _testCreateVDI(sr, oldSize, False)
    _testAttachVDI(vdi, False)
    blocks = oldSize / VHD_SIZE_INCREMENT
    for i in range(blocks):
        _testWrite(vdi, oldSize, i)
    _testDetachVDI(vdi)

    sm.setParam("sr", sr, "other-config:testmode", fistPoint)
    try:
        sm.resizeVDI(vdi, newSize, False)
        raise TestException("Resize didn't fail as expected")
    except (storagemanager.SMException, tutil.CommandException):
        pass
    sm.setParam("sr", sr, "other-config:testmode", "")
    sm.refreshSR(sr)
    info = sm.getInfoVDI(vdi)
    actualSize = int(info["virtual-size"])
    if actualSize != oldSize:
        raise TestException("Size not restored: %d != %d" % \
                (oldSize, actualSize))
    _testAttachVDI(vdi, False)
    _testRead(vdi, oldSize, blocks - 1, True)
    _testDestroyAll(sr)

def _runTestAttachSR(sr):
    """Test SR.attach/detach"""
    logger.log("====> Test Group: SR ops", 0)
    text = "Detach/attach"
    if not _nextTest(text): return

    sm.unplugSR(sr)
    lockDir = "/var/run/locks/%s" % sr
    refcntDirLVM = "/var/run/refcount/lvm-%s" % sr
    if tutil.pathExists(lockDir):
        raise TestException("Lock dir not deleted on detach")
    if tutil.pathExists(refcntDirLVM):
        raise TestException("RefCount dir not deleted on detach")
    sm.plugSR(sr)

def _runTestProbeSR(sr):
    """Test SR.probe"""
    text = "Probe"
    if not _nextTest(text): return
    info = sm.getInfoPBD(sm.findThisPBD(sr))
    device_config = info["device-config"]
    dev = device_config.get("device")
    probeResult = sm.probe(sr, dev)
    if probeResult.find(sr) == -1:
        raise TestException("Probe did not find target SR on %s" % dev)

def _testReadCache(sr, chainSize, skipBlocks, writeAmount):
    """Test local read caching"""
    text = "Read cache for chain of %d, skipping %d, writing %d" % \
            (chainSize, skipBlocks, writeAmount)
    if not _nextTest(text): return
    size = 100 * tutil.MiB
    fillBlocks = 50
    vdi = _testCreateVDI(sr, size, False)
    sm.setParam("vdi", vdi, "allow-caching", "false")
    _testAttachVDI(vdi, False)
    _testWritePattern(vdi, fillBlocks, skipBlocks, writeAmount)
    _testDetachVDI(vdi)

    # create a chain of at least 2 because SM expects it
    vdiSnap = _testSnapshotVDI(sr, vdi, False)

    # read vdi partially to fill up the read cache partially 
    sm.setParam("vdi", vdi, "allow-caching", "true")
    _testAttachVDI(vdi, False)
    _testReadPattern(vdi, fillBlocks, False, skipBlocks, writeAmount)
    _testDetachVDI(vdi)

    # read vdi completely to fill up the read cache fully
    _testAttachVDI(vdi, False)
    _testReadPattern(vdi, fillBlocks, True, skipBlocks, writeAmount)
    _testDetachVDI(vdi)

    sm.setParam("vdi", vdi, "allow-caching", "false")

    # reparent the cache file so that we can see only what it has
    tmpVDI = _testCreateVDI(sr, size, False)
    tmpVHD = sm.getPathVDI(sr, tmpVDI)
    cacheSR = _findTargetSR("ext")
    cacheDir = sm.getPathSR(cacheSR)
    parentUUID = sm.getParentVDI(sr, vdi)
    readCachePath = "%s/%s.vhdcache" % (cacheDir, parentUUID)
    cmd = "vhd-util modify -n %s -p %s" % (readCachePath, tmpVHD)
    text = tutil.execCmd(cmd, 0, logger, storagemanager.LOG_LEVEL_CMD)

    # rename the cache so that we can plug it as a regular VDI
    newUuid = util.gen_uuid()
    newPath = "%s/%s.vhd" % (cacheDir, newUuid)
    logger.log("Renaming read cache %s => %s" % (readCachePath, newPath))
    os.rename(readCachePath, newPath)
    sm.refreshSR(cacheSR)
    sm.learnVDI(newUuid)
    time.sleep(3) # give time for the scan to complete

    _testAttachVDI(newUuid, False)
    _testReadPattern(newUuid, fillBlocks, True, skipBlocks, writeAmount, True)
    _testDetachVDI(newUuid)

    logger.log("Renaming back %s => %s" % (newPath, readCachePath))
    os.rename(newPath, readCachePath)
    sm.refreshSR(cacheSR)
    sm.unlearnVDI(newUuid)

    _testDestroyAll(sr)

def _testStandbyModeCacheBasic(sr):
    """Test Standby Mode write caching"""
    text = "Standby mode base case"
    if not _nextTest(text): return
    size = 100 * tutil.MiB
    vdi = _testCreateVDI(sr, size, False)
    sm.setParam("vdi", vdi, "allow-caching", "false")
    _testAttachVDI(vdi, False)
    for i in range(50):
        _testWrite(vdi, size, i, "first-pass")
    _testDetachVDI(vdi)

    # write to the scratch node
    sm.setParam("vdi", vdi, "allow-caching", "true")
    sm.setParam("vdi", vdi, "on-boot", "reset")
    _testAttachVDI(vdi, False)
    for i in range(50):
        _testWrite(vdi, size, i, "second-pass")
    _testDetachVDI(vdi)
    sm.setParam("vdi", vdi, "on-boot", "persist")
    sm.setParam("vdi", vdi, "allow-caching", "false")

    # Plug in the standby and read the block to match the "MARKER" pattern
    _testAttachVDI(vdi, False)
    _testRead(vdi, size, 49, True, "first-pass")
    _testDetachVDI(vdi)
    _testDestroyAll(sr)

def _testStandbyModeCacheOutOfSpace(sr):
    text = "Standby mode out of space"
    if not _nextTest(text): return

    size = 100 * tutil.MiB
    fillBlocks = 10
    skipBlocks = 0
    writeAmount = FULL_BLOCK_SIZE

    cacheSR = _findTargetSR("ext")
    freeSpace = leaveFreeSpace(cacheSR, 3 * tutil.MiB) # assuming 1GB SR!

    vdi = _testCreateVDI(sr, size, False)

    # write in standby mode
    sm.setParam("vdi", vdi, "allow-caching", "true")
    sm.setParam("vdi", vdi, "on-boot", "reset")
    _testAttachVDI(vdi, False)
    # should fail over during the write
    _testWritePattern(vdi, fillBlocks, skipBlocks, writeAmount)

    _testReadPattern(vdi, fillBlocks, True, skipBlocks, writeAmount)
    _testDetachVDI(vdi)

    sm.setParam("vdi", vdi, "allow-caching", "false")
    sm.setParam("vdi", vdi, "on-boot", "persist")

    _testAttachVDI(vdi, False)
    _testReadPattern(vdi, fillBlocks, True, skipBlocks, writeAmount, True)
    _testDetachVDI(vdi)

    _destroySpaceHogFile(cacheSR)
    _testDestroyAll(sr)

def _testMirrorModeCacheBasic(sr):
    """Test Mirror Mode write caching"""
    text = "Write cache base case"
    if not _nextTest(text): return
    size = 100 * tutil.MiB
    fillBlocks = 50
    skipBlocks = 1
    writeAmount = PART_BLOCK_SIZE
    vdi = _testCreateVDI(sr, size, False)
    sm.setParam("vdi", vdi, "allow-caching", "false")
    vdiSnap = _testSnapshotVDI(sr, vdi, False)

    # prefill the leaf without mirroring first
    _testAttachVDI(vdi, False)
    _testWritePattern(vdi, fillBlocks, skipBlocks, writeAmount, True)
    _testDetachVDI(vdi)

    # write in mirror mode
    sm.setParam("vdi", vdi, "allow-caching", "true")
    _testAttachVDI(vdi, False)
    _testWritePattern(vdi, fillBlocks, skipBlocks, writeAmount)
    _testDetachVDI(vdi)

    sm.setParam("vdi", vdi, "allow-caching", "false")

    # check the primary node
    _testAttachVDI(vdi, False)
    _testReadPattern(vdi, fillBlocks, True, skipBlocks, writeAmount, True)
    _testDetachVDI(vdi)

    # Now read from the local node only and to ensure that it has the same data
    tmpVDI = _testCreateVDI(sr, size, False)
    tmpVHD = sm.getPathVDI(sr, tmpVDI)
    cacheSR = _findTargetSR("ext")
    cacheDir = sm.getPathSR(cacheSR)
    writeCachePath = "%s/%s.vhdcache" % (cacheDir, vdi)
    cmd = "vhd-util modify -n %s -p %s" % (writeCachePath, tmpVHD)
    text = tutil.execCmd(cmd, 0, logger, storagemanager.LOG_LEVEL_CMD)

    # rename the cache so that we can plug it as a regular VDI
    newUuid = util.gen_uuid()
    newPath = "%s/%s.vhd" % (cacheDir, newUuid)
    logger.log("Renaming read cache %s => %s" % (writeCachePath, newPath))
    os.rename(writeCachePath, newPath)
    sm.refreshSR(cacheSR)
    sm.learnVDI(newUuid)
    time.sleep(3) # give time for the scan to complete

    _testAttachVDI(newUuid, False)
    _testReadPattern(newUuid, fillBlocks, True, skipBlocks, writeAmount, True)
    _testDetachVDI(newUuid)

    logger.log("Renaming back %s => %s" % (newPath, writeCachePath))
    os.rename(newPath, writeCachePath)
    sm.refreshSR(cacheSR)
    sm.unlearnVDI(newUuid)

    _testDestroyAll(sr)

def _testMirrorModeCacheOutOfSpace(sr):
    text = "Write cache out of space"
    if not _nextTest(text): return

    size = 100 * tutil.MiB
    fillBlocks = 3
    skipBlocks = 0
    writeAmount = FULL_BLOCK_SIZE

    vdi = _testCreateVDI(sr, size, False)
    sm.setParam("vdi", vdi, "allow-caching", "false")
    vdiSnap = _testSnapshotVDI(sr, vdi, False)

    cacheSR = _findTargetSR("ext")
    freeSpace = leaveFreeSpace(cacheSR, 3 * tutil.MiB) # assuming 1GB SR!

    # write in mirror mode
    sm.setParam("vdi", vdi, "allow-caching", "true")
    _testAttachVDI(vdi, False)
    # should fail over after writing first block
    _testWritePattern(vdi, fillBlocks, skipBlocks, writeAmount)
    _testReadPattern(vdi, fillBlocks, True, skipBlocks, writeAmount)
    _testDetachVDI(vdi)

    sm.setParam("vdi", vdi, "allow-caching", "false")

    # Now read from the local node only and to ensure that it has the first 
    # block
    tmpVDI = _testCreateVDI(sr, size, False)
    tmpVHD = sm.getPathVDI(sr, tmpVDI)
    cacheSR = _findTargetSR("ext")
    cacheDir = sm.getPathSR(cacheSR)
    writeCachePath = "%s/%s.vhdcache" % (cacheDir, vdi)
    cmd = "vhd-util modify -n %s -p %s" % (writeCachePath, tmpVHD)
    text = tutil.execCmd(cmd, 0, logger, storagemanager.LOG_LEVEL_CMD)

    # rename the cache so that we can plug it as a regular VDI
    newUuid = util.gen_uuid()
    newPath = "%s/%s.vhd" % (cacheDir, newUuid)
    logger.log("Renaming read cache %s => %s" % (writeCachePath, newPath))
    os.rename(writeCachePath, newPath)
    sm.refreshSR(cacheSR)
    sm.learnVDI(newUuid)
    time.sleep(3) # give time for the scan to complete

    _testAttachVDI(newUuid, False)
    _testReadPattern(newUuid, fillBlocks, True, skipBlocks, writeAmount, True)
    _testDetachVDI(newUuid)

    logger.log("Renaming back %s => %s" % (newPath, writeCachePath))
    os.rename(newPath, writeCachePath)
    sm.refreshSR(cacheSR)
    sm.unlearnVDI(newUuid)
    _destroySpaceHogFile(cacheSR)

    _testDestroyAll(sr)

WORKER_TYPE_ATTACH_DETACH = "worker1"
WORKER_TYPE_SNAPSHOT_DESTROY = "worker2"
WORKER_DIR = "/tmp"
WORKER_LOG_FILE = "log."
WORKER_ABORT_FILE = "abort-signal"
WORKER_FAIL_FILE = "fail."
WORKER_SUCCESS_FILE = "success."

def _checkAbort():
    files = os.listdir("/tmp")
    return WORKER_ABORT_FILE in files

def _doAttachDetachLoop(sr, vdi, numIters):
    for i in range(numIters):
        if _checkAbort():
            logger.log("Abort signaled - aborting")
            break
        try:
            logger.log("Iteration %d" % i)
            _testAttachVDI(vdi, False)
            _testDetachVDI(vdi)
        except Exception, e:
            logger.log("Failed: %s" % e)
            open("%s/%s%d" % (WORKER_DIR, WORKER_FAIL_FILE, os.getpid()), 'w').close()
            return
    logger.log("Completed successfully")
    open("%s/%s%d" % (WORKER_DIR, WORKER_SUCCESS_FILE, os.getpid()), 'w').close()

def _doSnapshotDestroyLoop(sr, vdi, numIters):
    for i in range(numIters):
        if _checkAbort():
            logger.log("Abort signaled - aborting")
            break
        try:
            logger.log("Iteration %d" % i)
            vdiSnap = _testSnapshotVDI(sr, vdi, False)
            sm.destroyVDI(vdiSnap)
        except Exception, e:
            logger.log("Failed: %s" % e)
            open("%s/%s%d" % (WORKER_DIR, WORKER_FAIL_FILE, os.getpid()), 'w').close()
            return
    logger.log("Completed successfully")
    open("%s/%s%d" % (WORKER_DIR, WORKER_SUCCESS_FILE, os.getpid()), 'w').close()

def _createWorker(sr, workerType, vdi, numIters, vbdLetter):
    global logger
    global sm
    pid = os.fork()
    if pid:
        logger.log("New %s for VDI %s created: PID %d" % (workerType, vdi, pid))
        return pid
    else:
        os.setpgrp()
        logger = tutil.Logger("%s/%s%d" % (WORKER_DIR, WORKER_LOG_FILE, os.getpid()), 3)
        sm.logger = logger
        sm.availableVBDLetters = [vbdLetter]
        if workerType == WORKER_TYPE_ATTACH_DETACH:
            _doAttachDetachLoop(sr, vdi, numIters)
        else:
            _doSnapshotDestroyLoop(sr, vdi, numIters)
        os._exit(0)

def _killAll(pids):
    for pid in pids:
        try:
            os.killpg(pid, signal.SIGKILL)
            logger.log("Killed PID %d" % pid)
        except Exception, e:
            logger.log("Error killing PID %d: %s" % (pid, e))

def _getStatus(pid):
    status = ""
    ext = ".%d" % pid
    files = filter(lambda x: x.endswith(ext), os.listdir("/tmp"))
    if len(files) == 0:
        return "none"
    successFile = "%s%d" % (WORKER_SUCCESS_FILE, pid)
    failFile = "%s%d" % (WORKER_FAIL_FILE, pid)
    if (not successFile in files) or (failFile in files):
        logger.log("%s, %s, %s" % (successFile, failFile, repr(files)))
        return "fail" # don't delete the temp files

    for name in files:
        os.unlink("%s/%s" % (WORKER_DIR, name))
    return "success"

def _testPause(sr, numVDIs, numIters):
    text = "Concurrent operations to test pause: %d VDIs, %d iterations" % (numVDIs, numIters)
    if not _nextTest(text): return

    size = 10 * tutil.MiB
    success = True
    pids = []
    vdis = []
    if WORKER_ABORT_FILE in os.listdir(WORKER_DIR):
        os.unlink("%s/%s" % (WORKER_DIR, WORKER_ABORT_FILE))

    for i in range(numVDIs):
        vdi = _testCreateVDI(sr, size, False)
        vdis.append(vdi)

    try:
        for i in range(numVDIs):
            pid = _createWorker(sr, WORKER_TYPE_ATTACH_DETACH, vdis[i], numIters, chr(ord('a') + i))
            pids.append(pid)
            pid = _createWorker(sr, WORKER_TYPE_SNAPSHOT_DESTROY, vdis[i], numIters, chr(ord('a') + i))
            pids.append(pid)
    except Exception, e:
        logger.log("Exception: %s, aborting workers" % e)
        open("%s/%s" % (WORKER_DIR, WORKER_ABORT_FILE), 'w').close()
        success = False
        #_killAll(pids)
        #raise

    # wait for all the worker processes to die
    while len(pids):
        pid, ret = os.wait()
        status = _getStatus(pid)
        logger.log("Worker %d done, status: %s" % (pid, status))
        pids.remove(pid)
        if status != "success":
            success = False
            open("%s/%s" % (WORKER_DIR, WORKER_ABORT_FILE), 'w').close()

    if not success:
        raise TestException("One or more workers did not succeed")

    _testDestroyAll(sr)


def runTestSR(sr):
    """Test SR ops"""
    _runTestAttachSR(sr)
    if vmDom0["slave"]:
        logger.log("<SR.probe test not implemented on pools>", 0)
        return
    if srType == "lvhd":
        _runTestProbeSR(sr)

def runCreateTests(sr):
    logger.log("====> Test Group: Create", 0)
    _testDestroyAll(sr)
    
    rawValues = [False, True]
    if srType != "lvhd":
        rawValues = [False]
    vdis = []
    for raw in rawValues:
        for size in CREATE_SIZES:
            text = "Create "
            if raw:
                text += "Raw"
            else:
                text += "VHD"
            text += " VDI of size %d" % (size)
            if not _nextTest(text): continue
            vdi = _testCreateVDI(sr, size, raw)
            vdis.append(vdi)
            sm.refreshSR(sr)
            if size == CREATE_SIZES[1]:
                _testMultiAttach(vdi, size)

    hostTypes = ["master"]
    if vmDom0["slave"]:
        hostTypes.append("slave")
    for h in hostTypes:
        text = "Attach VDIs on %s" % h
        if not _nextTest(text): continue
        vbds = []
        for vdi in vdis:
            _testAttachVDI(vdi, False, vmDom0[h])
        logger.log("Detach VDI from %s" % h, 1)
        for vdi in vdis:
            _testDetachVDI(vdi)

    return _testDestroyAll(sr)

def runSnapshotTests(sr):
    logger.log("====> Test Group: Snapshot", 0)

    rawValues = [False, True]
    if srType != "lvhd":
        rawValues = [False]
    liveValues = [False, True]
    writeValues = [False, True]
    for raw in rawValues:
        for live in liveValues:
            for write in writeValues:
                for size in SNAPSHOT_SIZES:
                    _testSnapshot(sr, raw, live, write, size, \
                            SNAPSHOT_NUM_ITERS)

    if srType == "lvhd":
        for raw in rawValues:
            for live in liveValues:
                for write in writeValues:
                    for size in SNAPSHOT_SIZES:
                        _testSnapshotSingle(sr, raw, live, write, size)

        _testSnapshotInsufficientSpace(sr)
        _testSnapshotClobberBase(sr)
        try:
            for single in [False, True]:
                for raw in [False, True]:
                    for live in [False]:
                        for complexity in [0, 1, 2]:
                            for recovery in [False, True]:
                                _testSnapshotFIST(sr, single, raw, live, \
                                        complexity, recovery)
        finally:
            for fistPoint in SNAPSHOT_FIST_POINTS.keys():
                setFistPoint(fistPoint, False)
            for fistPoint in SNAPSHOT_RECOVERY_FIST_POINTS:
                setFistPoint(fistPoint, False)

def runResizeTests(sr):
    logger.log("====> Test Group: Resize", 0)
    rawValues = [False, True]
    if srType != "lvhd":
        rawValues = [False]
    liveValues = [False]
    for raw in rawValues:
        for live in liveValues:
            _testResize(sr, raw, live, RESIZE_SNAPSHOTS)

    for size in RESIZE_PREFILL_SIZES:
        _testResizePrefill(sr, size)

    _testResizeShrink(sr)
    if srType == "lvhd":
        _testResizeInsufficientSpace(sr)

def runPauseTests(sr):
    logger.log("====> Test Group: Pause", 0)
    numVDIs = 10
    numIters = 100
    _testPause(sr, numVDIs, numIters)

def runCoalesceTests(sr):
    logger.log("====> Test Group: Coalesce", 0)

    rawVals = [False, True]
    resizeVals = [0, 100 * tutil.MiB]
    if srType != "lvhd":
        rawVals = [False]
    size = 30 * tutil.MiB
    for raw in rawVals:
        for live in [False, True]:
            for num in [1, 10]:
                for diff in resizeVals:
                    if live and diff:
                        continue
                    _testCoalesce(sr, size, raw, live, num, diff)

    for live in [False, True]:
        _testCoalesceRelinkNonleaf(sr, size, live)
    for live in [False, True]:
        _testCoalesceNonRoot(sr, size, live)
    for live in [False, True]:
        _testCoalesceRandomIO(sr, COALESCE_RND_SIZE, live)

def runLeafTests(sr):
    logger.log("====> Test Group: Leaf coalesce", 0)

    rawVals = [False, True]
    if srType != "lvhd":
        rawVals = [False]
    liveVals = [False, True]
    resizeVals = [0, 100 * tutil.MiB]
    writeBlocks = [1, 100]
    for raw in rawVals:
        for live in liveVals:
            for diff in resizeVals:
                for write in writeBlocks:
                    if diff and live:
                        continue # not supported
                    _testLeafCoalesce(sr, raw, live, diff, write)

    for fistPoint in COALEAF_CONCURRENCY_FIST_POINTS:
        for raw in rawVals:
            for live in liveVals:
                for action in ["snap", "destroy"]:
                    for write in [False, True]:
                        if live and action == "destroy":
                            continue
                        try:
                            _testLeafCoalesceConcurrency1(sr, fistPoint, raw, \
                                    live, action, write)
                        finally:
                            for fp in COALEAF_CONCURRENCY_FIST_POINTS:
                                setFistPoint(fp, False)

    for raw in rawVals:
        for live in liveVals:
            for diff in resizeVals:
                for action in ["attach", "snap", "resize", "destroy"]:
                    if live and (diff or action != "snap"):
                        continue
                    _testLeafCoalesceConcurrency2(sr, raw, live, diff, action)

    for raw in rawVals:
        _testLeafCoalesceInsufficientSpace(sr, raw)

    try:
        for raw in rawVals:
            for live in liveVals:
                for recovery in [False]: #, True]:
                    _testLeafCoalesceFIST(sr, raw, live, recovery)
    finally:
        for fistPoint in COALEAF_FIST_POINTS:
            setFistPoint(fistPoint, False)
        setFistPoint("LVHDRT_coaleaf_stop_after_recovery", False)

def runReadCacheTests(sr):
    logger.log("====> Test Group: Read Caching", 0)
    for  chainSize in [1]: #, 2]:
        for skipBlocks in [0, 2]:
            for writeAmount in [FULL_BLOCK_SIZE, PART_BLOCK_SIZE]:
                _testReadCache(sr, chainSize, skipBlocks, writeAmount)

def runMirrorCacheTests(sr):
    logger.log("====> Test Group: Mirror Mode Write Caching", 0)
    _testMirrorModeCacheBasic(sr)
    _testMirrorModeCacheOutOfSpace(sr)

def runStandbyCacheTests(sr):
    logger.log("====> Test Group: Standby Mode Write Caching", 0)
    _testStandbyModeCacheBasic(sr)
    _testStandbyModeCacheOutOfSpace(sr)

def runCacheTests(sr):
    runReadCacheTests(sr)
    runMirrorCacheTests(sr)
    runStandbyCacheTests(sr)

def runJournalTests(sr):
    logger.log("====> Test Group: VHD-journaling", 0)

    initSize = 100 * tutil.MiB
    for fistPoint in RESIZE_FIST_POINTS:
        for newSize in [1 * tutil.GiB, 10 * tutil.GiB]:
            _testJournalResize(sr, initSize, newSize, fistPoint)

def usage():
    print "Params: -t lvhd|lvm|ext|nfs -m basic|extended|coalesce|jvhd " \
        "[-v 1..4 log verbosity (default 3)] " \
        "[-a NUM skip to test NUM] [-b NUM stop after test NUM] " \
        "[-h print this help]"
    print
    print "The modes are: \n" \
        " - basic:    tests SR attach,detach,probe; " \
        "VDI create,snapshot,resize (LVHD only)\n"\
        " - pause:    tests concurrent attach/detach and snapshot/delete\n" \
        " - extended: same as basic, but don't skip long disk checks and " \
        "add more parameter values (LVHD only)\n" \
        " - coalesce: test coalescing\n" \
        " - caching: test local caching\n" \
        " - jvhd:     test VHD journaling (LVHD only)\n"
    print
    print "The script expects an empty SR of the specified type to be " \
        "available (if there are multiple SRs of the specified type, the " \
        "default SR is used if it is the right type). " \
        "No cleanup is performed upon a failure to assist debugging."
    sys.exit(0)

def main():
    global logger
    global vmDom0
    global thisHost
    global testMode
    global skipTo, stopAfter
    global srType
    global sm
    testSR = False
    testCreate = False
    testSnapshot = False
    testResize = False
    testPause = False
    testCoalesce = False
    testCaching = False
    testJVHD = False
    verbosity = 3
    mode = ""

    try:
        opts, args = getopt.getopt(sys.argv[1:], "v:t:m:a:b:h", "")
    except getopt.GetoptError:
        usage()

    for o, a in opts:
        if o in ["-t"]:
            srType = a
        if o in ["-m"]:
            testMode = a
        if o in ["-v"]:
            verbosity = int(a)
        if o in ["-a"]:
            skipTo = int(a)
        if o in ["-b"]:
            stopAfter = int(a)
        if o in ["-h"]:
            usage()

    if not srType.replace("oiscsi", "") in ["lvhd", "ext", "lvm", "nfs"]:
        usage()
    if not testMode in ["basic", "pause", "extended", "coalesce", "caching", "jvhd"]:
        usage()

    logger = tutil.Logger(LOG_FILE, verbosity)
    print "Log file in %s" % LOG_FILE
    logger.log("Testing: %s" % testMode, 0)
    if skipTo:
        logger.log("Skipping to test %d" % skipTo, 0)
    if stopAfter < 100000:
        logger.log("Will stop after test %d" % stopAfter, 0)

    sm = storagemanager.StorageManager.getInstance(logger)
    masterVM, slaveVM = sm.getVMs()
    if slaveVM:
        if sm.getThisDom0() == masterVM:
            logger.log("Running on the master of a pool", 0)
        else:
            thisHost = "slave"
            logger.log("Running on a slave in a pool", 0)
    srTypeActual = srType
    if srType.startswith("lvm") or srType.startswith("lvhd"):
        srType = "lvhd"

    vmDom0["master"] = masterVM
    vmDom0["slave"] = slaveVM

    if testMode in ["basic", "extended"]:
        testSR = True
        testCreate = True
        testSnapshot = True
        testResize = True
    elif testMode in ["pause"]:
        testPause = True
    elif testMode in ["coalesce"]:
        testCoalesce = True
    elif testMode in ["caching"]:
        testCaching = True
    elif testMode in ["jvhd"]:
        if srType != "lvhd":
            raise TestException("VHD journaling tests only available for LVHD")
        testJVHD = True

    success = True
    startTime = time.time()
    try:
        sr = _findTargetSR(srTypeActual)
        if not sr:
            return 1
        if testSR:
            runTestSR(sr)

        setFistPoint("testsm_clone_allow_raw", True)

        if testCreate:
            runCreateTests(sr)
        if testSnapshot:
            runSnapshotTests(sr)
        if testResize:
            runResizeTests(sr)
        if testPause:
            runPauseTests(sr)
        if testCoalesce:
            runLeafTests(sr)
            runCoalesceTests(sr)
        if testCaching:
            if srType != "nfs":
                raise TestException("Caching tests only available for NFS SR")
            runCacheTests(sr)
        if testJVHD:
            runJournalTests(sr)
    except (tutil.CommandException, storagemanager.SMException,
            util.SMException, TestException):
        info = sys.exc_info()
        tb = reduce(lambda a, b: "%s%s" % (a, b), traceback.format_tb(info[2]))
        logger.log("Error: %s" % info[0], 0)
        logger.log("Description: %s" % info[1], 0)
        logger.log("Stack trace:\n%s" % tb, 0)
        success = False
    except StopRequest, e:
        logger.log("Stop requested: %s" % e, 0)
        pass

    setFistPoint("testsm_clone_allow_raw", False)

    endTime = time.time()
    totalTime = int(endTime - startTime)
    strTotalTime = ""
    if totalTime > 3600:
        strTotalTime += "%d:" % (totalTime / 3600)
        totalTime = totalTime % 3600
    strTotalTime += "%02d:" % (totalTime / 60)
    totalTime = totalTime % 60
    strTotalTime += "%02d" % totalTime
    logger.log("Total time: %s" % strTotalTime, 0)
    logger.log("", 0)

    if success:
        logger.log("PASS", 0)
        return 0

    logger.log("FAIL", 0)
    return 1

main()