Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

2254

2255

2256

2257

2258

2259

2260

2261

2262

2263

2264

2265

2266

2267

2268

2269

2270

2271

2272

2273

2274

2275

2276

2277

2278

2279

2280

2281

2282

2283

2284

2285

2286

2287

2288

2289

2290

2291

2292

2293

2294

2295

2296

2297

2298

2299

2300

2301

2302

2303

2304

2305

2306

2307

2308

2309

2310

2311

2312

2313

2314

2315

2316

2317

2318

2319

2320

2321

2322

2323

2324

2325

2326

2327

2328

2329

2330

2331

2332

2333

2334

2335

2336

2337

2338

2339

2340

2341

2342

2343

2344

2345

2346

2347

2348

2349

2350

2351

2352

2353

2354

2355

2356

2357

2358

2359

2360

2361

2362

2363

2364

2365

2366

2367

2368

2369

2370

2371

2372

2373

2374

2375

2376

2377

2378

2379

2380

2381

2382

2383

2384

2385

2386

2387

2388

2389

2390

2391

2392

2393

2394

2395

2396

2397

2398

2399

2400

2401

2402

2403

2404

2405

2406

2407

2408

2409

2410

2411

2412

2413

2414

2415

2416

2417

2418

2419

2420

2421

2422

2423

2424

2425

2426

2427

2428

2429

2430

2431

2432

2433

2434

2435

2436

2437

2438

2439

2440

2441

2442

2443

2444

2445

2446

2447

2448

2449

2450

2451

2452

2453

2454

2455

2456

2457

2458

2459

2460

2461

2462

2463

2464

2465

2466

2467

2468

2469

2470

2471

2472

2473

2474

2475

2476

2477

2478

2479

2480

2481

2482

2483

2484

2485

2486

2487

2488

2489

2490

2491

2492

2493

2494

2495

2496

2497

2498

2499

2500

2501

2502

2503

2504

2505

2506

2507

2508

2509

2510

2511

2512

2513

2514

2515

2516

2517

2518

2519

2520

2521

2522

2523

2524

2525

2526

2527

2528

2529

2530

2531

2532

2533

2534

2535

2536

2537

2538

2539

2540

2541

2542

2543

2544

2545

2546

2547

2548

2549

2550

2551

2552

2553

2554

2555

2556

2557

2558

2559

2560

2561

2562

2563

2564

2565

2566

2567

2568

2569

2570

2571

2572

2573

2574

2575

2576

2577

2578

2579

2580

2581

2582

2583

2584

2585

2586

2587

2588

2589

2590

2591

2592

2593

2594

2595

2596

2597

2598

2599

2600

2601

2602

2603

2604

2605

2606

2607

2608

2609

2610

2611

2612

2613

2614

2615

2616

2617

2618

2619

2620

2621

2622

2623

2624

2625

2626

2627

2628

2629

2630

2631

2632

2633

2634

2635

2636

2637

2638

2639

2640

2641

2642

2643

2644

2645

2646

2647

2648

2649

2650

2651

2652

2653

2654

2655

2656

2657

2658

2659

2660

2661

2662

2663

2664

2665

2666

2667

2668

2669

2670

2671

2672

2673

2674

2675

2676

2677

2678

2679

2680

2681

2682

2683

2684

2685

2686

2687

2688

2689

2690

2691

2692

2693

2694

2695

2696

2697

2698

2699

2700

2701

2702

2703

2704

2705

2706

2707

2708

2709

2710

2711

2712

2713

2714

2715

2716

2717

2718

2719

2720

2721

2722

2723

2724

2725

2726

2727

2728

2729

2730

2731

2732

2733

2734

2735

2736

2737

2738

2739

2740

2741

2742

2743

2744

2745

2746

2747

2748

2749

2750

2751

2752

2753

2754

2755

2756

2757

2758

2759

2760

2761

2762

2763

2764

2765

2766

2767

2768

2769

2770

2771

2772

2773

2774

2775

2776

2777

2778

2779

2780

2781

2782

2783

2784

2785

2786

2787

2788

2789

2790

2791

2792

2793

2794

2795

2796

2797

2798

2799

2800

2801

2802

2803

2804

2805

2806

2807

2808

2809

2810

2811

2812

2813

2814

2815

2816

2817

2818

2819

2820

2821

2822

2823

2824

2825

2826

2827

2828

2829

2830

2831

2832

2833

2834

2835

2836

2837

2838

2839

2840

2841

2842

2843

2844

2845

2846

2847

2848

2849

2850

2851

2852

2853

2854

2855

2856

2857

2858

2859

2860

2861

2862

2863

2864

2865

2866

2867

2868

2869

2870

2871

2872

2873

2874

2875

2876

2877

2878

2879

2880

2881

2882

2883

2884

2885

2886

2887

2888

2889

2890

2891

2892

2893

2894

2895

2896

2897

2898

2899

2900

2901

2902

2903

2904

2905

2906

2907

2908

2909

2910

2911

2912

2913

2914

2915

2916

2917

2918

2919

2920

2921

2922

2923

2924

2925

2926

2927

2928

2929

2930

2931

2932

2933

2934

2935

2936

2937

2938

2939

2940

2941

2942

2943

2944

2945

2946

2947

2948

2949

2950

2951

2952

2953

2954

2955

2956

2957

2958

2959

2960

2961

2962

2963

2964

2965

2966

2967

2968

2969

2970

2971

2972

2973

2974

2975

2976

2977

2978

2979

2980

2981

2982

2983

2984

2985

2986

2987

2988

2989

2990

2991

2992

2993

2994

2995

2996

2997

2998

2999

3000

3001

3002

3003

3004

3005

3006

3007

3008

3009

3010

3011

3012

3013

3014

3015

3016

3017

3018

3019

3020

3021

3022

3023

3024

3025

3026

3027

3028

3029

3030

3031

3032

3033

3034

3035

3036

3037

3038

3039

3040

3041

3042

3043

3044

3045

3046

3047

3048

3049

3050

3051

3052

3053

3054

3055

3056

3057

3058

3059

3060

3061

3062

3063

3064

3065

3066

3067

3068

3069

3070

3071

3072

3073

3074

3075

3076

3077

3078

3079

3080

3081

3082

3083

3084

3085

3086

3087

3088

3089

3090

3091

3092

3093

3094

3095

3096

3097

3098

3099

3100

3101

3102

3103

3104

3105

3106

3107

3108

3109

3110

3111

3112

3113

3114

3115

3116

3117

3118

3119

3120

3121

3122

3123

3124

3125

3126

3127

3128

3129

3130

3131

3132

3133

3134

3135

3136

3137

3138

3139

3140

3141

3142

3143

3144

3145

3146

3147

3148

3149

3150

3151

3152

3153

3154

3155

3156

3157

3158

3159

3160

3161

3162

3163

3164

3165

3166

3167

3168

3169

3170

3171

3172

3173

3174

3175

3176

3177

3178

3179

3180

3181

3182

3183

3184

3185

3186

3187

3188

3189

3190

3191

3192

3193

3194

3195

3196

3197

3198

3199

3200

3201

3202

3203

3204

3205

3206

3207

3208

3209

3210

3211

3212

3213

3214

3215

3216

3217

3218

3219

3220

3221

3222

3223

3224

3225

3226

3227

3228

3229

3230

3231

3232

3233

3234

3235

3236

3237

3238

3239

3240

3241

3242

3243

3244

3245

3246

3247

3248

3249

3250

3251

3252

3253

3254

3255

3256

3257

3258

3259

3260

3261

3262

3263

3264

3265

3266

3267

3268

3269

3270

3271

3272

3273

3274

3275

3276

3277

3278

3279

3280

3281

3282

3283

3284

3285

3286

3287

3288

3289

3290

3291

3292

3293

3294

3295

3296

3297

3298

3299

3300

3301

3302

3303

3304

3305

3306

3307

3308

3309

3310

3311

3312

3313

3314

3315

3316

3317

3318

3319

3320

3321

3322

3323

3324

3325

3326

3327

3328

3329

3330

3331

3332

3333

3334

3335

3336

3337

3338

3339

3340

3341

3342

3343

3344

3345

3346

3347

3348

3349

3350

3351

3352

3353

3354

3355

3356

3357

3358

3359

3360

3361

3362

3363

3364

3365

3366

3367

3368

3369

3370

3371

3372

3373

3374

3375

3376

3377

3378

3379

3380

3381

3382

3383

3384

3385

3386

3387

3388

3389

3390

3391

3392

3393

3394

3395

3396

3397

3398

3399

3400

3401

3402

3403

3404

3405

3406

3407

3408

3409

3410

3411

3412

3413

3414

3415

3416

3417

3418

3419

3420

3421

3422

3423

3424

3425

3426

3427

3428

3429

3430

3431

3432

3433

3434

3435

3436

3437

3438

3439

3440

3441

3442

3443

3444

3445

3446

3447

3448

3449

3450

3451

3452

3453

3454

3455

3456

3457

3458

3459

3460

3461

3462

3463

3464

3465

3466

3467

3468

3469

3470

3471

3472

3473

3474

3475

3476

3477

3478

3479

3480

3481

3482

3483

3484

3485

3486

3487

3488

3489

3490

3491

3492

3493

3494

3495

3496

3497

3498

3499

3500

3501

3502

3503

3504

3505

3506

3507

3508

3509

3510

3511

3512

3513

3514

3515

3516

3517

3518

3519

3520

3521

3522

3523

3524

3525

3526

3527

3528

3529

3530

3531

3532

3533

3534

3535

3536

3537

3538

3539

3540

3541

3542

3543

3544

3545

3546

3547

3548

3549

3550

3551

3552

3553

3554

3555

3556

3557

3558

3559

3560

3561

3562

3563

3564

3565

3566

3567

3568

3569

3570

3571

3572

3573

3574

#!/usr/bin/python 

# 

# Copyright (C) Citrix Systems Inc. 

# 

# This program is free software; you can redistribute it and/or modify  

# it under the terms of the GNU Lesser General Public License as published  

# by the Free Software Foundation; version 2.1 only. 

# 

# This program is distributed in the hope that it will be useful,  

# but WITHOUT ANY WARRANTY; without even the implied warranty of  

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the  

# GNU Lesser General Public License for more details. 

# 

# You should have received a copy of the GNU Lesser General Public License 

# along with this program; if not, write to the Free Software Foundation, Inc., 

# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA 

# 

# Script to coalesce and garbage collect VHD-based SR's in the background 

# 

 

import os 

import os.path 

import sys 

import time 

import signal 

import subprocess 

import getopt 

import datetime 

import exceptions 

import traceback 

import base64 

import zlib 

import errno 

import stat 

 

import XenAPI 

import util 

import lvutil 

import vhdutil 

import lvhdutil 

import lvmcache 

import journaler 

import fjournaler 

import lock 

import blktap2 

import xs_errors 

from refcounter import RefCounter 

from ipc import IPCFlag 

from lvmanager import LVActivator 

from srmetadata import LVMMetadataHandler, VDI_TYPE_TAG 

 

try: 

    from linstorjournaler import LinstorJournaler 

    from linstorvhdutil import LinstorVhdUtil 

    from linstorvolumemanager \ 

        import LinstorVolumeManager, LinstorVolumeManagerError 

    LINSTOR_AVAILABLE = True 

except ImportError: 

    LINSTOR_AVAILABLE = False 

 

 

# Disable automatic leaf-coalescing. Online leaf-coalesce is currently not  

# possible due to lvhd_stop_using_() not working correctly. However, we leave  

# this option available through the explicit LEAFCLSC_FORCE flag in the VDI  

# record for use by the offline tool (which makes the operation safe by pausing  

# the VM first) 

AUTO_ONLINE_LEAF_COALESCE_ENABLED = True 

 

FLAG_TYPE_ABORT = "abort"     # flag to request aborting of GC/coalesce 

 

# process "lock", used simply as an indicator that a process already exists  

# that is doing GC/coalesce on this SR (such a process holds the lock, and we  

# check for the fact by trying the lock).  

LOCK_TYPE_RUNNING = "running" 

lockRunning = None 

 

# process "lock" to indicate that the GC process has been activated but may not 

# yet be running, stops a second process from being started. 

LOCK_TYPE_GC_ACTIVE = "gc_active" 

lockActive = None 

 

# Default coalesce error rate limit, in messages per minute. A zero value 

# disables throttling, and a negative value disables error reporting. 

DEFAULT_COALESCE_ERR_RATE = 1.0/60 

 

COALESCE_LAST_ERR_TAG = 'last-coalesce-error' 

COALESCE_ERR_RATE_TAG = 'coalesce-error-rate' 

VAR_RUN = "/var/run/" 

SPEED_LOG_ROOT = VAR_RUN + "{uuid}.speed_log" 

 

N_RUNNING_AVERAGE = 10 

 

NON_PERSISTENT_DIR = '/run/nonpersistent/sm' 

 

class AbortException(util.SMException): 

    pass 

 

################################################################################ 

# 

#  Util 

# 

class Util: 

    RET_RC     = 1 

    RET_STDOUT = 2 

    RET_STDERR = 4 

 

    UUID_LEN = 36 

 

    PREFIX = {"G": 1024 * 1024 * 1024, "M": 1024 * 1024, "K": 1024} 

 

    def log(text): 

        util.SMlog(text, ident="SMGC") 

    log = staticmethod(log) 

 

    def logException(tag): 

        info = sys.exc_info() 

        if info[0] == exceptions.SystemExit: 

            # this should not be happening when catching "Exception", but it is 

            sys.exit(0) 

        tb = reduce(lambda a, b: "%s%s" % (a, b), traceback.format_tb(info[2])) 

        Util.log("*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*") 

        Util.log("         ***********************") 

        Util.log("         *  E X C E P T I O N  *") 

        Util.log("         ***********************") 

        Util.log("%s: EXCEPTION %s, %s" % (tag, info[0], info[1])) 

        Util.log(tb) 

        Util.log("*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*") 

    logException = staticmethod(logException) 

 

    def doexec(args, expectedRC, inputtext=None, ret=None, log=True): 

        "Execute a subprocess, then return its return code, stdout, stderr" 

        proc = subprocess.Popen(args, 

                                stdin=subprocess.PIPE,\ 

                                stdout=subprocess.PIPE,\ 

                                stderr=subprocess.PIPE,\ 

                                shell=True,\ 

                                close_fds=True) 

        (stdout, stderr) = proc.communicate(inputtext) 

        stdout = str(stdout) 

        stderr = str(stderr) 

        rc = proc.returncode 

        if log: 

            Util.log("`%s`: %s" % (args, rc)) 

        if type(expectedRC) != type([]): 

            expectedRC = [expectedRC] 

        if not rc in expectedRC: 

            reason = stderr.strip() 

            if stdout.strip(): 

                reason = "%s (stdout: %s)" % (reason, stdout.strip()) 

            Util.log("Failed: %s" % reason) 

            raise util.CommandException(rc, args, reason) 

 

        if ret == Util.RET_RC: 

            return rc 

        if ret == Util.RET_STDERR: 

            return stderr 

        return stdout 

    doexec = staticmethod(doexec) 

 

    def runAbortable(func, ret, ns, abortTest, pollInterval, timeOut): 

        """execute func in a separate thread and kill it if abortTest signals 

        so""" 

        abortSignaled = abortTest() # check now before we clear resultFlag 

        resultFlag = IPCFlag(ns) 

        resultFlag.clearAll() 

        pid = os.fork() 

        if pid: 

            startTime = time.time() 

            try: 

                while True: 

                    if resultFlag.test("success"): 

                        Util.log("  Child process completed successfully") 

                        resultFlag.clear("success") 

                        return 

                    if resultFlag.test("failure"): 

                        resultFlag.clear("failure") 

                        raise util.SMException("Child process exited with error") 

                    if abortTest() or abortSignaled: 

                        os.killpg(pid, signal.SIGKILL) 

                        raise AbortException("Aborting due to signal") 

                    if timeOut and time.time() - startTime > timeOut: 

                        os.killpg(pid, signal.SIGKILL) 

                        resultFlag.clearAll() 

                        raise util.SMException("Timed out") 

                    time.sleep(pollInterval) 

            finally: 

                wait_pid = 0 

                rc = -1 

                count = 0 

                while wait_pid == 0 and count < 10: 

                    wait_pid, rc = os.waitpid(pid, os.WNOHANG) 

                    if wait_pid == 0: 

                        time.sleep(2) 

                        count += 1 

 

                if wait_pid == 0: 

                    Util.log("runAbortable: wait for process completion timed out") 

        else: 

            os.setpgrp() 

            try: 

                if func() == ret: 

                    resultFlag.set("success") 

                else: 

                    resultFlag.set("failure") 

            except Exception, e: 

                Util.log("Child process failed with : (%s)" % e) 

                resultFlag.set("failure") 

                Util.logException("This exception has occured") 

            os._exit(0) 

    runAbortable = staticmethod(runAbortable) 

 

    def num2str(number): 

        for prefix in ("G", "M", "K"): 

            if number >= Util.PREFIX[prefix]: 

                return "%.3f%s" % (float(number) / Util.PREFIX[prefix], prefix) 

        return "%s" % number 

    num2str = staticmethod(num2str) 

 

    def numBits(val): 

        count = 0 

        while val: 

            count += val & 1 

            val = val >> 1 

        return count 

    numBits = staticmethod(numBits) 

 

    def countBits(bitmap1, bitmap2): 

        """return bit count in the bitmap produced by ORing the two bitmaps""" 

        len1 = len(bitmap1) 

        len2 = len(bitmap2) 

        lenLong = len1 

        lenShort = len2 

        bitmapLong = bitmap1 

        if len2 > len1: 

            lenLong = len2 

            lenShort = len1 

            bitmapLong = bitmap2 

 

        count = 0 

        for i in range(lenShort): 

            val = ord(bitmap1[i]) | ord(bitmap2[i]) 

            count += Util.numBits(val) 

 

        for i in range(i + 1, lenLong): 

            val = ord(bitmapLong[i]) 

            count += Util.numBits(val) 

        return count 

    countBits = staticmethod(countBits) 

 

    def getThisScript(): 

        thisScript = util.get_real_path(__file__) 

        if thisScript.endswith(".pyc"): 

            thisScript = thisScript[:-1] 

        return thisScript 

    getThisScript = staticmethod(getThisScript) 

 

 

################################################################################ 

# 

#  XAPI 

# 

class XAPI: 

    USER = "root" 

    PLUGIN_ON_SLAVE = "on-slave" 

 

    CONFIG_SM = 0 

    CONFIG_OTHER = 1 

    CONFIG_ON_BOOT = 2 

    CONFIG_ALLOW_CACHING = 3 

 

    CONFIG_NAME = { 

            CONFIG_SM: "sm-config", 

            CONFIG_OTHER: "other-config", 

            CONFIG_ON_BOOT: "on-boot", 

            CONFIG_ALLOW_CACHING: "allow_caching" 

    } 

 

    class LookupError(util.SMException): 

        pass 

 

    def getSession(): 

        session = XenAPI.xapi_local() 

        session.xenapi.login_with_password(XAPI.USER, '', '', 'SM') 

        return session 

    getSession = staticmethod(getSession) 

 

    def __init__(self, session, srUuid): 

        self.sessionPrivate = False 

        self.session = session 

        if self.session is None: 

            self.session = self.getSession() 

            self.sessionPrivate = True 

        self._srRef = self.session.xenapi.SR.get_by_uuid(srUuid) 

        self.srRecord = self.session.xenapi.SR.get_record(self._srRef) 

        self.hostUuid = util.get_this_host() 

        self._hostRef = self.session.xenapi.host.get_by_uuid(self.hostUuid) 

 

    def __del__(self): 

        if self.sessionPrivate: 

            self.session.xenapi.session.logout() 

 

    def isPluggedHere(self): 

        pbds = self.getAttachedPBDs() 

        for pbdRec in pbds: 

            if pbdRec["host"] == self._hostRef: 

                return True 

        return False 

 

    def poolOK(self): 

        host_recs = self.session.xenapi.host.get_all_records() 

        for host_ref, host_rec in host_recs.iteritems(): 

            if not host_rec["enabled"]: 

                Util.log("Host %s not enabled" % host_rec["uuid"]) 

                return False 

        return True 

 

    def isMaster(self): 

        if self.srRecord["shared"]: 

            pool = self.session.xenapi.pool.get_all_records().values()[0] 

            return pool["master"] == self._hostRef 

        else: 

            pbds = self.getAttachedPBDs() 

            if len(pbds) < 1: 

                raise util.SMException("Local SR not attached") 

            elif len(pbds) > 1: 

                raise util.SMException("Local SR multiply attached") 

            return pbds[0]["host"] == self._hostRef 

 

    def getAttachedPBDs(self): 

        """Return PBD records for all PBDs of this SR that are currently 

        attached""" 

        attachedPBDs = [] 

        pbds = self.session.xenapi.PBD.get_all_records() 

        for pbdRec in pbds.values(): 

            if pbdRec["SR"] == self._srRef and pbdRec["currently_attached"]: 

                attachedPBDs.append(pbdRec) 

        return attachedPBDs 

 

    def getOnlineHosts(self): 

        return util.get_online_hosts(self.session) 

 

    def ensureInactive(self, hostRef, args): 

        text = self.session.xenapi.host.call_plugin( \ 

                hostRef, self.PLUGIN_ON_SLAVE, "multi", args) 

        Util.log("call-plugin returned: '%s'" % text) 

 

    def getRecordHost(self, hostRef): 

        return self.session.xenapi.host.get_record(hostRef) 

 

    def _getRefVDI(self, uuid): 

        return self.session.xenapi.VDI.get_by_uuid(uuid) 

 

    def getRefVDI(self, vdi): 

        return self._getRefVDI(vdi.uuid) 

 

    def getRecordVDI(self, uuid): 

        try: 

            ref = self._getRefVDI(uuid) 

            return self.session.xenapi.VDI.get_record(ref) 

        except XenAPI.Failure: 

            return None 

 

    def singleSnapshotVDI(self, vdi): 

        return self.session.xenapi.VDI.snapshot(vdi.getRef(), 

                {"type":"internal"}) 

 

    def forgetVDI(self, srUuid, vdiUuid): 

        """Forget the VDI, but handle the case where the VDI has already been 

        forgotten (i.e. ignore errors)""" 

        try: 

            vdiRef = self.session.xenapi.VDI.get_by_uuid(vdiUuid) 

            self.session.xenapi.VDI.forget(vdiRef) 

        except XenAPI.Failure: 

            pass 

 

    def getConfigVDI(self, vdi, key): 

        kind = vdi.CONFIG_TYPE[key] 

        if kind == self.CONFIG_SM: 

            cfg = self.session.xenapi.VDI.get_sm_config(vdi.getRef()) 

        elif kind == self.CONFIG_OTHER: 

            cfg = self.session.xenapi.VDI.get_other_config(vdi.getRef()) 

        elif kind == self.CONFIG_ON_BOOT: 

            cfg = self.session.xenapi.VDI.get_on_boot(vdi.getRef()) 

        elif kind == self.CONFIG_ALLOW_CACHING: 

            cfg = self.session.xenapi.VDI.get_allow_caching(vdi.getRef()) 

        else: 

            assert(False) 

        Util.log("Got %s for %s: %s" % (self.CONFIG_NAME[kind], vdi, repr(cfg))) 

        return cfg 

 

    def removeFromConfigVDI(self, vdi, key): 

        kind = vdi.CONFIG_TYPE[key] 

        if kind == self.CONFIG_SM: 

            self.session.xenapi.VDI.remove_from_sm_config(vdi.getRef(), key) 

        elif kind == self.CONFIG_OTHER: 

            self.session.xenapi.VDI.remove_from_other_config(vdi.getRef(), key) 

        else: 

            assert(False) 

 

    def addToConfigVDI(self, vdi, key, val): 

        kind = vdi.CONFIG_TYPE[key] 

        if kind == self.CONFIG_SM: 

            self.session.xenapi.VDI.add_to_sm_config(vdi.getRef(), key, val) 

        elif kind == self.CONFIG_OTHER: 

            self.session.xenapi.VDI.add_to_other_config(vdi.getRef(), key, val) 

        else: 

            assert(False) 

 

    def isSnapshot(self, vdi): 

        return self.session.xenapi.VDI.get_is_a_snapshot(vdi.getRef()) 

 

    def markCacheSRsDirty(self): 

        sr_refs = self.session.xenapi.SR.get_all_records_where( \ 

                'field "local_cache_enabled" = "true"') 

        for sr_ref in sr_refs: 

            Util.log("Marking SR %s dirty" % sr_ref) 

            util.set_dirty(self.session, sr_ref) 

 

    def srUpdate(self): 

        Util.log("Starting asynch srUpdate for SR %s" % self.srRecord["uuid"]) 

        abortFlag = IPCFlag(self.srRecord["uuid"]) 

        task = self.session.xenapi.Async.SR.update(self._srRef) 

        cancelTask = True 

        try: 

            for i in range(60): 

                status = self.session.xenapi.task.get_status(task) 

                if not status == "pending": 

                    Util.log("SR.update_asynch status changed to [%s]" % status) 

                    cancelTask = False 

                    return 

                if abortFlag.test(FLAG_TYPE_ABORT): 

                    Util.log("Abort signalled during srUpdate, cancelling task...") 

                    try: 

                        self.session.xenapi.task.cancel(task) 

                        cancelTask = False 

                        Util.log("Task cancelled") 

                    except: 

                        pass 

                    return 

                time.sleep(1) 

        finally: 

            if cancelTask: 

                self.session.xenapi.task.cancel(task) 

            self.session.xenapi.task.destroy(task) 

        Util.log("Asynch srUpdate still running, but timeout exceeded.") 

 

 

################################################################################ 

# 

#  VDI 

# 

class VDI: 

    """Object representing a VDI of a VHD-based SR""" 

 

    POLL_INTERVAL = 1 

    POLL_TIMEOUT  = 30 

    DEVICE_MAJOR  = 202 

    DRIVER_NAME_VHD = "vhd" 

 

    # config keys & values 

    DB_VHD_PARENT = "vhd-parent" 

    DB_VDI_TYPE = "vdi_type" 

    DB_VHD_BLOCKS = "vhd-blocks" 

    DB_VDI_PAUSED = "paused" 

    DB_GC = "gc" 

    DB_COALESCE = "coalesce" 

    DB_LEAFCLSC = "leaf-coalesce" # config key 

    LEAFCLSC_DISABLED = "false"  # set by user; means do not leaf-coalesce 

    LEAFCLSC_FORCE = "force"     # set by user; means skip snap-coalesce 

    LEAFCLSC_OFFLINE = "offline" # set here for informational purposes: means 

                                 # no space to snap-coalesce or unable to keep  

                                 # up with VDI. This is not used by the SM, it 

                                 # might be used by external components. 

    DB_ONBOOT = "on-boot" 

    ONBOOT_RESET = "reset" 

    DB_ALLOW_CACHING = "allow_caching" 

 

    CONFIG_TYPE = { 

            DB_VHD_PARENT:   XAPI.CONFIG_SM, 

            DB_VDI_TYPE:     XAPI.CONFIG_SM, 

            DB_VHD_BLOCKS:   XAPI.CONFIG_SM, 

            DB_VDI_PAUSED:   XAPI.CONFIG_SM, 

            DB_GC:           XAPI.CONFIG_OTHER, 

            DB_COALESCE:     XAPI.CONFIG_OTHER, 

            DB_LEAFCLSC:     XAPI.CONFIG_OTHER, 

            DB_ONBOOT:       XAPI.CONFIG_ON_BOOT, 

            DB_ALLOW_CACHING:XAPI.CONFIG_ALLOW_CACHING, 

    } 

 

    LIVE_LEAF_COALESCE_MAX_SIZE = 20 * 1024 * 1024 # bytes 

    LIVE_LEAF_COALESCE_TIMEOUT = 10 # seconds 

    TIMEOUT_SAFETY_MARGIN = 0.5 # extra margin when calculating 

                                # feasibility of leaf coalesce 

 

    JRN_RELINK = "relink" # journal entry type for relinking children 

    JRN_COALESCE = "coalesce" # to communicate which VDI is being coalesced 

    JRN_LEAF = "leaf" # used in coalesce-leaf 

 

    STR_TREE_INDENT = 4 

 

    def __init__(self, sr, uuid, raw): 

        self.sr         = sr 

        self.scanError  = True 

        self.uuid       = uuid 

        self.raw        = raw 

        self.fileName   = "" 

        self.parentUuid = "" 

        self.sizeVirt   = -1 

        self._sizeVHD   = -1 

        self.hidden     = False 

        self.parent     = None 

        self.children   = [] 

        self._vdiRef    = None 

        self._clearRef() 

 

    def load(self): 

        """Load VDI info""" 

        pass # abstract 

 

    def getDriverName(self): 

        return self.DRIVER_NAME_VHD 

 

    def getRef(self): 

        if self._vdiRef == None: 

            self._vdiRef = self.sr.xapi.getRefVDI(self) 

        return self._vdiRef 

 

    def getConfig(self, key, default = None): 

        config = self.sr.xapi.getConfigVDI(self, key) 

        if key == self.DB_ONBOOT or key == self.DB_ALLOW_CACHING: 

            val = config 

        else: 

            val = config.get(key) 

        if val: 

            return val 

        return default 

 

    def setConfig(self, key, val): 

        self.sr.xapi.removeFromConfigVDI(self, key) 

        self.sr.xapi.addToConfigVDI(self, key, val) 

        Util.log("Set %s = %s for %s" % (key, val, self)) 

 

    def delConfig(self, key): 

        self.sr.xapi.removeFromConfigVDI(self, key) 

        Util.log("Removed %s from %s" % (key, self)) 

 

    def ensureUnpaused(self): 

        if self.getConfig(self.DB_VDI_PAUSED) == "true": 

            Util.log("Unpausing VDI %s" % self) 

            self.unpause() 

 

    def pause(self, failfast=False): 

        if not blktap2.VDI.tap_pause(self.sr.xapi.session, self.sr.uuid, 

                self.uuid, failfast): 

            raise util.SMException("Failed to pause VDI %s" % self) 

 

    def _report_tapdisk_unpause_error(self): 

        try: 

            xapi = self.sr.xapi.session.xenapi 

            sr_ref = xapi.SR.get_by_uuid(self.sr.uuid) 

            msg_name = "failed to unpause tapdisk" 

            msg_body = "Failed to unpause tapdisk for VDI %s, " \ 

                    "VMs using this tapdisk have lost access " \ 

                    "to the corresponding disk(s)" % self.uuid 

            xapi.message.create(msg_name, "4", "SR", self.sr.uuid, msg_body) 

        except Exception, e: 

            util.SMlog("failed to generate message: %s" % e) 

 

    def unpause(self): 

        if not blktap2.VDI.tap_unpause(self.sr.xapi.session, self.sr.uuid, 

                self.uuid): 

            self._report_tapdisk_unpause_error() 

            raise util.SMException("Failed to unpause VDI %s" % self) 

 

    def refresh(self, ignoreNonexistent = True): 

        """Pause-unpause in one step""" 

        self.sr.lock() 

        try: 

            try: 

                if not blktap2.VDI.tap_refresh(self.sr.xapi.session, 

                        self.sr.uuid, self.uuid): 

                    self._report_tapdisk_unpause_error() 

                    raise util.SMException("Failed to refresh %s" % self) 

            except XenAPI.Failure, e: 

                if util.isInvalidVDI(e) and ignoreNonexistent: 

                    Util.log("VDI %s not found, ignoring" % self) 

                    return 

                raise 

        finally: 

            self.sr.unlock() 

 

    def isSnapshot(self): 

        return self.sr.xapi.isSnapshot(self) 

 

    def isAttachedRW(self): 

        return util.is_attached_rw( 

                self.sr.xapi.session.xenapi.VDI.get_sm_config(self.getRef())) 

 

    def getVHDBlocks(self): 

        val = self.updateBlockInfo() 

        bitmap = zlib.decompress(base64.b64decode(val)) 

        return bitmap 

 

    def isCoalesceable(self): 

        """A VDI is coalesceable if it has no siblings and is not a leaf""" 

        return not self.scanError and \ 

                self.parent and \ 

                len(self.parent.children) == 1 and \ 

                self.hidden and \ 

                len(self.children) > 0 

 

    def isLeafCoalesceable(self): 

        """A VDI is leaf-coalesceable if it has no siblings and is a leaf""" 

        return not self.scanError and \ 

                self.parent and \ 

                len(self.parent.children) == 1 and \ 

                not self.hidden and \ 

                len(self.children) == 0 

 

    def canLiveCoalesce(self, speed): 

        """Can we stop-and-leaf-coalesce this VDI? The VDI must be 

        isLeafCoalesceable() already""" 

        feasibleSize = False 

        allowedDownTime =\ 

                self.TIMEOUT_SAFETY_MARGIN * self.LIVE_LEAF_COALESCE_TIMEOUT 

        if speed: 

            feasibleSize =\ 

                self.getSizeVHD()/speed < allowedDownTime 

        else: 

            feasibleSize =\ 

                self.getSizeVHD() < self.LIVE_LEAF_COALESCE_MAX_SIZE 

 

        return (feasibleSize or 

                self.getConfig(self.DB_LEAFCLSC) == self.LEAFCLSC_FORCE) 

 

    def getAllPrunable(self): 

        if len(self.children) == 0: # base case 

            # it is possible to have a hidden leaf that was recently coalesced  

            # onto its parent, its children already relinked but not yet  

            # reloaded - in which case it may not be garbage collected yet:  

            # some tapdisks could still be using the file. 

            if self.sr.journaler.get(self.JRN_RELINK, self.uuid): 

                return [] 

            if not self.scanError and self.hidden: 

                return [self] 

            return [] 

 

        thisPrunable = True 

        vdiList = [] 

        for child in self.children: 

            childList = child.getAllPrunable() 

            vdiList.extend(childList) 

            if child not in childList: 

                thisPrunable = False 

 

        # We can destroy the current VDI if all childs are hidden BUT the 

        # current VDI must be hidden too to do that! 

        # Example in this case (after a failed live leaf coalesce): 

        # 

        # SMGC: [32436] SR 07ed ('linstor-nvme-sr') (2 VDIs in 1 VHD trees): 

        # SMGC: [32436]         b5458d61(1.000G/4.127M) 

        # SMGC: [32436]             *OLD_b545(1.000G/4.129M) 

        # 

        # OLD_b545 is hidden and must be removed, but b5458d61 not. 

        # Normally we are not in this function when the delete action is 

        # executed but in `_liveLeafCoalesce`. 

 

        if not self.scanError and not self.hidden and thisPrunable: 

            vdiList.append(self) 

        return vdiList 

 

    def getSizeVHD(self): 

        return self._sizeVHD 

 

    def getTreeRoot(self): 

        "Get the root of the tree that self belongs to" 

        root = self 

        while root.parent: 

            root = root.parent 

        return root 

 

    def getTreeHeight(self): 

        "Get the height of the subtree rooted at self" 

        if len(self.children) == 0: 

            return 1 

 

        maxChildHeight = 0 

        for child in self.children: 

            childHeight = child.getTreeHeight() 

            if childHeight > maxChildHeight: 

                maxChildHeight = childHeight 

 

        return maxChildHeight + 1 

 

    def getAllLeaves(self): 

        "Get all leaf nodes in the subtree rooted at self" 

        if len(self.children) == 0: 

            return [self] 

 

        leaves = [] 

        for child in self.children: 

            leaves.extend(child.getAllLeaves()) 

        return leaves 

 

    def updateBlockInfo(self): 

        val = base64.b64encode(self._queryVHDBlocks()) 

        self.setConfig(VDI.DB_VHD_BLOCKS, val) 

        return val 

 

    def rename(self, uuid): 

        "Rename the VDI file" 

        assert(not self.sr.vdis.get(uuid)) 

        self._clearRef() 

        oldUuid = self.uuid 

        self.uuid = uuid 

        self.children = [] 

        # updating the children themselves is the responsiblity of the caller 

        del self.sr.vdis[oldUuid] 

        self.sr.vdis[self.uuid] = self 

 

    def delete(self): 

        "Physically delete the VDI" 

        lock.Lock.cleanup(self.uuid, lvhdutil.NS_PREFIX_LVM + self.sr.uuid) 

        lock.Lock.cleanupAll(self.uuid) 

        self._clear() 

 

    def __str__(self): 

        strHidden = "" 

730        if self.hidden: 

            strHidden = "*" 

        strSizeVirt = "?" 

733        if self.sizeVirt > 0: 

            strSizeVirt = Util.num2str(self.sizeVirt) 

        strSizeVHD = "?" 

736        if self._sizeVHD > 0: 

            strSizeVHD = "/%s" % Util.num2str(self._sizeVHD) 

        strType = "" 

739        if self.raw: 

            strType = "[RAW]" 

            strSizeVHD = "" 

 

        return "%s%s(%s%s)%s" % (strHidden, self.uuid[0:8], strSizeVirt, 

                strSizeVHD, strType) 

 

    def validate(self, fast = False): 

        if not vhdutil.check(self.path, fast = fast): 

            raise util.SMException("VHD %s corrupted" % self) 

 

    def _clear(self): 

        self.uuid = "" 

        self.path = "" 

        self.parentUuid = "" 

        self.parent = None 

        self._clearRef() 

 

    def _clearRef(self): 

        self._vdiRef = None 

 

    def _doCoalesce(self): 

        """Coalesce self onto parent. Only perform the actual coalescing of 

        VHD, but not the subsequent relinking. We'll do that as the next step, 

        after reloading the entire SR in case things have changed while we 

        were coalescing""" 

        self.validate() 

        self.parent.validate(True) 

        self.parent._increaseSizeVirt(self.sizeVirt) 

        self.sr._updateSlavesOnResize(self.parent) 

        self._coalesceVHD(0) 

        self.parent.validate(True) 

        #self._verifyContents(0) 

        self.parent.updateBlockInfo() 

 

    def _verifyContents(self, timeOut): 

        Util.log("  Coalesce verification on %s" % self) 

        abortTest = lambda:IPCFlag(self.sr.uuid).test(FLAG_TYPE_ABORT) 

        Util.runAbortable(lambda: self._runTapdiskDiff(), True, 

                self.sr.uuid, abortTest, VDI.POLL_INTERVAL, timeOut) 

        Util.log("  Coalesce verification succeeded") 

 

    def _runTapdiskDiff(self): 

        cmd = "tapdisk-diff -n %s:%s -m %s:%s" % \ 

                (self.getDriverName(), self.path, \ 

                self.parent.getDriverName(), self.parent.path) 

        Util.doexec(cmd, 0) 

        return True 

 

    def _reportCoalesceError(vdi, ce): 

        """Reports a coalesce error to XenCenter. 

 

        vdi: the VDI object on which the coalesce error occured 

        ce: the CommandException that was raised""" 

 

        msg_name = os.strerror(ce.code) 

        if ce.code == errno.ENOSPC: 

            # TODO We could add more information here, e.g. exactly how much 

            # space is required for the particular coalesce, as well as actions 

            # to be taken by the user and consequences of not taking these 

            # actions. 

            msg_body = 'Run out of space while coalescing.' 

        elif ce.code == errno.EIO: 

            msg_body = 'I/O error while coalescing.' 

        else: 

            msg_body = '' 

        util.SMlog('Coalesce failed on SR %s: %s (%s)' 

                % (vdi.sr.uuid, msg_name, msg_body)) 

 

        # Create a XenCenter message, but don't spam. 

        xapi = vdi.sr.xapi.session.xenapi 

        sr_ref = xapi.SR.get_by_uuid(vdi.sr.uuid) 

        oth_cfg = xapi.SR.get_other_config(sr_ref) 

        if COALESCE_ERR_RATE_TAG in oth_cfg: 

            coalesce_err_rate = float(oth_cfg[COALESCE_ERR_RATE_TAG]) 

        else: 

            coalesce_err_rate = DEFAULT_COALESCE_ERR_RATE 

 

        xcmsg = False 

        if coalesce_err_rate == 0: 

            xcmsg = True 

        elif coalesce_err_rate > 0: 

            now = datetime.datetime.now() 

            sm_cfg = xapi.SR.get_sm_config(sr_ref) 

            if COALESCE_LAST_ERR_TAG in sm_cfg: 

                # seconds per message (minimum distance in time between two 

                # messages in seconds) 

                spm = datetime.timedelta(seconds=(1.0/coalesce_err_rate)*60) 

                last = datetime.datetime.fromtimestamp( 

                        float(sm_cfg[COALESCE_LAST_ERR_TAG])) 

                if now - last >= spm: 

                    xapi.SR.remove_from_sm_config(sr_ref, 

                            COALESCE_LAST_ERR_TAG) 

                    xcmsg = True 

            else: 

                xcmsg = True 

            if xcmsg: 

                xapi.SR.add_to_sm_config(sr_ref, COALESCE_LAST_ERR_TAG, 

                        str(now.strftime('%s'))) 

        if xcmsg: 

            xapi.message.create(msg_name, "3", "SR", vdi.sr.uuid, msg_body) 

    _reportCoalesceError = staticmethod(_reportCoalesceError) 

 

    def _doCoalesceVHD(vdi): 

        try: 

 

            startTime = time.time() 

            vhdSize = vdi.getSizeVHD() 

            vhdutil.coalesce(vdi.path) 

            endTime = time.time() 

            vdi.sr.recordStorageSpeed(startTime, endTime, vhdSize) 

        except util.CommandException, ce: 

            # We use try/except for the following piece of code because it runs 

            # in a separate process context and errors will not be caught and 

            # reported by anyone. 

            try: 

                # Report coalesce errors back to user via XC 

                VDI._reportCoalesceError(vdi, ce) 

            except Exception, e: 

                util.SMlog('failed to create XenCenter message: %s' % e) 

            raise ce 

        except: 

            raise 

    _doCoalesceVHD = staticmethod(_doCoalesceVHD) 

 

    def _coalesceVHD(self, timeOut): 

        Util.log("  Running VHD coalesce on %s" % self) 

        abortTest = lambda:IPCFlag(self.sr.uuid).test(FLAG_TYPE_ABORT) 

        try: 

            Util.runAbortable(lambda: VDI._doCoalesceVHD(self), None, 

                    self.sr.uuid, abortTest, VDI.POLL_INTERVAL, timeOut) 

        except: 

            #exception at this phase could indicate a failure in vhd coalesce 

            # or a kill of vhd coalesce by runAbortable due to  timeOut 

            # Try a repair and reraise the exception 

            parent = "" 

            try: 

                parent = vhdutil.getParent(self.path, lambda x: x.strip()) 

                # Repair error is logged and ignored. Error reraised later 

                util.SMlog('Coalesce failed on %s, attempting repair on ' \ 

                           'parent %s' % (self.uuid, parent)) 

                vhdutil.repair(parent) 

            except Exception, e: 

                util.SMlog('(error ignored) Failed to repair parent %s ' \ 

                           'after failed coalesce on %s, err: %s' % 

                           (parent, self.path, e)) 

            raise 

 

        util.fistpoint.activate("LVHDRT_coalescing_VHD_data",self.sr.uuid) 

 

    def _relinkSkip(self): 

        """Relink children of this VDI to point to the parent of this VDI""" 

        abortFlag = IPCFlag(self.sr.uuid) 

        for child in self.children: 

            if abortFlag.test(FLAG_TYPE_ABORT): 

                raise AbortException("Aborting due to signal") 

            Util.log("  Relinking %s from %s to %s" % \ 

                    (child, self, self.parent)) 

            util.fistpoint.activate("LVHDRT_relinking_grandchildren",self.sr.uuid) 

            child._setParent(self.parent) 

        self.children = [] 

 

    def _reloadChildren(self, vdiSkip): 

        """Pause & unpause all VDIs in the subtree to cause blktap to reload 

        the VHD metadata for this file in any online VDI""" 

        abortFlag = IPCFlag(self.sr.uuid) 

        for child in self.children: 

            if child == vdiSkip: 

                continue 

            if abortFlag.test(FLAG_TYPE_ABORT): 

                raise AbortException("Aborting due to signal") 

            Util.log("  Reloading VDI %s" % child) 

            child._reload() 

 

    def _reload(self): 

        """Pause & unpause to cause blktap to reload the VHD metadata""" 

        for child in self.children: 

            child._reload() 

 

        # only leaves can be attached 

        if len(self.children) == 0: 

            self.refresh() 

 

    def _loadInfoParent(self): 

        ret = vhdutil.getParent(self.path, lvhdutil.extractUuid) 

        if ret: 

            self.parentUuid = ret 

 

    def _setParent(self, parent): 

        vhdutil.setParent(self.path, parent.path, False) 

        self.parent = parent 

        self.parentUuid = parent.uuid 

        parent.children.append(self) 

        try: 

            self.setConfig(self.DB_VHD_PARENT, self.parentUuid) 

            Util.log("Updated the vhd-parent field for child %s with %s" % \ 

                     (self.uuid, self.parentUuid)) 

        except: 

            Util.log("Failed to update %s with vhd-parent field %s" % \ 

                     (self.uuid, self.parentUuid)) 

 

    def _loadInfoHidden(self): 

        hidden = vhdutil.getHidden(self.path) 

        self.hidden = (hidden != 0) 

 

    def _setHidden(self, hidden = True): 

        vhdutil.setHidden(self.path, hidden) 

        self.hidden = hidden 

 

    def _increaseSizeVirt(self, size, atomic = True): 

        """ensure the virtual size of 'self' is at least 'size'. Note that  

        resizing a VHD must always be offline and atomically: the file must 

        not be open by anyone and no concurrent operations may take place. 

        Thus we use the Agent API call for performing paused atomic  

        operations. If the caller is already in the atomic context, it must 

        call with atomic = False""" 

        if self.sizeVirt >= size: 

            return 

        Util.log("  Expanding VHD virt size for VDI %s: %s -> %s" % \ 

                (self, Util.num2str(self.sizeVirt), Util.num2str(size))) 

 

        msize = vhdutil.getMaxResizeSize(self.path) * 1024 * 1024 

        if (size <= msize): 

            vhdutil.setSizeVirtFast(self.path, size) 

        else: 

            if atomic: 

                vdiList = self._getAllSubtree() 

                self.sr.lock() 

                try: 

                    self.sr.pauseVDIs(vdiList) 

                    try: 

                        self._setSizeVirt(size) 

                    finally: 

                        self.sr.unpauseVDIs(vdiList) 

                finally: 

                    self.sr.unlock() 

            else: 

                self._setSizeVirt(size) 

 

        self.sizeVirt = vhdutil.getSizeVirt(self.path) 

 

    def _setSizeVirt(self, size): 

        """WARNING: do not call this method directly unless all VDIs in the 

        subtree are guaranteed to be unplugged (and remain so for the duration 

        of the operation): this operation is only safe for offline VHDs""" 

        jFile = os.path.join(self.sr.path, self.uuid) 

        vhdutil.setSizeVirt(self.path, size, jFile) 

 

    def _queryVHDBlocks(self): 

        return vhdutil.getBlockBitmap(self.path) 

 

    def _getCoalescedSizeData(self): 

        """Get the data size of the resulting VHD if we coalesce self onto 

        parent. We calculate the actual size by using the VHD block allocation 

        information (as opposed to just adding up the two VHD sizes to get an 

        upper bound)""" 

        # make sure we don't use stale BAT info from vdi_rec since the child  

        # was writable all this time 

        self.delConfig(VDI.DB_VHD_BLOCKS) 

        blocksChild = self.getVHDBlocks() 

        blocksParent = self.parent.getVHDBlocks() 

        numBlocks = Util.countBits(blocksChild, blocksParent) 

        Util.log("Num combined blocks = %d" % numBlocks) 

        sizeData = numBlocks * vhdutil.VHD_BLOCK_SIZE 

        assert(sizeData <= self.sizeVirt) 

        return sizeData 

 

    def _calcExtraSpaceForCoalescing(self): 

        sizeData = self._getCoalescedSizeData() 

        sizeCoalesced = sizeData + vhdutil.calcOverheadBitmap(sizeData) + \ 

                vhdutil.calcOverheadEmpty(self.sizeVirt) 

        Util.log("Coalesced size = %s" % Util.num2str(sizeCoalesced)) 

        return sizeCoalesced - self.parent.getSizeVHD() 

 

    def _calcExtraSpaceForLeafCoalescing(self): 

        """How much extra space in the SR will be required to 

        [live-]leaf-coalesce this VDI""" 

        # the space requirements are the same as for inline coalesce 

        return self._calcExtraSpaceForCoalescing() 

 

    def _calcExtraSpaceForSnapshotCoalescing(self): 

        """How much extra space in the SR will be required to 

        snapshot-coalesce this VDI""" 

        return self._calcExtraSpaceForCoalescing() + \ 

                vhdutil.calcOverheadEmpty(self.sizeVirt) # extra snap leaf 

 

    def _getAllSubtree(self): 

        """Get self and all VDIs in the subtree of self as a flat list""" 

        vdiList = [self] 

        for child in self.children: 

            vdiList.extend(child._getAllSubtree()) 

        return vdiList 

 

 

class FileVDI(VDI): 

    """Object representing a VDI in a file-based SR (EXT or NFS)""" 

 

    def extractUuid(path): 

        path = os.path.basename(path.strip()) 

        if not (path.endswith(vhdutil.FILE_EXTN_VHD) or \ 

                path.endswith(vhdutil.FILE_EXTN_RAW)): 

            return None 

        uuid = path.replace(vhdutil.FILE_EXTN_VHD, "").replace( \ 

                vhdutil.FILE_EXTN_RAW, "") 

        # TODO: validate UUID format 

        return uuid 

    extractUuid = staticmethod(extractUuid) 

 

    def __init__(self, sr, uuid, raw): 

        VDI.__init__(self, sr, uuid, raw) 

        if self.raw: 

            self.fileName = "%s%s" % (self.uuid, vhdutil.FILE_EXTN_RAW) 

        else: 

            self.fileName = "%s%s" % (self.uuid, vhdutil.FILE_EXTN_VHD) 

 

    def load(self, info = None): 

        if not info: 

            if not util.pathexists(self.path): 

                raise util.SMException("%s not found" % self.path) 

            try: 

                info = vhdutil.getVHDInfo(self.path, self.extractUuid) 

            except util.SMException: 

                Util.log(" [VDI %s: failed to read VHD metadata]" % self.uuid) 

                return 

        self.parent     = None 

        self.children   = [] 

        self.parentUuid = info.parentUuid 

        self.sizeVirt   = info.sizeVirt 

        self._sizeVHD   = info.sizePhys 

        self.hidden     = info.hidden 

        self.scanError  = False 

        self.path       = os.path.join(self.sr.path, "%s%s" % \ 

                (self.uuid, vhdutil.FILE_EXTN_VHD)) 

 

    def rename(self, uuid): 

        oldPath = self.path 

        VDI.rename(self, uuid) 

        self.fileName = "%s%s" % (self.uuid, vhdutil.FILE_EXTN_VHD) 

        self.path = os.path.join(self.sr.path, self.fileName) 

        assert(not util.pathexists(self.path)) 

        Util.log("Renaming %s -> %s" % (oldPath, self.path)) 

        os.rename(oldPath, self.path) 

 

    def delete(self): 

        if len(self.children) > 0: 

            raise util.SMException("VDI %s has children, can't delete" % \ 

                    self.uuid) 

        try: 

            self.sr.lock() 

            try: 

                os.unlink(self.path) 

                self.sr.forgetVDI(self.uuid) 

            finally: 

                self.sr.unlock() 

        except OSError: 

            raise util.SMException("os.unlink(%s) failed" % self.path) 

        VDI.delete(self) 

 

 

class LVHDVDI(VDI): 

    """Object representing a VDI in an LVHD SR""" 

 

    JRN_ZERO = "zero" # journal entry type for zeroing out end of parent 

    DRIVER_NAME_RAW = "aio" 

 

    def load(self, vdiInfo): 

        self.parent     = None 

        self.children   = [] 

        self._sizeVHD   = -1 

        self.scanError  = vdiInfo.scanError 

        self.sizeLV     = vdiInfo.sizeLV 

        self.sizeVirt   = vdiInfo.sizeVirt 

        self.fileName   = vdiInfo.lvName 

        self.lvActive   = vdiInfo.lvActive 

        self.lvOpen     = vdiInfo.lvOpen 

        self.lvReadonly = vdiInfo.lvReadonly 

        self.hidden     = vdiInfo.hidden 

        self.parentUuid = vdiInfo.parentUuid 

        self.path       = os.path.join(self.sr.path, self.fileName) 

 

    def getDriverName(self): 

        if self.raw: 

            return self.DRIVER_NAME_RAW 

        return self.DRIVER_NAME_VHD 

 

    def inflate(self, size): 

        """inflate the LV containing the VHD to 'size'""" 

        if self.raw: 

            return 

        self._activate() 

        self.sr.lock() 

        try: 

            lvhdutil.inflate(self.sr.journaler, self.sr.uuid, self.uuid, size) 

            util.fistpoint.activate("LVHDRT_inflating_the_parent",self.sr.uuid) 

        finally: 

            self.sr.unlock() 

        self.sizeLV = self.sr.lvmCache.getSize(self.fileName) 

        self._sizeVHD = -1 

 

    def deflate(self): 

        """deflate the LV containing the VHD to minimum""" 

        if self.raw: 

            return 

        self._activate() 

        self.sr.lock() 

        try: 

            lvhdutil.deflate(self.sr.lvmCache, self.fileName, self.getSizeVHD()) 

        finally: 

            self.sr.unlock() 

        self.sizeLV = self.sr.lvmCache.getSize(self.fileName) 

        self._sizeVHD = -1 

 

    def inflateFully(self): 

        self.inflate(lvhdutil.calcSizeVHDLV(self.sizeVirt)) 

 

    def inflateParentForCoalesce(self): 

        """Inflate the parent only as much as needed for the purposes of 

        coalescing""" 

        if self.parent.raw: 

            return 

        inc = self._calcExtraSpaceForCoalescing() 

        if inc > 0: 

            util.fistpoint.activate("LVHDRT_coalescing_before_inflate_grandparent",self.sr.uuid) 

            self.parent.inflate(self.parent.sizeLV + inc) 

 

    def updateBlockInfo(self): 

        if not self.raw: 

            return VDI.updateBlockInfo(self) 

 

    def rename(self, uuid): 

        oldUuid = self.uuid 

        oldLVName = self.fileName 

        VDI.rename(self, uuid) 

        self.fileName = lvhdutil.LV_PREFIX[vhdutil.VDI_TYPE_VHD] + self.uuid 

        if self.raw: 

            self.fileName = lvhdutil.LV_PREFIX[vhdutil.VDI_TYPE_RAW] + self.uuid 

        self.path = os.path.join(self.sr.path, self.fileName) 

        assert(not self.sr.lvmCache.checkLV(self.fileName)) 

 

        self.sr.lvmCache.rename(oldLVName, self.fileName) 

        if self.sr.lvActivator.get(oldUuid, False): 

            self.sr.lvActivator.replace(oldUuid, self.uuid, self.fileName, False) 

 

        ns = lvhdutil.NS_PREFIX_LVM + self.sr.uuid 

        (cnt, bcnt) = RefCounter.check(oldUuid, ns) 

        RefCounter.set(self.uuid, cnt, bcnt, ns) 

        RefCounter.reset(oldUuid, ns) 

 

    def delete(self): 

        if len(self.children) > 0: 

            raise util.SMException("VDI %s has children, can't delete" % \ 

                    self.uuid) 

        self.sr.lock() 

        try: 

            self.sr.lvmCache.remove(self.fileName) 

            self.sr.forgetVDI(self.uuid) 

        finally: 

            self.sr.unlock() 

        RefCounter.reset(self.uuid, lvhdutil.NS_PREFIX_LVM + self.sr.uuid) 

        VDI.delete(self) 

 

    def getSizeVHD(self): 

        if self._sizeVHD == -1: 

            self._loadInfoSizeVHD() 

        return self._sizeVHD 

 

    def _loadInfoSizeVHD(self): 

        """Get the physical utilization of the VHD file. We do it individually 

        (and not using the VHD batch scanner) as an optimization: this info is 

        relatively expensive and we need it only for VDI's involved in 

        coalescing.""" 

        if self.raw: 

            return 

        self._activate() 

        self._sizeVHD = vhdutil.getSizePhys(self.path) 

        if self._sizeVHD <= 0: 

            raise util.SMException("phys size of %s = %d" % \ 

                    (self, self._sizeVHD)) 

 

    def _loadInfoHidden(self): 

        if self.raw: 

            self.hidden = self.sr.lvmCache.getHidden(self.fileName) 

        else: 

            VDI._loadInfoHidden(self) 

 

    def _setHidden(self, hidden = True): 

        if self.raw: 

            self.sr.lvmCache.setHidden(self.fileName, hidden) 

            self.hidden = hidden 

        else: 

            VDI._setHidden(self, hidden) 

 

    def __str__(self): 

        strType = "VHD" 

        if self.raw: 

            strType = "RAW" 

        strHidden = "" 

        if self.hidden: 

            strHidden = "*" 

        strSizeVHD = "" 

        if self._sizeVHD > 0: 

            strSizeVHD = Util.num2str(self._sizeVHD) 

        strActive = "n" 

        if self.lvActive: 

            strActive = "a" 

        if self.lvOpen: 

            strActive += "o" 

        return "%s%s[%s](%s/%s/%s|%s)" % (strHidden, self.uuid[0:8], strType, 

                Util.num2str(self.sizeVirt), strSizeVHD, 

                Util.num2str(self.sizeLV), strActive) 

 

    def validate(self, fast = False): 

        if not self.raw: 

            VDI.validate(self, fast) 

 

    def _doCoalesce(self): 

        """LVHD parents must first be activated, inflated, and made writable""" 

        try: 

            self._activateChain() 

            self.sr.lvmCache.setReadonly(self.parent.fileName, False) 

            self.parent.validate() 

            self.inflateParentForCoalesce() 

            VDI._doCoalesce(self) 

        finally: 

            self.parent._loadInfoSizeVHD() 

            self.parent.deflate() 

            self.sr.lvmCache.setReadonly(self.parent.fileName, True) 

 

    def _setParent(self, parent): 

        self._activate() 

        if self.lvReadonly: 

            self.sr.lvmCache.setReadonly(self.fileName, False) 

 

        try: 

            vhdutil.setParent(self.path, parent.path, parent.raw) 

        finally: 

            if self.lvReadonly: 

                self.sr.lvmCache.setReadonly(self.fileName, True) 

        self._deactivate() 

        self.parent = parent 

        self.parentUuid = parent.uuid 

        parent.children.append(self) 

        try: 

            self.setConfig(self.DB_VHD_PARENT, self.parentUuid) 

            Util.log("Updated the vhd-parent field for child %s with %s" % \ 

                     (self.uuid, self.parentUuid)) 

        except: 

            Util.log("Failed to update the vhd-parent with %s for child %s" % \ 

                     (self.parentUuid, self.uuid)) 

 

    def _activate(self): 

        self.sr.lvActivator.activate(self.uuid, self.fileName, False) 

 

    def _activateChain(self): 

        vdi = self 

        while vdi: 

            vdi._activate() 

            vdi = vdi.parent 

 

    def _deactivate(self): 

        self.sr.lvActivator.deactivate(self.uuid, False) 

 

    def _increaseSizeVirt(self, size, atomic = True): 

        "ensure the virtual size of 'self' is at least 'size'" 

        self._activate() 

        if not self.raw: 

            VDI._increaseSizeVirt(self, size, atomic) 

            return 

 

        # raw VDI case 

        offset = self.sizeLV 

        if self.sizeVirt < size: 

            oldSize = self.sizeLV 

            self.sizeLV = util.roundup(lvutil.LVM_SIZE_INCREMENT, size) 

            Util.log("  Growing %s: %d->%d" % (self.path, oldSize, self.sizeLV)) 

            self.sr.lvmCache.setSize(self.fileName, self.sizeLV) 

            offset = oldSize 

        unfinishedZero = False 

        jval = self.sr.journaler.get(self.JRN_ZERO, self.uuid) 

        if jval: 

            unfinishedZero = True 

            offset = int(jval) 

        length = self.sizeLV - offset 

        if not length: 

            return 

 

        if unfinishedZero: 

            Util.log("  ==> Redoing unfinished zeroing out") 

        else: 

            self.sr.journaler.create(self.JRN_ZERO, self.uuid, \ 

                    str(offset)) 

        Util.log("  Zeroing %s: from %d, %dB" % (self.path, offset, length)) 

        abortTest = lambda:IPCFlag(self.sr.uuid).test(FLAG_TYPE_ABORT) 

        func = lambda: util.zeroOut(self.path, offset, length) 

        Util.runAbortable(func, True, self.sr.uuid, abortTest, 

                VDI.POLL_INTERVAL, 0) 

        self.sr.journaler.remove(self.JRN_ZERO, self.uuid) 

 

    def _setSizeVirt(self, size): 

        """WARNING: do not call this method directly unless all VDIs in the 

        subtree are guaranteed to be unplugged (and remain so for the duration 

        of the operation): this operation is only safe for offline VHDs""" 

        self._activate() 

        jFile = lvhdutil.createVHDJournalLV(self.sr.lvmCache, self.uuid, 

                vhdutil.MAX_VHD_JOURNAL_SIZE) 

        try: 

            lvhdutil.setSizeVirt(self.sr.journaler, self.sr.uuid, self.uuid, 

                    size, jFile) 

        finally: 

            lvhdutil.deleteVHDJournalLV(self.sr.lvmCache, self.uuid) 

 

    def _queryVHDBlocks(self): 

        self._activate() 

        return VDI._queryVHDBlocks(self) 

 

    def _calcExtraSpaceForCoalescing(self): 

        if self.parent.raw: 

            return 0 # raw parents are never deflated in the first place 

        sizeCoalesced = lvhdutil.calcSizeVHDLV(self._getCoalescedSizeData()) 

        Util.log("Coalesced size = %s" % Util.num2str(sizeCoalesced)) 

        return sizeCoalesced - self.parent.sizeLV 

 

    def _calcExtraSpaceForLeafCoalescing(self): 

        """How much extra space in the SR will be required to 

        [live-]leaf-coalesce this VDI""" 

        # we can deflate the leaf to minimize the space requirements 

        deflateDiff = self.sizeLV - lvhdutil.calcSizeLV(self.getSizeVHD()) 

        return self._calcExtraSpaceForCoalescing() - deflateDiff 

 

    def _calcExtraSpaceForSnapshotCoalescing(self): 

        return self._calcExtraSpaceForCoalescing() + \ 

                lvhdutil.calcSizeLV(self.getSizeVHD()) 

 

 

class LinstorVDI(VDI): 

    """Object representing a VDI in a LINSTOR SR""" 

 

    MAX_SIZE = 2 * 1024 * 1024 * 1024 * 1024  # Max VHD size. 

 

    VOLUME_LOCK_TIMEOUT = 30 

 

    def load(self, info=None): 

        self.parentUuid = info.parentUuid 

        self.scanError = True 

        self.parent = None 

        self.children = [] 

 

        self.fileName = self.sr._linstor.get_volume_name(self.uuid) 

        self.path = self.sr._linstor.build_device_path(self.fileName) 

        if not util.pathexists(self.path): 

            raise util.SMException( 

                '{} of {} not found' 

                .format(self.fileName, self.uuid) 

            ) 

 

        if not info: 

            try: 

                info = self.sr._vhdutil.get_vhd_info(self.uuid) 

            except util.SMException: 

                Util.log( 

                    ' [VDI {}: failed to read VHD metadata]'.format(self.uuid) 

                ) 

                return 

 

        self.parentUuid = info.parentUuid 

        self.sizeVirt = info.sizeVirt 

        self._sizeVHD = info.sizePhys 

        self.hidden = info.hidden 

        self.scanError = False 

 

    def rename(self, uuid): 

        Util.log('Renaming {} -> {} (path={})'.format( 

            self.uuid, uuid, self.path 

        )) 

        self.sr._linstor.update_volume_uuid(self.uuid, uuid) 

        VDI.rename(self, uuid) 

 

    def delete(self): 

        if len(self.children) > 0: 

            raise util.SMException( 

                'VDI {} has children, can\'t delete'.format(self.uuid) 

            ) 

        self.sr.lock() 

        try: 

            self.sr._linstor.destroy_volume(self.uuid) 

            self.sr.forgetVDI(self.uuid) 

        finally: 

            self.sr.unlock() 

        VDI.delete(self) 

 

    def pauseVDIs(self, vdiList): 

        self.sr._linstor.ensure_volume_list_is_not_locked( 

            vdiList, timeout=self.VOLUME_LOCK_TIMEOUT 

        ) 

        return super(VDI).pauseVDIs(vdiList) 

 

    def _liveLeafCoalesce(self, vdi): 

        self.sr._linstor.ensure_volume_is_not_locked( 

            vdi.uuid, timeout=self.VOLUME_LOCK_TIMEOUT 

        ) 

        return super(VDI)._liveLeafCoalesce(vdi) 

 

    def _relinkSkip(self): 

        abortFlag = IPCFlag(self.sr.uuid) 

        for child in self.children: 

            if abortFlag.test(FLAG_TYPE_ABORT): 

                raise AbortException('Aborting due to signal') 

            Util.log( 

                '  Relinking {} from {} to {}'.format( 

                    child, self, self.parent 

                ) 

            ) 

 

            session = child.sr.xapi.session 

            sr_uuid = child.sr.uuid 

            vdi_uuid = child.uuid 

            try: 

                self.sr._linstor.ensure_volume_is_not_locked( 

                    vdi_uuid, timeout=self.VOLUME_LOCK_TIMEOUT 

                ) 

                blktap2.VDI.tap_pause(session, sr_uuid, vdi_uuid) 

                child._setParent(self.parent) 

            finally: 

                blktap2.VDI.tap_unpause(session, sr_uuid, vdi_uuid) 

        self.children = [] 

 

    def _setHidden(self, hidden=True): 

        HIDDEN_TAG = 'hidden' 

 

        if self.raw: 

            self.sr._linstor.update_volume_metadata(self.uuid, { 

                HIDDEN_TAG: hidden 

            }) 

            self.hidden = hidden 

        else: 

            VDI._setHidden(self, hidden) 

 

    def _queryVHDBlocks(self): 

        return self.sr._vhdutil.get_block_bitmap(self.uuid) 

 

################################################################################ 

# 

# SR 

# 

class SR: 

    class LogFilter: 

        def __init__(self, sr): 

            self.sr = sr 

            self.stateLogged = False 

            self.prevState = {} 

            self.currState = {} 

 

        def logState(self): 

            changes = "" 

            self.currState.clear() 

            for vdi in self.sr.vdiTrees: 

                self.currState[vdi.uuid] = self._getTreeStr(vdi) 

                if not self.prevState.get(vdi.uuid) or \ 

                        self.prevState[vdi.uuid] != self.currState[vdi.uuid]: 

                    changes += self.currState[vdi.uuid] 

 

            for uuid in self.prevState.iterkeys(): 

                if not self.currState.get(uuid): 

                    changes += "Tree %s gone\n" % uuid 

 

            result = "SR %s (%d VDIs in %d VHD trees): " % \ 

                    (self.sr, len(self.sr.vdis), len(self.sr.vdiTrees)) 

 

            if len(changes) > 0: 

                if self.stateLogged: 

                    result += "showing only VHD trees that changed:" 

                result += "\n%s" % changes 

            else: 

                result += "no changes" 

 

            for line in result.split("\n"): 

                Util.log("%s" % line) 

            self.prevState.clear() 

            for key, val in self.currState.iteritems(): 

                self.prevState[key] = val 

            self.stateLogged = True 

 

        def logNewVDI(self, uuid): 

            if self.stateLogged: 

                Util.log("Found new VDI when scanning: %s" % uuid) 

 

        def _getTreeStr(self, vdi, indent = 8): 

            treeStr = "%s%s\n" % (" " * indent, vdi) 

            for child in vdi.children: 

                treeStr += self._getTreeStr(child, indent + VDI.STR_TREE_INDENT) 

            return treeStr 

 

 

    TYPE_FILE = "file" 

    TYPE_LVHD = "lvhd" 

    TYPE_LINSTOR = "linstor" 

    TYPES = [TYPE_LVHD, TYPE_FILE, TYPE_LINSTOR] 

 

    LOCK_RETRY_INTERVAL = 3 

    LOCK_RETRY_ATTEMPTS = 20 

    LOCK_RETRY_ATTEMPTS_LOCK = 100 

 

    SCAN_RETRY_ATTEMPTS = 3 

 

    JRN_CLONE = "clone" # journal entry type for the clone operation (from SM) 

    TMP_RENAME_PREFIX = "OLD_" 

 

    KEY_OFFLINE_COALESCE_NEEDED = "leaf_coalesce_need_offline" 

    KEY_OFFLINE_COALESCE_OVERRIDE = "leaf_coalesce_offline_override" 

 

    def getInstance(uuid, xapiSession, createLock = True, force = False): 

        xapi = XAPI(xapiSession, uuid) 

        type = normalizeType(xapi.srRecord["type"]) 

        if type == SR.TYPE_FILE: 

            return FileSR(uuid, xapi, createLock, force) 

        elif type == SR.TYPE_LVHD: 

            return LVHDSR(uuid, xapi, createLock, force) 

        elif type == SR.TYPE_LINSTOR: 

            return LinstorSR(uuid, xapi, createLock, force) 

        raise util.SMException("SR type %s not recognized" % type) 

    getInstance = staticmethod(getInstance) 

 

    def __init__(self, uuid, xapi, createLock, force): 

        self.logFilter = self.LogFilter(self) 

        self.uuid = uuid 

        self.path = "" 

        self.name = "" 

        self.vdis = {} 

        self.vdiTrees = [] 

        self.journaler = None 

        self.xapi = xapi 

        self._locked = 0 

        self._srLock = None 

1572        if createLock: 

            self._srLock = lock.Lock(vhdutil.LOCK_TYPE_SR, self.uuid) 

        else: 

            Util.log("Requested no SR locking") 

        self.name = unicode(self.xapi.srRecord["name_label"]).encode("utf-8", "replace") 

        self._failedCoalesceTargets = [] 

 

1579        if not self.xapi.isPluggedHere(): 

            if force: 

                Util.log("SR %s not attached on this host, ignoring" % uuid) 

            else: 

                raise util.SMException("SR %s not attached on this host" % uuid) 

 

1585        if force: 

            Util.log("Not checking if we are Master (SR %s)" % uuid) 

1587        elif not self.xapi.isMaster(): 

            raise util.SMException("This host is NOT master, will not run") 

 

    def gcEnabled(self, refresh = True): 

        if refresh: 

            self.xapi.srRecord = \ 

                    self.xapi.session.xenapi.SR.get_record(self.xapi._srRef) 

        if self.xapi.srRecord["other_config"].get(VDI.DB_GC) == "false": 

            Util.log("GC is disabled for this SR, abort") 

            return False 

        return True 

 

    def scan(self, force = False): 

        """Scan the SR and load VDI info for each VDI. If called repeatedly, 

        update VDI objects if they already exist""" 

        pass # abstract 

 

    def scanLocked(self, force = False): 

        self.lock() 

        try: 

            self.scan(force) 

        finally: 

            self.unlock() 

 

    def getVDI(self, uuid): 

        return self.vdis.get(uuid) 

 

    def hasWork(self): 

        if len(self.findGarbage()) > 0: 

            return True 

        if self.findCoalesceable(): 

            return True 

        if self.findLeafCoalesceable(): 

            return True 

        if self.needUpdateBlockInfo(): 

            return True 

        return False 

 

    def findCoalesceable(self): 

        """Find a coalesceable VDI. Return a vdi that should be coalesced 

        (choosing one among all coalesceable candidates according to some 

        criteria) or None if there is no VDI that could be coalesced""" 

 

        candidates = [] 

 

        srSwitch = self.xapi.srRecord["other_config"].get(VDI.DB_COALESCE) 

        if srSwitch == "false": 

            Util.log("Coalesce disabled for this SR") 

            return candidates 

 

        # finish any VDI for which a relink journal entry exists first 

        journals = self.journaler.getAll(VDI.JRN_RELINK) 

        for uuid in journals.iterkeys(): 

            vdi = self.getVDI(uuid) 

            if vdi and vdi not in self._failedCoalesceTargets: 

                return vdi 

 

        for vdi in self.vdis.values(): 

            if vdi.isCoalesceable() and vdi not in self._failedCoalesceTargets: 

                candidates.append(vdi) 

                Util.log("%s is coalescable" % vdi.uuid) 

 

        # pick one in the tallest tree 

        treeHeight = dict() 

        for c in candidates: 

            height = c.getTreeRoot().getTreeHeight() 

            if treeHeight.get(height): 

                treeHeight[height].append(c) 

            else: 

                treeHeight[height] = [c] 

 

        freeSpace = self.getFreeSpace() 

        heights = treeHeight.keys() 

        heights.sort(reverse=True) 

        for h in heights: 

            for c in treeHeight[h]: 

                spaceNeeded = c._calcExtraSpaceForCoalescing() 

                if spaceNeeded <= freeSpace: 

                    Util.log("Coalesce candidate: %s (tree height %d)" % (c, h)) 

                    return c 

                else: 

                    Util.log("No space to coalesce %s (free space: %d)" % \ 

                            (c, freeSpace)) 

        return None 

 

    def getSwitch(self, key): 

        return self.xapi.srRecord["other_config"].get(key) 

 

    def forbiddenBySwitch(self, switch, condition, fail_msg): 

        srSwitch = self.getSwitch(switch) 

        ret = False 

        if srSwitch: 

            ret = srSwitch == condition 

 

        if ret: 

            Util.log(fail_msg) 

 

        return ret 

 

    def leafCoalesceForbidden(self): 

        return (self.forbiddenBySwitch(VDI.DB_COALESCE, 

                                       "false", 

                                       "Coalesce disabled for this SR") or 

                self.forbiddenBySwitch(VDI.DB_LEAFCLSC, 

                                       VDI.LEAFCLSC_DISABLED, 

                                       "Leaf-coalesce disabled for this SR")) 

 

    def findLeafCoalesceable(self): 

        """Find leaf-coalesceable VDIs in each VHD tree""" 

 

        candidates = [] 

        if self.leafCoalesceForbidden(): 

          return candidates 

 

        self.gatherLeafCoalesceable(candidates) 

 

        freeSpace = self.getFreeSpace() 

        for candidate in candidates: 

            # check the space constraints to see if leaf-coalesce is actually  

            # feasible for this candidate 

            spaceNeeded = candidate._calcExtraSpaceForSnapshotCoalescing() 

            spaceNeededLive = spaceNeeded 

            if spaceNeeded > freeSpace: 

                spaceNeededLive = candidate._calcExtraSpaceForLeafCoalescing() 

                if candidate.canLiveCoalesce(self.getStorageSpeed()): 

                    spaceNeeded = spaceNeededLive 

 

            if spaceNeeded <= freeSpace: 

                Util.log("Leaf-coalesce candidate: %s" % candidate) 

                return candidate 

            else: 

                Util.log("No space to leaf-coalesce %s (free space: %d)" % \ 

                        (candidate, freeSpace)) 

                if spaceNeededLive <= freeSpace: 

                    Util.log("...but enough space if skip snap-coalesce") 

                    candidate.setConfig(VDI.DB_LEAFCLSC, 

                            VDI.LEAFCLSC_OFFLINE) 

 

        return None 

 

    def gatherLeafCoalesceable(self, candidates): 

        for vdi in self.vdis.values(): 

            if not vdi.isLeafCoalesceable(): 

                continue 

            if vdi in self._failedCoalesceTargets: 

                continue 

            if vdi.getConfig(vdi.DB_ONBOOT) == vdi.ONBOOT_RESET: 

                Util.log("Skipping reset-on-boot %s" % vdi) 

                continue 

            if vdi.getConfig(vdi.DB_ALLOW_CACHING): 

                Util.log("Skipping allow_caching=true %s" % vdi) 

                continue 

            if vdi.getConfig(vdi.DB_LEAFCLSC) == vdi.LEAFCLSC_DISABLED: 

                Util.log("Leaf-coalesce disabled for %s" % vdi) 

                continue 

            if not (AUTO_ONLINE_LEAF_COALESCE_ENABLED or 

                    vdi.getConfig(vdi.DB_LEAFCLSC) == vdi.LEAFCLSC_FORCE): 

                continue 

            candidates.append(vdi) 

 

    def coalesce(self, vdi, dryRun): 

        """Coalesce vdi onto parent""" 

        Util.log("Coalescing %s -> %s" % (vdi, vdi.parent)) 

        if dryRun: 

            return 

 

        try: 

            self._coalesce(vdi) 

        except util.SMException, e: 

            if isinstance(e, AbortException): 

                self.cleanup() 

                raise 

            else: 

                self._failedCoalesceTargets.append(vdi) 

                Util.logException("coalesce") 

                Util.log("Coalesce failed, skipping") 

        self.cleanup() 

 

    def coalesceLeaf(self, vdi, dryRun): 

        """Leaf-coalesce vdi onto parent""" 

        Util.log("Leaf-coalescing %s -> %s" % (vdi, vdi.parent)) 

        if dryRun: 

            return 

 

        try: 

            uuid = vdi.uuid 

            try: 

                # "vdi" object will no longer be valid after this call 

                self._coalesceLeaf(vdi) 

            finally: 

                vdi = self.getVDI(uuid) 

                if vdi: 

                    vdi.delConfig(vdi.DB_LEAFCLSC) 

        except AbortException: 

            self.cleanup() 

            raise 

        except (util.SMException, XenAPI.Failure), e: 

            self._failedCoalesceTargets.append(vdi) 

            Util.logException("leaf-coalesce") 

            Util.log("Leaf-coalesce failed on %s, skipping" % vdi) 

        self.cleanup() 

 

    def garbageCollect(self, dryRun = False): 

        vdiList = self.findGarbage() 

        Util.log("Found %d VDIs for deletion:" % len(vdiList)) 

        for vdi in vdiList: 

            Util.log("  %s" % vdi) 

        if not dryRun: 

            self.deleteVDIs(vdiList) 

        self.cleanupJournals(dryRun) 

 

    def findGarbage(self): 

        vdiList = [] 

        for vdi in self.vdiTrees: 

            vdiList.extend(vdi.getAllPrunable()) 

        return vdiList 

 

    def deleteVDIs(self, vdiList): 

        for vdi in vdiList: 

            if IPCFlag(self.uuid).test(FLAG_TYPE_ABORT): 

                raise AbortException("Aborting due to signal") 

            Util.log("Deleting unlinked VDI %s" % vdi) 

            self.deleteVDI(vdi) 

 

    def deleteVDI(self, vdi): 

        assert(len(vdi.children) == 0) 

        del self.vdis[vdi.uuid] 

        if vdi.parent: 

            vdi.parent.children.remove(vdi) 

        if vdi in self.vdiTrees: 

            self.vdiTrees.remove(vdi) 

        vdi.delete() 

 

    def forgetVDI(self, vdiUuid): 

        self.xapi.forgetVDI(self.uuid, vdiUuid) 

 

    def pauseVDIs(self, vdiList): 

        paused = [] 

        failed = False 

        for vdi in vdiList: 

            try: 

                vdi.pause() 

                paused.append(vdi) 

            except: 

                Util.logException("pauseVDIs") 

                failed = True 

                break 

 

        if failed: 

            self.unpauseVDIs(paused) 

            raise util.SMException("Failed to pause VDIs") 

 

    def unpauseVDIs(self, vdiList): 

        failed = False 

        for vdi in vdiList: 

            try: 

                vdi.unpause() 

            except: 

                Util.log("ERROR: Failed to unpause VDI %s" % vdi) 

                failed = True 

        if failed: 

            raise util.SMException("Failed to unpause VDIs") 

 

    def getFreeSpace(self): 

        return 0 

 

    def cleanup(self): 

        Util.log("In cleanup") 

        return 

 

    def __str__(self): 

        if self.name: 

            ret = "%s ('%s')" % (self.uuid[0:4], self.name) 

        else: 

            ret = "%s" % self.uuid 

        return ret 

 

    def lock(self): 

        """Acquire the SR lock. Nested acquire()'s are ok. Check for Abort 

        signal to avoid deadlocking (trying to acquire the SR lock while the 

        lock is held by a process that is trying to abort us)""" 

        if not self._srLock: 

            return 

 

        if self._locked == 0 : 

            abortFlag = IPCFlag(self.uuid) 

            for i in range(SR.LOCK_RETRY_ATTEMPTS_LOCK): 

                if self._srLock.acquireNoblock(): 

                    self._locked += 1 

                    return 

                if abortFlag.test(FLAG_TYPE_ABORT): 

                    raise AbortException("Abort requested") 

                time.sleep(SR.LOCK_RETRY_INTERVAL) 

            raise util.SMException("Unable to acquire the SR lock") 

 

        self._locked += 1 

 

    def unlock(self): 

1886        if not self._srLock: 

            return 

        assert(self._locked > 0) 

        self._locked -= 1 

        if self._locked == 0: 

            self._srLock.release() 

 

    def needUpdateBlockInfo(self): 

        for vdi in self.vdis.values(): 

            if vdi.scanError or len(vdi.children) == 0: 

                continue 

            if not vdi.getConfig(vdi.DB_VHD_BLOCKS): 

                return True 

        return False 

 

    def updateBlockInfo(self): 

        for vdi in self.vdis.values(): 

            if vdi.scanError or len(vdi.children) == 0: 

                continue 

            if not vdi.getConfig(vdi.DB_VHD_BLOCKS): 

                vdi.updateBlockInfo() 

 

    def cleanupCoalesceJournals(self): 

        """Remove stale coalesce VDI indicators""" 

        entries = self.journaler.getAll(VDI.JRN_COALESCE) 

        for uuid, jval in entries.iteritems(): 

            self.journaler.remove(VDI.JRN_COALESCE, uuid) 

 

    def cleanupJournals(self, dryRun): 

        """delete journal entries for non-existing VDIs""" 

        for t in [LVHDVDI.JRN_ZERO, VDI.JRN_RELINK, SR.JRN_CLONE]: 

            entries = self.journaler.getAll(t) 

            for uuid, jval in entries.iteritems(): 

                if self.getVDI(uuid): 

                    continue 

                if t == SR.JRN_CLONE: 

                    baseUuid, clonUuid = jval.split("_") 

                    if self.getVDI(baseUuid): 

                        continue 

                Util.log("  Deleting stale '%s' journal entry for %s " 

                        "(%s)" % (t, uuid, jval)) 

                if not dryRun: 

                    self.journaler.remove(t, uuid) 

 

    def cleanupCache(self, maxAge = -1): 

        return 0 

 

    def _coalesce(self, vdi): 

        if self.journaler.get(vdi.JRN_RELINK, vdi.uuid): 

            # this means we had done the actual coalescing already and just  

            # need to finish relinking and/or refreshing the children 

            Util.log("==> Coalesce apparently already done: skipping") 

        else: 

            # JRN_COALESCE is used to check which VDI is being coalesced in  

            # order to decide whether to abort the coalesce. We remove the  

            # journal as soon as the VHD coalesce step is done, because we  

            # don't expect the rest of the process to take long 

            self.journaler.create(vdi.JRN_COALESCE, vdi.uuid, "1") 

            vdi._doCoalesce() 

            self.journaler.remove(vdi.JRN_COALESCE, vdi.uuid) 

 

            util.fistpoint.activate("LVHDRT_before_create_relink_journal",self.uuid) 

 

            # we now need to relink the children: lock the SR to prevent ops  

            # like SM.clone from manipulating the VDIs we'll be relinking and  

            # rescan the SR first in case the children changed since the last  

            # scan 

            self.journaler.create(vdi.JRN_RELINK, vdi.uuid, "1") 

 

        self.lock() 

        try: 

            self.scan() 

            vdi._relinkSkip() 

        finally: 

            self.unlock() 

 

        vdi.parent._reloadChildren(vdi) 

        self.journaler.remove(vdi.JRN_RELINK, vdi.uuid) 

        self.deleteVDI(vdi) 

 

    class CoalesceTracker: 

        MAX_ITERATIONS_NO_PROGRESS = 3 

        MAX_ITERATIONS = 10 

        MAX_INCREASE_FROM_MINIMUM = 1.2 

        HISTORY_STRING = "Iteration: {its} -- Initial size {initSize}" \ 

                         " --> Final size {finSize}" 

 

        def __init__(self): 

            self.itsNoProgress = 0 

            self.its = 0 

            self.minSize = float("inf") 

            self.history = [] 

            self.reason = "" 

            self.startSize = None 

            self.finishSize = None 

 

        def abortCoalesce(self, prevSize, curSize): 

            res = False 

 

            self.its += 1 

            self.history.append(self.HISTORY_STRING.format(its=self.its, 

                                                           initSize=prevSize, 

                                                           finSize=curSize)) 

 

            self.finishSize = curSize 

 

            if self.startSize is None: 

                self.startSize = prevSize 

 

            if curSize < self.minSize: 

                self.minSize = curSize 

 

            if prevSize < self.minSize: 

                self.minSize = prevSize 

 

            if prevSize < curSize: 

                self.itsNoProgress += 1 

                Util.log("No progress, attempt:" 

                         " {attempt}".format(attempt=self.itsNoProgress)) 

 

            if (not res) and (self.its > self.MAX_ITERATIONS): 

                max = self.MAX_ITERATIONS 

                self.reason =\ 

                    "Max iterations ({max}) exceeded".format(max=max) 

                res = True 

 

            if (not res) and (self.itsNoProgress > 

                              self.MAX_ITERATIONS_NO_PROGRESS): 

                max = self.MAX_ITERATIONS_NO_PROGRESS 

                self.reason =\ 

                    "No progress made for {max} iterations".format(max=max) 

                res = True 

 

            maxSizeFromMin = self.MAX_INCREASE_FROM_MINIMUM * self.minSize 

            if (not res) and (curSize > maxSizeFromMin): 

                self.reason = "Unexpected bump in size," \ 

                              " compared to minimum acheived" 

                res = True 

 

            return res 

 

        def printReasoning(self): 

            Util.log("Aborted coalesce") 

            for hist in self.history: 

                Util.log(hist) 

            Util.log(self.reason) 

            Util.log("Starting size was         {size}" 

                     .format(size=self.startSize)) 

            Util.log("Final size was            {size}" 

                     .format(size=self.finishSize)) 

            Util.log("Minimum size acheived was {size}" 

                     .format(size=self.minSize)) 

 

    def _coalesceLeaf(self, vdi): 

        """Leaf-coalesce VDI vdi. Return true if we succeed, false if we cannot 

        complete due to external changes, namely vdi_delete and vdi_snapshot  

        that alter leaf-coalescibility of vdi""" 

        tracker = self.CoalesceTracker() 

        while not vdi.canLiveCoalesce(self.getStorageSpeed()): 

            prevSizeVHD = vdi.getSizeVHD() 

2045            if not self._snapshotCoalesce(vdi): 

                return False 

            if tracker.abortCoalesce(prevSizeVHD, vdi.getSizeVHD()): 

                tracker.printReasoning() 

                raise util.SMException("VDI {uuid} could not be coalesced" 

                                       .format(uuid=vdi.uuid)) 

        return self._liveLeafCoalesce(vdi) 

 

    def calcStorageSpeed(self, startTime, endTime, vhdSize): 

        speed = None 

        total_time = endTime - startTime 

        if total_time > 0: 

            speed = float(vhdSize) / float(total_time) 

        return speed 

 

    def writeSpeedToFile(self, speed): 

        content = [] 

        speedFile = None 

        path = SPEED_LOG_ROOT.format(uuid=self.uuid) 

        self.lock() 

        try: 

            Util.log("Writing to file: {myfile}".format(myfile=path)) 

            lines = "" 

            if not os.path.isfile(path): 

                lines = str(speed)+"\n" 

            else: 

                speedFile = open(path, "r+") 

                content = speedFile.readlines() 

                content.append(str(speed) + "\n") 

                if len(content) > N_RUNNING_AVERAGE: 

                    del content[0] 

                lines = "".join(content) 

 

            util.atomicFileWrite(path, VAR_RUN, lines) 

        finally: 

            if speedFile is not None: 

                speedFile.close() 

            Util.log("Closing file: {myfile}".format(myfile=path)) 

            self.unlock() 

 

    def recordStorageSpeed(self, startTime, endTime, vhdSize): 

        speed = self.calcStorageSpeed(startTime, endTime, vhdSize) 

        if speed is None: 

            return 

 

        self.writeSpeedToFile(speed) 

 

    def getStorageSpeed(self): 

        speedFile = None 

        path = SPEED_LOG_ROOT.format(uuid=self.uuid) 

        self.lock() 

        try: 

            speed = None 

            if os.path.isfile(path): 

                speedFile = open(path) 

                content = speedFile.readlines() 

                try: 

                    content = [float(i) for i in content] 

                except exceptions.ValueError: 

                    Util.log("Something bad in the speed log:{log}". 

                             format(log=speedFile.readlines())) 

                    return speed 

 

                if len(content): 

                    speed = sum(content)/float(len(content)) 

2111                    if speed <= 0: 

                        # Defensive, should be impossible. 

                        Util.log("Bad speed: {speed} calculated for SR: {uuid}". 

                             format(speed=speed, uuid=self.uuid)) 

                        speed = None 

                else: 

                    Util.log("Speed file empty for SR: {uuid}". 

                             format(uuid=self.uuid)) 

            else: 

                Util.log("Speed log missing for SR: {uuid}". 

                         format(uuid=self.uuid)) 

            return speed 

        finally: 

            if not (speedFile is None): 

                speedFile.close() 

            self.unlock() 

 

    def _snapshotCoalesce(self, vdi): 

        # Note that because we are not holding any locks here, concurrent SM  

        # operations may change this tree under our feet. In particular, vdi  

        # can be deleted, or it can be snapshotted. 

        assert(AUTO_ONLINE_LEAF_COALESCE_ENABLED) 

        Util.log("Single-snapshotting %s" % vdi) 

        util.fistpoint.activate("LVHDRT_coaleaf_delay_1", self.uuid) 

        try: 

            ret = self.xapi.singleSnapshotVDI(vdi) 

            Util.log("Single-snapshot returned: %s" % ret) 

        except XenAPI.Failure, e: 

            if util.isInvalidVDI(e): 

                Util.log("The VDI appears to have been concurrently deleted") 

                return False 

            raise 

        self.scanLocked() 

        tempSnap = vdi.parent 

        if not tempSnap.isCoalesceable(): 

            Util.log("The VDI appears to have been concurrently snapshotted") 

            return False 

        Util.log("Coalescing parent %s" % tempSnap) 

        util.fistpoint.activate("LVHDRT_coaleaf_delay_2", self.uuid) 

        vhdSize = vdi.getSizeVHD() 

        self._coalesce(tempSnap) 

        if not vdi.isLeafCoalesceable(): 

            Util.log("The VDI tree appears to have been altered since") 

            return False 

        return True 

 

    def _liveLeafCoalesce(self, vdi): 

        util.fistpoint.activate("LVHDRT_coaleaf_delay_3", self.uuid) 

        self.lock() 

        try: 

            self.scan() 

            if not self.getVDI(vdi.uuid): 

                Util.log("The VDI appears to have been deleted meanwhile") 

                return False 

            if not vdi.isLeafCoalesceable(): 

                Util.log("The VDI is no longer leaf-coalesceable") 

                return False 

 

            uuid = vdi.uuid 

            vdi.pause(failfast=True) 

            try: 

                try: 

                    # "vdi" object will no longer be valid after this call 

                    self._doCoalesceLeaf(vdi) 

                except: 

                    Util.logException("_doCoalesceLeaf") 

                    self._handleInterruptedCoalesceLeaf() 

                    raise 

            finally: 

                vdi = self.getVDI(uuid) 

                if vdi: 

                    vdi.ensureUnpaused() 

                vdiOld = self.getVDI(self.TMP_RENAME_PREFIX + uuid) 

                if vdiOld: 

                    util.fistpoint.activate("LVHDRT_coaleaf_before_delete", self.uuid) 

                    self.deleteVDI(vdiOld) 

                    util.fistpoint.activate("LVHDRT_coaleaf_after_delete", self.uuid) 

        finally: 

            self.cleanup() 

            self.unlock() 

            self.logFilter.logState() 

        return True 

 

    def _doCoalesceLeaf(self, vdi): 

        """Actual coalescing of a leaf VDI onto parent. Must be called in an 

        offline/atomic context""" 

        self.journaler.create(VDI.JRN_LEAF, vdi.uuid, vdi.parent.uuid) 

        self._prepareCoalesceLeaf(vdi) 

        vdi.parent._setHidden(False) 

        vdi.parent._increaseSizeVirt(vdi.sizeVirt, False) 

        vdi.validate(True) 

        vdi.parent.validate(True) 

        util.fistpoint.activate("LVHDRT_coaleaf_before_coalesce", self.uuid) 

        timeout = vdi.LIVE_LEAF_COALESCE_TIMEOUT 

        if vdi.getConfig(vdi.DB_LEAFCLSC) == vdi.LEAFCLSC_FORCE: 

            Util.log("Leaf-coalesce forced, will not use timeout") 

            timeout = 0 

        vdi._coalesceVHD(timeout) 

        util.fistpoint.activate("LVHDRT_coaleaf_after_coalesce", self.uuid) 

        vdi.parent.validate(True) 

        #vdi._verifyContents(timeout / 2) 

 

        # rename 

        vdiUuid = vdi.uuid 

        oldName = vdi.fileName 

        origParentUuid = vdi.parent.uuid 

        vdi.rename(self.TMP_RENAME_PREFIX + vdiUuid) 

        util.fistpoint.activate("LVHDRT_coaleaf_one_renamed", self.uuid) 

        vdi.parent.rename(vdiUuid) 

        util.fistpoint.activate("LVHDRT_coaleaf_both_renamed", self.uuid) 

        self._updateSlavesOnRename(vdi.parent, oldName, origParentUuid) 

 

        # Note that "vdi.parent" is now the single remaining leaf and "vdi" is  

        # garbage 

 

        # update the VDI record 

        vdi.parent.delConfig(VDI.DB_VHD_PARENT) 

        if vdi.parent.raw: 

            vdi.parent.setConfig(VDI.DB_VDI_TYPE, vhdutil.VDI_TYPE_RAW) 

        vdi.parent.delConfig(VDI.DB_VHD_BLOCKS) 

        util.fistpoint.activate("LVHDRT_coaleaf_after_vdirec", self.uuid) 

 

        self._updateNode(vdi) 

 

        # delete the obsolete leaf & inflate the parent (in that order, to  

        # minimize free space requirements) 

        parent = vdi.parent 

        vdi._setHidden(True) 

        vdi.parent.children = [] 

        vdi.parent = None 

 

        extraSpace = self._calcExtraSpaceNeeded(vdi, parent) 

        freeSpace = self.getFreeSpace() 

        if freeSpace < extraSpace: 

            # don't delete unless we need the space: deletion is time-consuming  

            # because it requires contacting the slaves, and we're paused here 

            util.fistpoint.activate("LVHDRT_coaleaf_before_delete", self.uuid) 

            self.deleteVDI(vdi) 

            util.fistpoint.activate("LVHDRT_coaleaf_after_delete", self.uuid) 

 

        util.fistpoint.activate("LVHDRT_coaleaf_before_remove_j", self.uuid) 

        self.journaler.remove(VDI.JRN_LEAF, vdiUuid) 

 

        self.forgetVDI(origParentUuid) 

        self._finishCoalesceLeaf(parent) 

        self._updateSlavesOnResize(parent) 

 

 

    def _calcExtraSpaceNeeded(self, child, parent): 

        assert(not parent.raw) # raw parents not supported 

        extra = child.getSizeVHD() - parent.getSizeVHD() 

        if extra < 0: 

            extra = 0 

        return extra 

 

    def _prepareCoalesceLeaf(self, vdi): 

        pass 

 

    def _updateNode(self, vdi): 

        pass 

 

    def _finishCoalesceLeaf(self, parent): 

        pass 

 

    def _updateSlavesOnUndoLeafCoalesce(self, parent, child): 

        pass 

 

    def _updateSlavesOnRename(self, vdi, oldName, origParentUuid): 

        pass 

 

    def _updateSlavesOnResize(self, vdi): 

        pass 

 

    def _removeStaleVDIs(self, uuidsPresent): 

        for uuid in self.vdis.keys(): 

            if not uuid in uuidsPresent: 

                Util.log("VDI %s disappeared since last scan" % \ 

                        self.vdis[uuid]) 

                del self.vdis[uuid] 

 

    def _handleInterruptedCoalesceLeaf(self): 

        """An interrupted leaf-coalesce operation may leave the VHD tree in an  

        inconsistent state. If the old-leaf VDI is still present, we revert the  

        operation (in case the original error is persistent); otherwise we must  

        finish the operation""" 

        # abstract 

        pass 

 

    def _buildTree(self, force): 

        self.vdiTrees = [] 

        for vdi in self.vdis.values(): 

            if vdi.parentUuid: 

                parent = self.getVDI(vdi.parentUuid) 

                if not parent: 

                    if vdi.uuid.startswith(self.TMP_RENAME_PREFIX): 

                        self.vdiTrees.append(vdi) 

                        continue 

                    if force: 

                        Util.log("ERROR: Parent VDI %s not found! (for %s)" % \ 

                                (vdi.parentUuid, vdi.uuid)) 

                        self.vdiTrees.append(vdi) 

                        continue 

                    else: 

                        raise util.SMException("Parent VDI %s of %s not " \ 

                                "found" % (vdi.parentUuid, vdi.uuid)) 

                vdi.parent = parent 

                parent.children.append(vdi) 

            else: 

                self.vdiTrees.append(vdi) 

 

 

class FileSR(SR): 

    TYPE = SR.TYPE_FILE 

    CACHE_FILE_EXT = ".vhdcache" 

    # cache cleanup actions 

    CACHE_ACTION_KEEP = 0 

    CACHE_ACTION_REMOVE = 1 

    CACHE_ACTION_REMOVE_IF_INACTIVE = 2 

 

 

    def __init__(self, uuid, xapi, createLock, force): 

        SR.__init__(self, uuid, xapi, createLock, force) 

        self.path = "/var/run/sr-mount/%s" % self.uuid 

        self.journaler = fjournaler.Journaler(self.path) 

 

    def scan(self, force = False): 

        if not util.pathexists(self.path): 

            raise util.SMException("directory %s not found!" % self.uuid) 

        vhds = self._scan(force) 

        for uuid, vhdInfo in vhds.iteritems(): 

            vdi = self.getVDI(uuid) 

            if not vdi: 

                self.logFilter.logNewVDI(uuid) 

                vdi = FileVDI(self, uuid, False) 

                self.vdis[uuid] = vdi 

            vdi.load(vhdInfo) 

        uuidsPresent = vhds.keys() 

        rawList = filter(lambda x: x.endswith(vhdutil.FILE_EXTN_RAW), 

                os.listdir(self.path)) 

        for rawName in rawList: 

            uuid = FileVDI.extractUuid(rawName) 

            uuidsPresent.append(uuid) 

            vdi = self.getVDI(uuid) 

            if not vdi: 

                self.logFilter.logNewVDI(uuid) 

                vdi = FileVDI(self, uuid, True) 

                self.vdis[uuid] = vdi 

        self._removeStaleVDIs(uuidsPresent) 

        self._buildTree(force) 

        self.logFilter.logState() 

        self._handleInterruptedCoalesceLeaf() 

 

    def getFreeSpace(self): 

        return util.get_fs_size(self.path) - util.get_fs_utilisation(self.path) 

 

    def deleteVDIs(self, vdiList): 

        rootDeleted = False 

        for vdi in vdiList: 

            if not vdi.parent: 

                rootDeleted = True 

                break 

        SR.deleteVDIs(self, vdiList) 

        if self.xapi.srRecord["type"] == "nfs" and rootDeleted: 

            self.xapi.markCacheSRsDirty() 

 

 

    def cleanupCache(self, maxAge = -1): 

        """Clean up IntelliCache cache files. Caches for leaf nodes are  

        removed when the leaf node no longer exists or its allow-caching  

        attribute is not set. Caches for parent nodes are removed when the  

        parent node no longer exists or it hasn't been used in more than  

        <maxAge> hours. 

        Return number of caches removed. 

        """ 

        numRemoved = 0 

        cacheFiles = filter(self._isCacheFileName, os.listdir(self.path)) 

        Util.log("Found %d cache files" % len(cacheFiles)) 

        cutoff = datetime.datetime.now() - datetime.timedelta(hours = maxAge) 

        for cacheFile in cacheFiles: 

            uuid = cacheFile[:-len(self.CACHE_FILE_EXT)] 

            action = self.CACHE_ACTION_KEEP 

            rec = self.xapi.getRecordVDI(uuid) 

            if not rec: 

                Util.log("Cache %s: VDI doesn't exist" % uuid) 

                action = self.CACHE_ACTION_REMOVE 

            elif rec["managed"] and not rec["allow_caching"]: 

                Util.log("Cache %s: caching disabled" % uuid) 

                action = self.CACHE_ACTION_REMOVE 

            elif not rec["managed"] and maxAge >= 0: 

                lastAccess = datetime.datetime.fromtimestamp( \ 

                        os.path.getatime(os.path.join(self.path, cacheFile))) 

                if lastAccess < cutoff: 

                    Util.log("Cache %s: older than %d hrs" % (uuid, maxAge)) 

                    action = self.CACHE_ACTION_REMOVE_IF_INACTIVE 

 

            if action == self.CACHE_ACTION_KEEP: 

                Util.log("Keeping cache %s" % uuid) 

                continue 

 

            lockId = uuid 

            parentUuid = None 

            if rec and rec["managed"]: 

                parentUuid = rec["sm_config"].get("vhd-parent") 

            if parentUuid: 

                lockId = parentUuid 

 

            cacheLock = lock.Lock(blktap2.VDI.LOCK_CACHE_SETUP, lockId) 

            cacheLock.acquire() 

            try: 

                if self._cleanupCache(uuid, action): 

                    numRemoved += 1 

            finally: 

                cacheLock.release() 

        return numRemoved 

 

    def _cleanupCache(self, uuid, action): 

        assert(action != self.CACHE_ACTION_KEEP) 

        rec = self.xapi.getRecordVDI(uuid) 

        if rec and rec["allow_caching"]: 

            Util.log("Cache %s appears to have become valid" % uuid) 

            return False 

 

        fullPath = os.path.join(self.path, uuid + self.CACHE_FILE_EXT) 

        tapdisk = blktap2.Tapdisk.find_by_path(fullPath) 

        if tapdisk: 

            if action == self.CACHE_ACTION_REMOVE_IF_INACTIVE: 

                Util.log("Cache %s still in use" % uuid) 

                return False 

            Util.log("Shutting down tapdisk for %s" % fullPath) 

            tapdisk.shutdown() 

 

        Util.log("Deleting file %s" % fullPath) 

        os.unlink(fullPath) 

        return True 

 

    def _isCacheFileName(self, name): 

        return (len(name) == Util.UUID_LEN + len(self.CACHE_FILE_EXT)) and \ 

                name.endswith(self.CACHE_FILE_EXT) 

 

    def _scan(self, force): 

        for i in range(SR.SCAN_RETRY_ATTEMPTS): 

            error = False 

            pattern = os.path.join(self.path, "*%s" % vhdutil.FILE_EXTN_VHD) 

            vhds = vhdutil.getAllVHDs(pattern, FileVDI.extractUuid) 

            for uuid, vhdInfo in vhds.iteritems(): 

                if vhdInfo.error: 

                    error = True 

                    break 

            if not error: 

                return vhds 

            Util.log("Scan error on attempt %d" % i) 

        if force: 

            return vhds 

        raise util.SMException("Scan error") 

 

    def deleteVDI(self, vdi): 

        self._checkSlaves(vdi) 

        SR.deleteVDI(self, vdi) 

 

    def _checkSlaves(self, vdi): 

        onlineHosts = self.xapi.getOnlineHosts() 

        abortFlag = IPCFlag(self.uuid) 

        for pbdRecord in self.xapi.getAttachedPBDs(): 

            hostRef = pbdRecord["host"] 

            if hostRef == self.xapi._hostRef: 

                continue 

            if abortFlag.test(FLAG_TYPE_ABORT): 

                raise AbortException("Aborting due to signal") 

            try: 

                self._checkSlave(hostRef, vdi) 

            except util.CommandException: 

                if hostRef in onlineHosts: 

                    raise 

 

    def _checkSlave(self, hostRef, vdi): 

        call  = (hostRef, "nfs-on-slave", "check", { 'path': vdi.path }) 

        Util.log("Checking with slave: %s" % repr(call)) 

        _host = self.xapi.session.xenapi.host 

        text  = _host.call_plugin(*call) 

 

    def _handleInterruptedCoalesceLeaf(self): 

        entries = self.journaler.getAll(VDI.JRN_LEAF) 

        for uuid, parentUuid in entries.iteritems(): 

            fileList = os.listdir(self.path) 

            childName = uuid + vhdutil.FILE_EXTN_VHD 

            tmpChildName = self.TMP_RENAME_PREFIX + uuid + vhdutil.FILE_EXTN_VHD 

            parentName1 = parentUuid + vhdutil.FILE_EXTN_VHD 

            parentName2 = parentUuid + vhdutil.FILE_EXTN_RAW 

            parentPresent = (parentName1 in fileList or parentName2 in fileList) 

            if parentPresent or tmpChildName in fileList: 

                self._undoInterruptedCoalesceLeaf(uuid, parentUuid) 

            else: 

                self._finishInterruptedCoalesceLeaf(uuid, parentUuid) 

            self.journaler.remove(VDI.JRN_LEAF, uuid) 

            vdi = self.getVDI(uuid) 

            if vdi: 

                vdi.ensureUnpaused() 

 

    def _undoInterruptedCoalesceLeaf(self, childUuid, parentUuid): 

        Util.log("*** UNDO LEAF-COALESCE") 

        parent = self.getVDI(parentUuid) 

        if not parent: 

            parent = self.getVDI(childUuid) 

            if not parent: 

                raise util.SMException("Neither %s nor %s found" % \ 

                        (parentUuid, childUuid)) 

            Util.log("Renaming parent back: %s -> %s" % (childUuid, parentUuid)) 

            parent.rename(parentUuid) 

        util.fistpoint.activate("LVHDRT_coaleaf_undo_after_rename", self.uuid) 

 

        child = self.getVDI(childUuid) 

        if not child: 

            child = self.getVDI(self.TMP_RENAME_PREFIX + childUuid) 

            if not child: 

                raise util.SMException("Neither %s nor %s found" % \ 

                        (childUuid, self.TMP_RENAME_PREFIX + childUuid)) 

            Util.log("Renaming child back to %s" % childUuid) 

            child.rename(childUuid) 

            Util.log("Updating the VDI record") 

            child.setConfig(VDI.DB_VHD_PARENT, parentUuid) 

            child.setConfig(VDI.DB_VDI_TYPE, vhdutil.VDI_TYPE_VHD) 

            util.fistpoint.activate("LVHDRT_coaleaf_undo_after_rename2", self.uuid) 

 

        if child.hidden: 

            child._setHidden(False) 

        if not parent.hidden: 

            parent._setHidden(True) 

        self._updateSlavesOnUndoLeafCoalesce(parent, child) 

        util.fistpoint.activate("LVHDRT_coaleaf_undo_end", self.uuid) 

        Util.log("*** leaf-coalesce undo successful") 

        if util.fistpoint.is_active("LVHDRT_coaleaf_stop_after_recovery"): 

            child.setConfig(VDI.DB_LEAFCLSC, VDI.LEAFCLSC_DISABLED) 

 

    def _finishInterruptedCoalesceLeaf(self, childUuid, parentUuid): 

        Util.log("*** FINISH LEAF-COALESCE") 

        vdi = self.getVDI(childUuid) 

        if not vdi: 

            raise util.SMException("VDI %s not found" % childUuid) 

        try: 

            self.forgetVDI(parentUuid) 

        except XenAPI.Failure: 

            pass 

        self._updateSlavesOnResize(vdi) 

        util.fistpoint.activate("LVHDRT_coaleaf_finish_end", self.uuid) 

        Util.log("*** finished leaf-coalesce successfully") 

 

 

class LVHDSR(SR): 

    TYPE = SR.TYPE_LVHD 

    SUBTYPES = ["lvhdoiscsi", "lvhdohba"] 

 

    def __init__(self, uuid, xapi, createLock, force): 

        SR.__init__(self, uuid, xapi, createLock, force) 

        self.vgName = "%s%s" % (lvhdutil.VG_PREFIX, self.uuid) 

        self.path = os.path.join(lvhdutil.VG_LOCATION, self.vgName) 

        self.lvmCache = lvmcache.LVMCache(self.vgName) 

        self.lvActivator = LVActivator(self.uuid, self.lvmCache) 

        self.journaler = journaler.Journaler(self.lvmCache) 

 

    def deleteVDI(self, vdi): 

        if self.lvActivator.get(vdi.uuid, False): 

            self.lvActivator.deactivate(vdi.uuid, False) 

        self._checkSlaves(vdi) 

        SR.deleteVDI(self, vdi) 

 

    def forgetVDI(self, vdiUuid): 

        SR.forgetVDI(self, vdiUuid) 

        mdpath = os.path.join(self.path, lvutil.MDVOLUME_NAME) 

        LVMMetadataHandler(mdpath).deleteVdiFromMetadata(vdiUuid) 

 

    def getFreeSpace(self): 

        stats = lvutil._getVGstats(self.vgName) 

        return stats['physical_size'] - stats['physical_utilisation'] 

 

    def cleanup(self): 

        if not self.lvActivator.deactivateAll(): 

            Util.log("ERROR deactivating LVs while cleaning up") 

 

    def needUpdateBlockInfo(self): 

        for vdi in self.vdis.values(): 

            if vdi.scanError or vdi.raw or len(vdi.children) == 0: 

                continue 

            if not vdi.getConfig(vdi.DB_VHD_BLOCKS): 

                return True 

        return False 

 

    def updateBlockInfo(self): 

        numUpdated = 0 

        for vdi in self.vdis.values(): 

            if vdi.scanError or vdi.raw or len(vdi.children) == 0: 

                continue 

            if not vdi.getConfig(vdi.DB_VHD_BLOCKS): 

                vdi.updateBlockInfo() 

                numUpdated += 1 

        if numUpdated: 

            # deactivate the LVs back sooner rather than later. If we don't  

            # now, by the time this thread gets to deactivations, another one  

            # might have leaf-coalesced a node and deleted it, making the child  

            # inherit the refcount value and preventing the correct decrement 

            self.cleanup() 

 

    def scan(self, force = False): 

        vdis = self._scan(force) 

        for uuid, vdiInfo in vdis.iteritems(): 

            vdi = self.getVDI(uuid) 

            if not vdi: 

                self.logFilter.logNewVDI(uuid) 

                vdi = LVHDVDI(self, uuid, 

                        vdiInfo.vdiType == vhdutil.VDI_TYPE_RAW) 

                self.vdis[uuid] = vdi 

            vdi.load(vdiInfo) 

        self._removeStaleVDIs(vdis.keys()) 

        self._buildTree(force) 

        self.logFilter.logState() 

        self._handleInterruptedCoalesceLeaf() 

 

    def _scan(self, force): 

        for i in range(SR.SCAN_RETRY_ATTEMPTS): 

            error = False 

            self.lvmCache.refresh() 

            vdis = lvhdutil.getVDIInfo(self.lvmCache) 

            for uuid, vdiInfo in vdis.iteritems(): 

                if vdiInfo.scanError: 

                    error = True 

                    break 

            if not error: 

                return vdis 

            Util.log("Scan error, retrying (%d)" % i) 

        if force: 

            return vdis 

        raise util.SMException("Scan error") 

 

    def _removeStaleVDIs(self, uuidsPresent): 

        for uuid in self.vdis.keys(): 

            if not uuid in uuidsPresent: 

                Util.log("VDI %s disappeared since last scan" % \ 

                        self.vdis[uuid]) 

                del self.vdis[uuid] 

                if self.lvActivator.get(uuid, False): 

                    self.lvActivator.remove(uuid, False) 

 

    def _liveLeafCoalesce(self, vdi): 

        """If the parent is raw and the child was resized (virt. size), then 

        we'll need to resize the parent, which can take a while due to zeroing 

        out of the extended portion of the LV. Do it before pausing the child 

        to avoid a protracted downtime""" 

        if vdi.parent.raw and vdi.sizeVirt > vdi.parent.sizeVirt: 

            self.lvmCache.setReadonly(vdi.parent.fileName, False) 

            vdi.parent._increaseSizeVirt(vdi.sizeVirt) 

 

        return SR._liveLeafCoalesce(self, vdi) 

 

    def _prepareCoalesceLeaf(self, vdi): 

        vdi._activateChain() 

        self.lvmCache.setReadonly(vdi.parent.fileName, False) 

        vdi.deflate() 

        vdi.inflateParentForCoalesce() 

 

    def _updateNode(self, vdi): 

        # fix the refcounts: the remaining node should inherit the binary  

        # refcount from the leaf (because if it was online, it should remain  

        # refcounted as such), but the normal refcount from the parent (because  

        # this node is really the parent node) - minus 1 if it is online (since  

        # non-leaf nodes increment their normal counts when they are online and  

        # we are now a leaf, storing that 1 in the binary refcount). 

        ns = lvhdutil.NS_PREFIX_LVM + self.uuid 

        cCnt, cBcnt = RefCounter.check(vdi.uuid, ns) 

        pCnt, pBcnt = RefCounter.check(vdi.parent.uuid, ns) 

        pCnt = pCnt - cBcnt 

        assert(pCnt >= 0) 

        RefCounter.set(vdi.parent.uuid, pCnt, cBcnt, ns) 

 

    def _finishCoalesceLeaf(self, parent): 

        if not parent.isSnapshot() or parent.isAttachedRW(): 

            parent.inflateFully() 

        else: 

            parent.deflate() 

 

    def _calcExtraSpaceNeeded(self, child, parent): 

        return lvhdutil.calcSizeVHDLV(parent.sizeVirt) - parent.sizeLV 

 

    def _handleInterruptedCoalesceLeaf(self): 

        entries = self.journaler.getAll(VDI.JRN_LEAF) 

        for uuid, parentUuid in entries.iteritems(): 

            childLV = lvhdutil.LV_PREFIX[vhdutil.VDI_TYPE_VHD] + uuid 

            tmpChildLV = lvhdutil.LV_PREFIX[vhdutil.VDI_TYPE_VHD] + \ 

                    self.TMP_RENAME_PREFIX + uuid 

            parentLV1 = lvhdutil.LV_PREFIX[vhdutil.VDI_TYPE_VHD] + parentUuid 

            parentLV2 = lvhdutil.LV_PREFIX[vhdutil.VDI_TYPE_RAW] + parentUuid 

            parentPresent = (self.lvmCache.checkLV(parentLV1) or \ 

                    self.lvmCache.checkLV(parentLV2)) 

            if parentPresent or self.lvmCache.checkLV(tmpChildLV): 

                self._undoInterruptedCoalesceLeaf(uuid, parentUuid) 

            else: 

                self._finishInterruptedCoalesceLeaf(uuid, parentUuid) 

            self.journaler.remove(VDI.JRN_LEAF, uuid) 

            vdi = self.getVDI(uuid) 

            if vdi: 

                vdi.ensureUnpaused() 

 

    def _undoInterruptedCoalesceLeaf(self, childUuid, parentUuid): 

        Util.log("*** UNDO LEAF-COALESCE") 

        parent = self.getVDI(parentUuid) 

        if not parent: 

            parent = self.getVDI(childUuid) 

            if not parent: 

                raise util.SMException("Neither %s nor %s found" % \ 

                        (parentUuid, childUuid)) 

            Util.log("Renaming parent back: %s -> %s" % (childUuid, parentUuid)) 

            parent.rename(parentUuid) 

        util.fistpoint.activate("LVHDRT_coaleaf_undo_after_rename", self.uuid) 

 

        child = self.getVDI(childUuid) 

        if not child: 

            child = self.getVDI(self.TMP_RENAME_PREFIX + childUuid) 

            if not child: 

                raise util.SMException("Neither %s nor %s found" % \ 

                        (childUuid, self.TMP_RENAME_PREFIX + childUuid)) 

            Util.log("Renaming child back to %s" % childUuid) 

            child.rename(childUuid) 

            Util.log("Updating the VDI record") 

            child.setConfig(VDI.DB_VHD_PARENT, parentUuid) 

            child.setConfig(VDI.DB_VDI_TYPE, vhdutil.VDI_TYPE_VHD) 

            util.fistpoint.activate("LVHDRT_coaleaf_undo_after_rename2", self.uuid) 

 

            # refcount (best effort - assume that it had succeeded if the  

            # second rename succeeded; if not, this adjustment will be wrong,  

            # leading to a non-deactivation of the LV) 

            ns = lvhdutil.NS_PREFIX_LVM + self.uuid 

            cCnt, cBcnt = RefCounter.check(child.uuid, ns) 

            pCnt, pBcnt = RefCounter.check(parent.uuid, ns) 

            pCnt = pCnt + cBcnt 

            RefCounter.set(parent.uuid, pCnt, 0, ns) 

            util.fistpoint.activate("LVHDRT_coaleaf_undo_after_refcount", self.uuid) 

 

        parent.deflate() 

        child.inflateFully() 

        util.fistpoint.activate("LVHDRT_coaleaf_undo_after_deflate", self.uuid) 

        if child.hidden: 

            child._setHidden(False) 

        if not parent.hidden: 

            parent._setHidden(True) 

        if not parent.lvReadonly: 

            self.lvmCache.setReadonly(parent.fileName, True) 

        self._updateSlavesOnUndoLeafCoalesce(parent, child) 

        util.fistpoint.activate("LVHDRT_coaleaf_undo_end", self.uuid) 

        Util.log("*** leaf-coalesce undo successful") 

        if util.fistpoint.is_active("LVHDRT_coaleaf_stop_after_recovery"): 

            child.setConfig(VDI.DB_LEAFCLSC, VDI.LEAFCLSC_DISABLED) 

 

    def _finishInterruptedCoalesceLeaf(self, childUuid, parentUuid): 

        Util.log("*** FINISH LEAF-COALESCE") 

        vdi = self.getVDI(childUuid) 

        if not vdi: 

            raise util.SMException("VDI %s not found" % childUuid) 

        vdi.inflateFully() 

        util.fistpoint.activate("LVHDRT_coaleaf_finish_after_inflate", self.uuid) 

        try: 

            self.forgetVDI(parentUuid) 

        except XenAPI.Failure: 

            pass 

        self._updateSlavesOnResize(vdi) 

        util.fistpoint.activate("LVHDRT_coaleaf_finish_end", self.uuid) 

        Util.log("*** finished leaf-coalesce successfully") 

 

    def _checkSlaves(self, vdi): 

        """Confirm with all slaves in the pool that 'vdi' is not in use. We 

        try to check all slaves, including those that the Agent believes are 

        offline, but ignore failures for offline hosts. This is to avoid cases 

        where the Agent thinks a host is offline but the host is up.""" 

        args = {"vgName" : self.vgName, 

                "action1": "deactivateNoRefcount", 

                "lvName1": vdi.fileName, 

                "action2": "cleanupLockAndRefcount", 

                "uuid2"  : vdi.uuid, 

                "ns2"    : lvhdutil.NS_PREFIX_LVM + self.uuid} 

        onlineHosts = self.xapi.getOnlineHosts() 

        abortFlag = IPCFlag(self.uuid) 

        for pbdRecord in self.xapi.getAttachedPBDs(): 

            hostRef = pbdRecord["host"] 

            if hostRef == self.xapi._hostRef: 

                continue 

            if abortFlag.test(FLAG_TYPE_ABORT): 

                raise AbortException("Aborting due to signal") 

            Util.log("Checking with slave %s (path %s)" % ( 

                self.xapi.getRecordHost(hostRef)['hostname'], vdi.path)) 

            try: 

                self.xapi.ensureInactive(hostRef, args) 

            except XenAPI.Failure: 

                if hostRef in onlineHosts: 

                    raise 

 

    def _updateSlavesOnUndoLeafCoalesce(self, parent, child): 

        slaves = util.get_slaves_attached_on(self.xapi.session, [child.uuid]) 

        if not slaves: 

            Util.log("Update-on-leaf-undo: VDI %s not attached on any slave" % \ 

                    child) 

            return 

 

        tmpName = lvhdutil.LV_PREFIX[vhdutil.VDI_TYPE_VHD] + \ 

                self.TMP_RENAME_PREFIX + child.uuid 

        args = {"vgName" : self.vgName, 

                "action1": "deactivateNoRefcount", 

                "lvName1": tmpName, 

                "action2": "deactivateNoRefcount", 

                "lvName2": child.fileName, 

                "action3": "refresh", 

                "lvName3": child.fileName, 

                "action4": "refresh", 

                "lvName4": parent.fileName} 

        for slave in slaves: 

            Util.log("Updating %s, %s, %s on slave %s" % \ 

                    (tmpName, child.fileName, parent.fileName, 

                     self.xapi.getRecordHost(slave)['hostname'])) 

            text = self.xapi.session.xenapi.host.call_plugin( \ 

                    slave, self.xapi.PLUGIN_ON_SLAVE, "multi", args) 

            Util.log("call-plugin returned: '%s'" % text) 

 

    def _updateSlavesOnRename(self, vdi, oldNameLV, origParentUuid): 

        slaves = util.get_slaves_attached_on(self.xapi.session, [vdi.uuid]) 

        if not slaves: 

            Util.log("Update-on-rename: VDI %s not attached on any slave" % vdi) 

            return 

 

        args = {"vgName" : self.vgName, 

                "action1": "deactivateNoRefcount", 

                "lvName1": oldNameLV, 

                "action2": "refresh", 

                "lvName2": vdi.fileName, 

                "action3": "cleanupLockAndRefcount", 

                "uuid3"  : origParentUuid, 

                "ns3"    : lvhdutil.NS_PREFIX_LVM + self.uuid} 

        for slave in slaves: 

            Util.log("Updating %s to %s on slave %s" % \ 

                    (oldNameLV, vdi.fileName, 

                     self.xapi.getRecordHost(slave)['hostname'])) 

            text = self.xapi.session.xenapi.host.call_plugin( \ 

                    slave, self.xapi.PLUGIN_ON_SLAVE, "multi", args) 

            Util.log("call-plugin returned: '%s'" % text) 

 

    def _updateSlavesOnResize(self, vdi): 

        uuids = map(lambda x: x.uuid, vdi.getAllLeaves()) 

        slaves = util.get_slaves_attached_on(self.xapi.session, uuids) 

        if not slaves: 

            util.SMlog("Update-on-resize: %s not attached on any slave" % vdi) 

            return 

        lvhdutil.lvRefreshOnSlaves(self.xapi.session, self.uuid, self.vgName, 

                vdi.fileName, vdi.uuid, slaves) 

 

 

class LinstorSR(SR): 

    TYPE = SR.TYPE_LINSTOR 

 

    def __init__(self, uuid, xapi, createLock, force): 

        if not LINSTOR_AVAILABLE: 

            raise util.SMException( 

                'Can\'t load cleanup LinstorSR: LINSTOR libraries are missing' 

            ) 

 

        SR.__init__(self, uuid, xapi, createLock, force) 

        self._master_uri = 'linstor://localhost' 

        self.path = LinstorVolumeManager.DEV_ROOT_PATH 

        self._reloadLinstor() 

 

    def deleteVDI(self, vdi): 

        self._checkSlaves(vdi) 

        SR.deleteVDI(self, vdi) 

 

    def getFreeSpace(self): 

        return self._linstor.max_volume_size_allowed 

 

    def scan(self, force=False): 

        all_vdi_info = self._scan(force) 

        for uuid, vdiInfo in all_vdi_info.iteritems(): 

            # When vdiInfo is None, the VDI is RAW. 

            vdi = self.getVDI(uuid) 

            if not vdi: 

                self.logFilter.logNewVDI(uuid) 

                vdi = LinstorVDI(self, uuid, not vdiInfo) 

                self.vdis[uuid] = vdi 

            if vdiInfo: 

                vdi.load(vdiInfo) 

        self._removeStaleVDIs(all_vdi_info.keys()) 

        self._buildTree(force) 

        self.logFilter.logState() 

        self._handleInterruptedCoalesceLeaf() 

 

    def _reloadLinstor(self): 

        session = self.xapi.session 

        host_ref = util.get_this_host_ref(session) 

        sr_ref = session.xenapi.SR.get_by_uuid(self.uuid) 

 

        pbd = util.find_my_pbd(session, host_ref, sr_ref) 

        if pbd is None: 

            raise util.SMException('Failed to find PBD') 

 

        dconf = session.xenapi.PBD.get_device_config(pbd) 

        group_name = dconf['group-name'] 

 

        self.journaler = LinstorJournaler( 

            self._master_uri, group_name, logger=util.SMlog 

        ) 

 

        self._linstor = LinstorVolumeManager( 

            self._master_uri, 

            group_name, 

            repair=True, 

            logger=util.SMlog 

        ) 

        self._vhdutil = LinstorVhdUtil(session, self._linstor) 

 

    def _scan(self, force): 

        for i in range(SR.SCAN_RETRY_ATTEMPTS): 

            self._reloadLinstor() 

            error = False 

            try: 

                all_vdi_info = self._load_vdi_info() 

                for uuid, vdiInfo in all_vdi_info.iteritems(): 

                    if vdiInfo and vdiInfo.error: 

                        error = True 

                        break 

                if not error: 

                    return all_vdi_info 

                Util.log('Scan error, retrying ({})'.format(i)) 

            except Exception as e: 

                Util.log('Scan exception, retrying ({}): {}'.format(i, e)) 

                Util.log(traceback.format_exc()) 

 

        if force: 

            return all_vdi_info 

        raise util.SMException('Scan error') 

 

    def _load_vdi_info(self): 

        all_vdi_info = {} 

 

        # TODO: Ensure metadata contains the right info. 

 

        all_volume_info = self._linstor.volumes_with_info 

        volumes_metadata = self._linstor.volumes_with_metadata 

        for vdi_uuid, volume_info in all_volume_info.items(): 

            try: 

                if not volume_info.name and \ 

                        not list(volumes_metadata[vdi_uuid].items()): 

                    continue  # Ignore it, probably deleted. 

 

                vdi_type = volumes_metadata[vdi_uuid][VDI_TYPE_TAG] 

                if vdi_type == vhdutil.VDI_TYPE_VHD: 

                    info = self._vhdutil.get_vhd_info(vdi_uuid) 

                else: 

                    info = None 

            except Exception as e: 

                Util.log( 

                    ' [VDI {}: failed to load VDI info]: {}' 

                    .format(self.uuid, e) 

                ) 

                info = vhdutil.VHDInfo(vdi_uuid) 

                info.error = 1 

            all_vdi_info[vdi_uuid] = info 

        return all_vdi_info 

 

    # TODO: Maybe implement _liveLeafCoalesce/_prepareCoalesceLeaf/ 

    # _finishCoalesceLeaf/_updateSlavesOnResize like LVM plugin. 

 

    def _calcExtraSpaceNeeded(self, child, parent): 

        meta_overhead = vhdutil.calcOverheadEmpty(LinstorVDI.MAX_SIZE) 

        bitmap_overhead = vhdutil.calcOverheadBitmap(parent.sizeVirt) 

        virtual_size = LinstorVolumeManager.round_up_volume_size( 

            parent.sizeVirt + meta_overhead + bitmap_overhead 

        ) 

        # TODO: Check result. 

        return virtual_size - self._linstor.get_volume_size(parent.uuid) 

 

    def _hasValidDevicePath(self, uuid): 

        try: 

            self._linstor.get_device_path(uuid) 

        except Exception: 

            # TODO: Maybe log exception. 

            return False 

        return True 

 

    def _handleInterruptedCoalesceLeaf(self): 

        entries = self.journaler.get_all(VDI.JRN_LEAF) 

        for uuid, parentUuid in entries.iteritems(): 

            if self._hasValidDevicePath(parentUuid) or \ 

                    self._hasValidDevicePath(self.TMP_RENAME_PREFIX + uuid): 

                self._undoInterruptedCoalesceLeaf(uuid, parentUuid) 

            else: 

                self._finishInterruptedCoalesceLeaf(uuid, parentUuid) 

            self.journaler.remove(VDI.JRN_LEAF, uuid) 

            vdi = self.getVDI(uuid) 

            if vdi: 

                vdi.ensureUnpaused() 

 

    def _undoInterruptedCoalesceLeaf(self, childUuid, parentUuid): 

        Util.log('*** UNDO LEAF-COALESCE') 

        parent = self.getVDI(parentUuid) 

        if not parent: 

            parent = self.getVDI(childUuid) 

            if not parent: 

                raise util.SMException( 

                    'Neither {} nor {} found'.format(parentUuid, childUuid) 

                ) 

            Util.log( 

                'Renaming parent back: {} -> {}'.format(childUuid, parentUuid) 

            ) 

            parent.rename(parentUuid) 

        util.fistpoint.activate('LVHDRT_coaleaf_undo_after_rename', self.uuid) 

 

        child = self.getVDI(childUuid) 

        if not child: 

            child = self.getVDI(self.TMP_RENAME_PREFIX + childUuid) 

            if not child: 

                raise util.SMException( 

                    'Neither {} nor {} found'.format( 

                        childUuid, self.TMP_RENAME_PREFIX + childUuid 

                    ) 

                ) 

            Util.log('Renaming child back to {}'.format(childUuid)) 

            child.rename(childUuid) 

            Util.log('Updating the VDI record') 

            child.setConfig(VDI.DB_VHD_PARENT, parentUuid) 

            child.setConfig(VDI.DB_VDI_TYPE, vhdutil.VDI_TYPE_VHD) 

            util.fistpoint.activate( 

                'LVHDRT_coaleaf_undo_after_rename2', self.uuid 

            ) 

 

        # TODO: Maybe deflate here. 

 

        if child.hidden: 

            child._setHidden(False) 

        if not parent.hidden: 

            parent._setHidden(True) 

        self._updateSlavesOnUndoLeafCoalesce(parent, child) 

        util.fistpoint.activate('LVHDRT_coaleaf_undo_end', self.uuid) 

        Util.log('*** leaf-coalesce undo successful') 

        if util.fistpoint.is_active('LVHDRT_coaleaf_stop_after_recovery'): 

            child.setConfig(VDI.DB_LEAFCLSC, VDI.LEAFCLSC_DISABLED) 

 

    def _finishInterruptedCoalesceLeaf(self, childUuid, parentUuid): 

        Util.log('*** FINISH LEAF-COALESCE') 

        vdi = self.getVDI(childUuid) 

        if not vdi: 

            raise util.SMException('VDI {} not found'.format(childUuid)) 

        # TODO: Maybe inflate. 

        try: 

            self.forgetVDI(parentUuid) 

        except XenAPI.Failure: 

            pass 

        self._updateSlavesOnResize(vdi) 

        util.fistpoint.activate('LVHDRT_coaleaf_finish_end', self.uuid) 

        Util.log('*** finished leaf-coalesce successfully') 

 

    def _checkSlaves(self, vdi): 

        try: 

            states = self._linstor.get_usage_states(vdi.uuid) 

            for node_name, state in states.items(): 

                self._checkSlave(node_name, vdi, state) 

        except LinstorVolumeManagerError as e: 

            if e.code != LinstorVolumeManagerError.ERR_VOLUME_NOT_EXISTS: 

                raise 

 

    @staticmethod 

    def _checkSlave(node_name, vdi, state): 

        # If state is None, LINSTOR doesn't know the host state 

        # (bad connection?). 

        if state is None: 

            raise util.SMException( 

                'Unknown state for VDI {} on {}'.format(vdi.uuid, node_name) 

            ) 

 

        if state: 

            raise util.SMException( 

                'VDI {} is in use on {}'.format(vdi.uuid, node_name) 

            ) 

 

 

################################################################################ 

# 

#  Helpers 

# 

def daemonize(): 

    pid = os.fork() 

3095    if pid: 

        os.waitpid(pid, 0) 

        Util.log("New PID [%d]" % pid) 

        return False 

    os.chdir("/") 

    os.setsid() 

    pid = os.fork() 

    if pid: 

        Util.log("Will finish as PID [%d]" % pid) 

        os._exit(0) 

    for fd in [0, 1, 2]: 

        try: 

            os.close(fd) 

        except OSError: 

            pass 

    # we need to fill those special fd numbers or pread won't work 

    sys.stdin = open("/dev/null", 'r') 

    sys.stderr = open("/dev/null", 'w') 

    sys.stdout = open("/dev/null", 'w') 

    # As we're a new process we need to clear the lock objects 

    lock.Lock.clearAll() 

    return True 

 

def normalizeType(type): 

    if type in LVHDSR.SUBTYPES: 

        type = SR.TYPE_LVHD 

    if type in ["lvm", "lvmoiscsi", "lvmohba", "lvmofcoe"]: 

        # temporary while LVHD is symlinked as LVM 

        type = SR.TYPE_LVHD 

    if type in [ 

        "ext", "nfs", "ocfsoiscsi", "ocfsohba", "smb", "cephfs", "glusterfs", 

        "moosefs", "xfs", "zfs", "ext4" 

    ]: 

        type = SR.TYPE_FILE 

    if type in ["linstor"]: 

        type = SR.TYPE_LINSTOR 

    if type not in SR.TYPES: 

        raise util.SMException("Unsupported SR type: %s" % type) 

    return type 

 

 

GCPAUSE_DEFAULT_SLEEP = 5 * 60 

 

 

def _gc_init_file(sr_uuid): 

    return os.path.join(NON_PERSISTENT_DIR, str(sr_uuid), 'gc_init') 

 

 

def _create_init_file(sr_uuid): 

    util.makedirs(os.path.join(NON_PERSISTENT_DIR, str(sr_uuid))) 

    with open(os.path.join( 

            NON_PERSISTENT_DIR, str(sr_uuid), 'gc_init'), 'w+') as f: 

        f.write('1') 

 

 

def _gcLoopPause(sr, dryRun): 

 

    # Check to see if the GCPAUSE_FISTPOINT is present. If so the fist 

    # point will just return. Otherwise, fall back on an abortable sleep. 

 

    if util.fistpoint.is_active(util.GCPAUSE_FISTPOINT): 

 

exit        util.fistpoint.activate_custom_fn(util.GCPAUSE_FISTPOINT, 

                                          lambda *args: None) 

    elif os.path.exists(_gc_init_file(sr.uuid)): 

        def abortTest(): 

            return IPCFlag(sr.uuid).test(FLAG_TYPE_ABORT) 

 

        # If time.sleep hangs we are in deep trouble, however for 

        # completeness we set the timeout of the abort thread to 

        # 110% of GCPAUSE_DEFAULT_SLEEP. 

        Util.log("GC active, about to go quiet") 

exit        Util.runAbortable(lambda: time.sleep(GCPAUSE_DEFAULT_SLEEP), 

                          None, sr.uuid, abortTest, VDI.POLL_INTERVAL, 

                          GCPAUSE_DEFAULT_SLEEP*1.1) 

        Util.log("GC active, quiet period ended") 

 

def _gcLoop(sr, dryRun): 

    if not lockActive.acquireNoblock(): 

        Util.log("Another GC instance already active, exiting") 

        return 

    try: 

        # Check if any work needs to be done 

        sr.scanLocked() 

        if not sr.hasWork(): 

            Util.log("No work, exiting") 

            return 

        _gcLoopPause(sr, dryRun) 

        while True: 

            if not sr.xapi.isPluggedHere(): 

                Util.log("SR no longer attached, exiting") 

                break 

            sr.scanLocked() 

            if not sr.hasWork(): 

                Util.log("No work, exiting") 

                break 

 

            if not lockRunning.acquireNoblock(): 

                Util.log("Unable to acquire GC running lock.") 

                return 

            try: 

                if not sr.gcEnabled(): 

                    break 

                sr.cleanupCoalesceJournals() 

                # Create the init file here in case startup is waiting on it 

                _create_init_file(sr.uuid) 

                sr.scanLocked() 

                sr.updateBlockInfo() 

 

                howmany = len(sr.findGarbage()) 

                if howmany > 0: 

                    Util.log("Found %d orphaned vdis" % howmany) 

                    sr.lock() 

                    try: 

                        sr.garbageCollect(dryRun) 

                    finally: 

                        sr.unlock() 

                    sr.xapi.srUpdate() 

 

                candidate = sr.findCoalesceable() 

                if candidate: 

                    util.fistpoint.activate( 

                        "LVHDRT_finding_a_suitable_pair", sr.uuid) 

                    sr.coalesce(candidate, dryRun) 

                    sr.xapi.srUpdate() 

                    continue 

 

                candidate = sr.findLeafCoalesceable() 

                if candidate: 

                    sr.coalesceLeaf(candidate, dryRun) 

                    sr.xapi.srUpdate() 

                    continue 

 

            finally: 

                lockRunning.release() 

    finally: 

        Util.log("GC process exiting, no work left") 

        _create_init_file(sr.uuid) 

        lockActive.release() 

 

 

def _xapi_enabled(session, hostref): 

    host = session.xenapi.host.get_record(hostref) 

    return host['enabled'] 

 

 

def _ensure_xapi_initialised(session): 

    """ 

    Don't want to start GC until Xapi is fully initialised 

    """ 

    local_session = None 

    if session is None: 

        local_session = util.get_localAPI_session() 

        session = local_session 

 

    try: 

        hostref = session.xenapi.host.get_by_uuid(util.get_this_host()) 

        while not _xapi_enabled(session, hostref): 

            util.SMlog("Xapi not ready, GC waiting") 

            time.sleep(15) 

    finally: 

        if local_session is not None: 

            local_session.logout() 

 

def _gc(session, srUuid, dryRun): 

    init(srUuid) 

    _ensure_xapi_initialised(session) 

    sr = SR.getInstance(srUuid, session) 

    if not sr.gcEnabled(False): 

        return 

 

    sr.cleanupCache() 

    try: 

        _gcLoop(sr, dryRun) 

    finally: 

        sr.cleanup() 

        sr.logFilter.logState() 

        del sr.xapi 

 

def _abort(srUuid, soft=False): 

    """Aborts an GC/coalesce. 

 

    srUuid: the UUID of the SR whose GC/coalesce must be aborted 

    soft: If set to True and there is a pending abort signal, the function 

    doesn't do anything. If set to False, a new abort signal is issued. 

 

    returns: If soft is set to False, we return True holding lockActive. If 

    soft is set to False and an abort signal is pending, we return False 

    without holding lockActive. An exception is raised in case of error.""" 

    Util.log("=== SR %s: abort ===" % (srUuid)) 

    init(srUuid) 

    if not lockActive.acquireNoblock(): 

        gotLock = False 

        Util.log("Aborting currently-running instance (SR %s)" % srUuid) 

        abortFlag = IPCFlag(srUuid) 

        if not abortFlag.set(FLAG_TYPE_ABORT, soft): 

            return False 

        for i in range(SR.LOCK_RETRY_ATTEMPTS): 

            gotLock = lockActive.acquireNoblock() 

            if gotLock: 

                break 

            time.sleep(SR.LOCK_RETRY_INTERVAL) 

        abortFlag.clear(FLAG_TYPE_ABORT) 

        if not gotLock: 

            raise util.CommandException(code=errno.ETIMEDOUT, 

                    reason="SR %s: error aborting existing process" % srUuid) 

    return True 

 

def init(srUuid): 

    global lockRunning 

    if not lockRunning: 

        lockRunning = lock.Lock(LOCK_TYPE_RUNNING, srUuid) 

    global lockActive 

    if not lockActive: 

        lockActive = lock.Lock(LOCK_TYPE_GC_ACTIVE, srUuid) 

 

def usage(): 

    output = """Garbage collect and/or coalesce VHDs in a VHD-based SR 

 

Parameters: 

    -u --uuid UUID   SR UUID 

and one of: 

    -g --gc          garbage collect, coalesce, and repeat while there is work 

    -G --gc_force    garbage collect once, aborting any current operations 

    -c --cache-clean <max_age> clean up IntelliCache cache files older than 

                     max_age hours 

    -a --abort       abort any currently running operation (GC or coalesce) 

    -q --query       query the current state (GC'ing, coalescing or not running) 

    -x --disable     disable GC/coalesce (will be in effect until you exit) 

    -t --debug       see Debug below 

 

Options: 

    -b --background  run in background (return immediately) (valid for -g only) 

    -f --force       continue in the presence of VHDs with errors (when doing 

                     GC, this might cause removal of any such VHDs) (only valid 

                     for -G) (DANGEROUS) 

 

Debug: 

    The --debug parameter enables manipulation of LVHD VDIs for debugging 

    purposes.  ** NEVER USE IT ON A LIVE VM ** 

    The following parameters are required: 

    -t --debug <cmd> <cmd> is one of "activate", "deactivate", "inflate", 

                     "deflate". 

    -v --vdi_uuid    VDI UUID 

    """ 

   #-d --dry-run     don't actually perform any SR-modifying operations 

    print output 

    Util.log("(Invalid usage)") 

    sys.exit(1) 

 

 

############################################################################## 

# 

#  API 

# 

def abort(srUuid, soft=False): 

    """Abort GC/coalesce if we are currently GC'ing or coalescing a VDI pair. 

    """ 

    if _abort(srUuid, soft): 

        Util.log("abort: releasing the process lock") 

        lockActive.release() 

        return True 

    else: 

        return False 

 

def gc(session, srUuid, inBackground, dryRun = False): 

    """Garbage collect all deleted VDIs in SR "srUuid". Fork & return  

    immediately if inBackground=True.  

     

    The following algorithm is used: 

    1. If we are already GC'ing in this SR, return 

    2. If we are already coalescing a VDI pair: 

        a. Scan the SR and determine if the VDI pair is GC'able 

        b. If the pair is not GC'able, return 

        c. If the pair is GC'able, abort coalesce 

    3. Scan the SR 

    4. If there is nothing to collect, nor to coalesce, return 

    5. If there is something to collect, GC all, then goto 3 

    6. If there is something to coalesce, coalesce one pair, then goto 3 

    """ 

    Util.log("=== SR %s: gc ===" % srUuid) 

3387    if inBackground: 

3378        if daemonize(): 

            # we are now running in the background. Catch & log any errors  

            # because there is no other way to propagate them back at this  

            # point 

 

            try: 

                _gc(None, srUuid, dryRun) 

            except AbortException: 

                Util.log("Aborted") 

            except Exception: 

                Util.logException("gc") 

                Util.log("* * * * * SR %s: ERROR\n" % srUuid) 

            os._exit(0) 

    else: 

        _gc(session, srUuid, dryRun) 

 

def gc_force(session, srUuid, force = False, dryRun = False, lockSR = False): 

    """Garbage collect all deleted VDIs in SR "srUuid". The caller must ensure 

    the SR lock is held. 

    The following algorithm is used: 

    1. If we are already GC'ing or coalescing a VDI pair, abort GC/coalesce 

    2. Scan the SR 

    3. GC 

    4. return 

    """ 

    Util.log("=== SR %s: gc_force ===" % srUuid) 

    init(srUuid) 

    sr = SR.getInstance(srUuid, session, lockSR, True) 

    if not lockActive.acquireNoblock(): 

        abort(srUuid) 

    else: 

        Util.log("Nothing was running, clear to proceed") 

 

    if force: 

        Util.log("FORCED: will continue even if there are VHD errors") 

    sr.scanLocked(force) 

    sr.cleanupCoalesceJournals() 

 

    try: 

        sr.cleanupCache() 

        sr.garbageCollect(dryRun) 

    finally: 

        sr.cleanup() 

        sr.logFilter.logState() 

        lockActive.release() 

 

def get_state(srUuid): 

    """Return whether GC/coalesce is currently running or not. The information 

    is not guaranteed for any length of time if the call is not protected by 

    locking. 

    """ 

    init(srUuid) 

    if lockActive.acquireNoblock(): 

        lockActive.release() 

        return False 

    return True 

 

def should_preempt(session, srUuid): 

    sr = SR.getInstance(srUuid, session) 

    entries = sr.journaler.getAll(VDI.JRN_COALESCE) 

    if len(entries) == 0: 

        return False 

    elif len(entries) > 1: 

        raise util.SMException("More than one coalesce entry: " + str(entries)) 

    sr.scanLocked() 

    coalescedUuid = entries.popitem()[0] 

    garbage = sr.findGarbage() 

    for vdi in garbage: 

        if vdi.uuid == coalescedUuid: 

            return True 

    return False 

 

def get_coalesceable_leaves(session, srUuid, vdiUuids): 

    coalesceable = [] 

    sr = SR.getInstance(srUuid, session) 

    sr.scanLocked() 

    for uuid in vdiUuids: 

        vdi = sr.getVDI(uuid) 

        if not vdi: 

            raise util.SMException("VDI %s not found" % uuid) 

        if vdi.isLeafCoalesceable(): 

            coalesceable.append(uuid) 

    return coalesceable 

 

def cache_cleanup(session, srUuid, maxAge): 

    sr = SR.getInstance(srUuid, session) 

    return sr.cleanupCache(maxAge) 

 

def debug(sr_uuid, cmd, vdi_uuid): 

    Util.log("Debug command: %s" % cmd) 

    sr = SR.getInstance(sr_uuid, None) 

    if not isinstance(sr, LVHDSR): 

        print "Error: not an LVHD SR" 

        return 

    sr.scanLocked() 

    vdi = sr.getVDI(vdi_uuid) 

    if not vdi: 

        print "Error: VDI %s not found" 

        return 

    print "Running %s on SR %s" % (cmd, sr) 

    print "VDI before: %s" % vdi 

    if cmd == "activate": 

        vdi._activate() 

        print "VDI file: %s" % vdi.path 

    if cmd == "deactivate": 

        ns = lvhdutil.NS_PREFIX_LVM + sr.uuid 

        sr.lvmCache.deactivate(ns, vdi.uuid, vdi.fileName, False) 

    if cmd == "inflate": 

        vdi.inflateFully() 

        sr.cleanup() 

    if cmd == "deflate": 

        vdi.deflate() 

        sr.cleanup() 

    sr.scanLocked() 

    print "VDI after:  %s" % vdi 

 

 

def abort_optional_reenable(uuid): 

    print "Disabling GC/coalesce for %s" % uuid 

    ret = _abort(uuid) 

    raw_input("Press enter to re-enable...") 

    print "GC/coalesce re-enabled" 

    lockRunning.release() 

    if ret: 

        lockActive.release() 

 

############################################################################## 

# 

#  CLI 

# 

def main(): 

    action     = "" 

    uuid       = "" 

    background = False 

    force      = False 

    dryRun     = False 

    debug_cmd  = "" 

    vdi_uuid   = "" 

    shortArgs  = "gGc:aqxu:bfdt:v:" 

    longArgs   = ["gc", "gc_force", "clean_cache", "abort", "query", "disable", 

            "uuid=", "background", "force", "dry-run", "debug=", "vdi_uuid="] 

 

    try: 

        opts, args = getopt.getopt(sys.argv[1:], shortArgs, longArgs) 

    except getopt.GetoptError: 

        usage() 

    for o, a in opts: 

        if o in ("-g", "--gc"): 

            action = "gc" 

        if o in ("-G", "--gc_force"): 

            action = "gc_force" 

        if o in ("-c", "--clean_cache"): 

            action = "clean_cache" 

            maxAge = int(a) 

        if o in ("-a", "--abort"): 

            action = "abort" 

        if o in ("-q", "--query"): 

            action = "query" 

        if o in ("-x", "--disable"): 

            action = "disable" 

        if o in ("-u", "--uuid"): 

            uuid = a 

        if o in ("-b", "--background"): 

            background = True 

        if o in ("-f", "--force"): 

            force = True 

        if o in ("-d", "--dry-run"): 

            Util.log("Dry run mode") 

            dryRun = True 

        if o in ("-t", "--debug"): 

            action = "debug" 

            debug_cmd = a 

        if o in ("-v", "--vdi_uuid"): 

            vdi_uuid = a 

 

    if not action or not uuid: 

        usage() 

    if action == "debug" and not (debug_cmd and vdi_uuid) or \ 

            action != "debug" and (debug_cmd or vdi_uuid): 

        usage() 

 

    if action != "query" and action != "debug": 

        print "All output goes to log" 

 

    if action == "gc": 

        gc(None, uuid, background, dryRun) 

    elif action == "gc_force": 

        gc_force(None, uuid, force, dryRun, True) 

    elif action == "clean_cache": 

        cache_cleanup(None, uuid, maxAge) 

    elif action == "abort": 

        abort(uuid) 

    elif action == "query": 

        print "Currently running: %s" % get_state(uuid) 

    elif action == "disable": 

        abort_optional_reenable(uuid) 

    elif action == "debug": 

        debug(uuid, debug_cmd, vdi_uuid) 

 

 

3574if __name__ == '__main__': 

    main()