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

#!/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 

# 

# LVHDSR: VHD on LVM storage repository 

# 

 

import SR 

from SR import deviceCheck 

import VDI 

import SRCommand 

import util 

import lvutil 

import lvmcache 

import vhdutil 

import lvhdutil 

import scsiutil 

import os 

import sys 

import time 

import errno 

import xs_errors 

import cleanup 

import blktap2 

from journaler import Journaler 

from lock import Lock 

from refcounter import RefCounter 

from ipc import IPCFlag 

from lvmanager import LVActivator 

import XenAPI 

import re 

from srmetadata import ALLOCATION_TAG, NAME_LABEL_TAG, NAME_DESCRIPTION_TAG, \ 

    UUID_TAG, IS_A_SNAPSHOT_TAG, SNAPSHOT_OF_TAG, TYPE_TAG, VDI_TYPE_TAG, \ 

    READ_ONLY_TAG, MANAGED_TAG, SNAPSHOT_TIME_TAG, METADATA_OF_POOL_TAG, \ 

    requiresUpgrade, LVMMetadataHandler, METADATA_OBJECT_TYPE_VDI, \ 

    METADATA_OBJECT_TYPE_SR, METADATA_UPDATE_OBJECT_TYPE_TAG 

from metadata import retrieveXMLfromFile, _parseXML 

from xmlrpclib import DateTime 

import glob 

from constants import CBTLOG_TAG 

DEV_MAPPER_ROOT = os.path.join('/dev/mapper', lvhdutil.VG_PREFIX) 

 

geneology = {} 

CAPABILITIES = ["SR_PROBE","SR_UPDATE", "SR_TRIM", 

        "VDI_CREATE","VDI_DELETE","VDI_ATTACH", "VDI_DETACH", "VDI_MIRROR", 

        "VDI_CLONE", "VDI_SNAPSHOT", "VDI_RESIZE", "ATOMIC_PAUSE", 

        "VDI_RESET_ON_BOOT/2", "VDI_UPDATE", "VDI_CONFIG_CBT", 

        "VDI_ACTIVATE", "VDI_DEACTIVATE"] 

 

CONFIGURATION = [ ['device', 'local device path (required) (e.g. /dev/sda3)'] ] 

 

 

DRIVER_INFO = { 

    'name': 'Local VHD on LVM', 

    'description': 'SR plugin which represents disks as VHD disks on ' + \ 

            'Logical Volumes within a locally-attached Volume Group', 

    'vendor': 'XenSource Inc', 

    'copyright': '(C) 2008 XenSource Inc', 

    'driver_version': '1.0', 

    'required_api_version': '1.0', 

    'capabilities': CAPABILITIES, 

    'configuration': CONFIGURATION 

    } 

 

PARAM_VHD = "vhd" 

PARAM_RAW = "raw" 

 

OPS_EXCLUSIVE = [ 

        "sr_create", "sr_delete", "sr_attach", "sr_detach", "sr_scan", 

        "sr_update", "vdi_create", "vdi_delete", "vdi_resize", "vdi_snapshot", 

        "vdi_clone" ] 

 

# Log if snapshot pauses VM for more than this many seconds 

LONG_SNAPTIME = 60 

 

class LVHDSR(SR.SR): 

    DRIVER_TYPE = 'lvhd' 

 

    PROVISIONING_TYPES = ["thin", "thick"] 

    PROVISIONING_DEFAULT = "thick" 

    THIN_PLUGIN = "lvhd-thin" 

 

    PLUGIN_ON_SLAVE = "on-slave" 

 

    FLAG_USE_VHD = "use_vhd" 

    MDVOLUME_NAME = "MGT" 

 

    ALLOCATION_QUANTUM = "allocation_quantum" 

    INITIAL_ALLOCATION = "initial_allocation" 

 

    LOCK_RETRY_INTERVAL = 3 

    LOCK_RETRY_ATTEMPTS = 10 

 

    TEST_MODE_KEY = "testmode" 

    TEST_MODE_VHD_FAIL_REPARENT_BEGIN   = "vhd_fail_reparent_begin" 

    TEST_MODE_VHD_FAIL_REPARENT_LOCATOR = "vhd_fail_reparent_locator" 

    TEST_MODE_VHD_FAIL_REPARENT_END     = "vhd_fail_reparent_end" 

    TEST_MODE_VHD_FAIL_RESIZE_BEGIN     = "vhd_fail_resize_begin" 

    TEST_MODE_VHD_FAIL_RESIZE_DATA      = "vhd_fail_resize_data" 

    TEST_MODE_VHD_FAIL_RESIZE_METADATA  = "vhd_fail_resize_metadata" 

    TEST_MODE_VHD_FAIL_RESIZE_END       = "vhd_fail_resize_end" 

 

    ENV_VAR_VHD_TEST = { 

            TEST_MODE_VHD_FAIL_REPARENT_BEGIN: 

                "VHD_UTIL_TEST_FAIL_REPARENT_BEGIN", 

            TEST_MODE_VHD_FAIL_REPARENT_LOCATOR: 

                "VHD_UTIL_TEST_FAIL_REPARENT_LOCATOR", 

            TEST_MODE_VHD_FAIL_REPARENT_END: 

                "VHD_UTIL_TEST_FAIL_REPARENT_END", 

            TEST_MODE_VHD_FAIL_RESIZE_BEGIN: 

                "VHD_UTIL_TEST_FAIL_RESIZE_BEGIN", 

            TEST_MODE_VHD_FAIL_RESIZE_DATA: 

                "VHD_UTIL_TEST_FAIL_RESIZE_DATA_MOVED", 

            TEST_MODE_VHD_FAIL_RESIZE_METADATA: 

                "VHD_UTIL_TEST_FAIL_RESIZE_METADATA_MOVED", 

            TEST_MODE_VHD_FAIL_RESIZE_END: 

                "VHD_UTIL_TEST_FAIL_RESIZE_END" 

    } 

    testMode = "" 

 

    legacyMode = True 

 

    def handles(type): 

        """Returns True if this SR class understands the given dconf string""" 

        # we can pose as LVMSR or EXTSR for compatibility purposes 

        if __name__ == '__main__': 

            name = sys.argv[0] 

        else: 

            name = __name__ 

        if name.endswith("LVMSR"): 

            return type == "lvm" 

        elif name.endswith("EXTSR"): 

            return type == "ext" 

        return type == LVHDSR.DRIVER_TYPE 

    handles = staticmethod(handles) 

 

    def load(self, sr_uuid): 

        self.ops_exclusive = OPS_EXCLUSIVE 

 

        self.isMaster = False 

155        if self.dconf.has_key('SRmaster') and self.dconf['SRmaster'] == 'true': 

            self.isMaster = True 

 

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

        self.sr_vditype = SR.DEFAULT_TAP 

        self.uuid = sr_uuid 

        self.vgname = lvhdutil.VG_PREFIX + self.uuid 

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

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

        self.provision = self.PROVISIONING_DEFAULT 

        try: 

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

        except: 

            raise xs_errors.XenError('SRUnavailable', \ 

                        opterr='Failed to initialise the LVMCache') 

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

        self.journaler = Journaler(self.lvmCache) 

174        if not self.srcmd.params.get("sr_ref"): 

            return # must be a probe call 

        # Test for thick vs thin provisioning conf parameter 

        if self.dconf.has_key('allocation'): 

            if self.dconf['allocation'] in self.PROVISIONING_TYPES: 

                self.provision = self.dconf['allocation'] 

            else: 

                raise xs_errors.XenError('InvalidArg', \ 

                        opterr='Allocation parameter must be one of %s' % self.PROVISIONING_TYPES) 

 

        self.other_conf = self.session.xenapi.SR.get_other_config(self.sr_ref) 

        if self.other_conf.get(self.TEST_MODE_KEY): 

            self.testMode = self.other_conf[self.TEST_MODE_KEY] 

            self._prepareTestMode() 

 

        self.sm_config = self.session.xenapi.SR.get_sm_config(self.sr_ref) 

        # sm_config flag overrides PBD, if any 

        if self.sm_config.get('allocation') in self.PROVISIONING_TYPES: 

            self.provision = self.sm_config.get('allocation') 

 

        if self.sm_config.get(self.FLAG_USE_VHD) == "true": 

            self.legacyMode = False 

 

        if lvutil._checkVG(self.vgname): 

            if self.isMaster and not self.cmd in ["vdi_attach", "vdi_detach", 

                    "vdi_activate", "vdi_deactivate"]: 

                self._undoAllJournals() 

            if not self.cmd in ["sr_attach","sr_probe"]: 

                self._checkMetadataVolume() 

 

        self.mdexists = False 

 

        # get a VDI -> TYPE map from the storage 

        contains_uuid_regex = \ 

            re.compile("^.*[0-9a-f]{8}-(([0-9a-f]{4})-){3}[0-9a-f]{12}.*") 

        self.storageVDIs = {} 

 

        for key in self.lvmCache.lvs.keys(): 

            # if the lvname has a uuid in it 

            type = None 

            if contains_uuid_regex.search(key) != None: 

                if key.startswith(lvhdutil.LV_PREFIX[vhdutil.VDI_TYPE_VHD]): 

                    type = vhdutil.VDI_TYPE_VHD 

                    vdi = key[len(lvhdutil.LV_PREFIX[type]):] 

                elif key.startswith(lvhdutil.LV_PREFIX[vhdutil.VDI_TYPE_RAW]): 

                    type = vhdutil.VDI_TYPE_RAW 

                    vdi = key[len(lvhdutil.LV_PREFIX[type]):] 

                else: 

                    continue 

 

            if type != None: 

                self.storageVDIs[vdi] = type 

 

        # check if metadata volume exists 

        try: 

            self.mdexists = self.lvmCache.checkLV(self.MDVOLUME_NAME) 

        except: 

            pass 

 

    def cleanup(self): 

        # we don't need to hold the lock to dec refcounts of activated LVs 

        if not self.lvActivator.deactivateAll(): 

            raise util.SMException("failed to deactivate LVs") 

 

    def updateSRMetadata(self, allocation): 

        try: 

            # Add SR specific SR metadata 

            sr_info = \ 

            { ALLOCATION_TAG: allocation, 

              UUID_TAG: self.uuid, 

              NAME_LABEL_TAG: util.to_plain_string\ 

                (self.session.xenapi.SR.get_name_label(self.sr_ref)), 

              NAME_DESCRIPTION_TAG: util.to_plain_string\ 

                (self.session.xenapi.SR.get_name_description(self.sr_ref)) 

            } 

 

            vdi_info = {} 

            for vdi in self.session.xenapi.SR.get_VDIs(self.sr_ref): 

                vdi_uuid = self.session.xenapi.VDI.get_uuid(vdi) 

 

                # Create the VDI entry in the SR metadata 

                vdi_info[vdi_uuid] = \ 

                { 

                    UUID_TAG: vdi_uuid, 

                    NAME_LABEL_TAG: util.to_plain_string\ 

                        (self.session.xenapi.VDI.get_name_label(vdi)), 

                    NAME_DESCRIPTION_TAG: util.to_plain_string\ 

                        (self.session.xenapi.VDI.get_name_description(vdi)), 

                    IS_A_SNAPSHOT_TAG: \ 

                        int(self.session.xenapi.VDI.get_is_a_snapshot(vdi)), 

                    SNAPSHOT_OF_TAG: \ 

                        self.session.xenapi.VDI.get_snapshot_of(vdi), 

                   SNAPSHOT_TIME_TAG: \ 

                        self.session.xenapi.VDI.get_snapshot_time(vdi), 

                    TYPE_TAG: \ 

                        self.session.xenapi.VDI.get_type(vdi), 

                    VDI_TYPE_TAG: \ 

                       self.session.xenapi.VDI.get_sm_config(vdi)\ 

                        ['vdi_type'], 

                    READ_ONLY_TAG: \ 

                        int(self.session.xenapi.VDI.get_read_only(vdi)), 

                    METADATA_OF_POOL_TAG: \ 

                        self.session.xenapi.VDI.get_metadata_of_pool(vdi), 

                    MANAGED_TAG: \ 

                        int(self.session.xenapi.VDI.get_managed(vdi)) 

                } 

            LVMMetadataHandler(self.mdpath).writeMetadata(sr_info, vdi_info) 

 

        except Exception, e: 

            raise xs_errors.XenError('MetadataError', \ 

                         opterr='Error upgrading SR Metadata: %s' % str(e)) 

 

    def syncMetadataAndStorage(self): 

        try: 

            # if a VDI is present in the metadata but not in the storage 

            # then delete it from the metadata 

            vdi_info = LVMMetadataHandler(self.mdpath, False).getMetadata()[1] 

            for vdi in vdi_info.keys(): 

                update_map = {} 

                if not vdi_info[vdi][UUID_TAG] in set(self.storageVDIs.keys()): 

                    # delete this from metadata 

                    LVMMetadataHandler(self.mdpath).\ 

                        deleteVdiFromMetadata(vdi_info[vdi][UUID_TAG]) 

                else: 

                    # search for this in the metadata, compare types 

                    # self.storageVDIs is a map of vdi_uuid to vdi_type 

                    if vdi_info[vdi][VDI_TYPE_TAG] != \ 

                        self.storageVDIs[vdi_info[vdi][UUID_TAG]]: 

                        # storage type takes authority 

                        update_map[METADATA_UPDATE_OBJECT_TYPE_TAG] \ 

                            = METADATA_OBJECT_TYPE_VDI 

                        update_map[UUID_TAG] = vdi_info[vdi][UUID_TAG] 

                        update_map[VDI_TYPE_TAG] = \ 

                            self.storageVDIs[vdi_info[vdi][UUID_TAG]] 

                        LVMMetadataHandler(self.mdpath)\ 

                            .updateMetadata(update_map) 

                    else: 

                        # This should never happen 

                        pass 

 

        except Exception, e: 

            raise xs_errors.XenError('MetadataError', \ 

                opterr='Error synching SR Metadata and storage: %s' % str(e)) 

 

    def syncMetadataAndXapi(self): 

        try: 

            # get metadata 

            (sr_info, vdi_info) = \ 

                LVMMetadataHandler(self.mdpath, False).getMetadata() 

 

            # First synch SR parameters 

            self.update(self.uuid) 

 

            # Now update the VDI information in the metadata if required 

            for vdi_offset in vdi_info.keys(): 

                try: 

                    vdi_ref = \ 

                        self.session.xenapi.VDI.get_by_uuid(\ 

                                        vdi_info[vdi_offset][UUID_TAG]) 

                except: 

                    # may be the VDI is not in XAPI yet dont bother 

                    continue 

 

                new_name_label = util.to_plain_string\ 

                    (self.session.xenapi.VDI.get_name_label(vdi_ref)) 

                new_name_description = util.to_plain_string\ 

                    (self.session.xenapi.VDI.get_name_description(vdi_ref)) 

 

                if vdi_info[vdi_offset][NAME_LABEL_TAG] != new_name_label or \ 

                    vdi_info[vdi_offset][NAME_DESCRIPTION_TAG] != \ 

                    new_name_description: 

                    update_map = {} 

                    update_map[METADATA_UPDATE_OBJECT_TYPE_TAG] = \ 

                        METADATA_OBJECT_TYPE_VDI 

                    update_map[UUID_TAG] = vdi_info[vdi_offset][UUID_TAG] 

                    update_map[NAME_LABEL_TAG] = new_name_label 

                    update_map[NAME_DESCRIPTION_TAG] = new_name_description 

                    LVMMetadataHandler(self.mdpath)\ 

                        .updateMetadata(update_map) 

        except Exception, e: 

            raise xs_errors.XenError('MetadataError', \ 

                opterr='Error synching SR Metadata and XAPI: %s' % str(e)) 

 

    def _checkMetadataVolume(self): 

        util.SMlog("Entering _checkMetadataVolume") 

        self.mdexists = self.lvmCache.checkLV(self.MDVOLUME_NAME) 

        if self.isMaster: 

            if self.mdexists and self.cmd == "sr_attach": 

                try: 

                    # activate the management volume 

                    # will be deactivated at detach time 

                    self.lvmCache.activateNoRefcount(self.MDVOLUME_NAME) 

                    self._synchSmConfigWithMetaData() 

                    if requiresUpgrade(self.mdpath): 

                        util.SMlog("This SR requires metadata upgrade.") 

                        self.updateSRMetadata( \ 

                            self.session.xenapi.SR.get_sm_config(self.sr_ref)\ 

                                ['allocation'] 

                        ) 

                    else: 

                        util.SMlog("SR metadata upgrade not required.") 

                        util.SMlog("Sync SR metadata and the state on the storage.") 

                        self.syncMetadataAndStorage() 

                        self.syncMetadataAndXapi() 

                except Exception, e: 

                    util.SMlog("Exception in _checkMetadataVolume, " \ 

                               "Error: %s." % str(e)) 

            elif not self.mdexists and not self.legacyMode: 

                self._introduceMetaDataVolume() 

 

        if self.mdexists: 

            self.legacyMode = False 

 

    def _synchSmConfigWithMetaData(self): 

        util.SMlog("Synching sm-config with metadata volume") 

 

        try: 

            # get SR info from metadata 

            sr_info = {} 

            map = {} 

            try: 

                # First try old metadata format 

                # CHECKME: this can be removed once we stop supporting upgrade 

                # from pre-6.0 pools 

                xml = retrieveXMLfromFile(self.mdpath) 

                sr_info = _parseXML(xml) 

            except Exception, e: 

                # That dint work, try new format valid 6.0 onwards 

                util.SMlog("Could not read SR info from metadata using old " \ 

                           "format, trying new format. Error: %s" % str(e)) 

                sr_info = LVMMetadataHandler(self.mdpath,False).getMetadata()[0] 

 

            if sr_info == {}: 

                raise Exception("Failed to get SR information from metadata.") 

 

            if sr_info.has_key("allocation"): 

                self.provision = sr_info.get("allocation") 

                map['allocation'] = sr_info.get("allocation") 

            else: 

                raise Exception("Allocation key not found in SR metadata. " \ 

                                "SR info found: %s" % sr_info) 

 

        except Exception, e: 

            raise xs_errors.XenError('MetadataError', \ 

                         opterr='Error reading SR params from ' \ 

                         'metadata Volume: %s' % str(e)) 

        try: 

            map[self.FLAG_USE_VHD] = 'true' 

            self.session.xenapi.SR.set_sm_config(self.sr_ref, map) 

        except: 

            raise xs_errors.XenError('MetadataError', \ 

                         opterr='Error updating sm_config key') 

 

    def _introduceMetaDataVolume(self): 

        util.SMlog("Creating Metadata volume") 

        try: 

            map = {} 

            self.lvmCache.create(self.MDVOLUME_NAME, 4*1024*1024) 

 

            # activate the management volume, will be deactivated at detach time 

            self.lvmCache.activateNoRefcount(self.MDVOLUME_NAME) 

 

            name_label = util.to_plain_string(\ 

                            self.session.xenapi.SR.get_name_label(self.sr_ref)) 

            name_description = util.to_plain_string(\ 

                    self.session.xenapi.SR.get_name_description(self.sr_ref)) 

            map[self.FLAG_USE_VHD] = "true" 

            map['allocation'] = self.provision 

            self.session.xenapi.SR.set_sm_config(self.sr_ref, map) 

 

            # Add the SR metadata 

            self.updateSRMetadata(self.provision) 

        except Exception, e: 

            raise xs_errors.XenError('MetadataError', \ 

                        opterr='Error introducing Metadata Volume: %s' % str(e)) 

 

    def _removeMetadataVolume(self): 

        if self.mdexists: 

            try: 

                self.lvmCache.remove(self.MDVOLUME_NAME) 

            except: 

                raise xs_errors.XenError('MetadataError', \ 

                             opterr='Failed to delete MGT Volume') 

 

 

    def _refresh_size(self): 

        """ 

        Refreshs the size of the backing device. 

        Return true if all paths/devices agree on the same size. 

        """ 

        if hasattr(self, 'SCSIid'): 

            # LVHDoHBASR, LVHDoISCSISR 

            return scsiutil.refresh_lun_size_by_SCSIid(getattr(self, 'SCSIid')) 

        else: 

            # LVHDSR 

            devices = self.root.split(',') 

            scsiutil.refreshdev(devices) 

            return True 

 

 

    def _expand_size(self): 

        """ 

        Expands the size of the SR by growing into additional availiable 

        space, if extra space is availiable on the backing device. 

        Needs to be called after a successful call of _refresh_size. 

        """ 

        currentvgsize = lvutil._getVGstats(self.vgname)['physical_size'] 

        # We are comparing PV- with VG-sizes that are aligned. Need a threshold 

        resizethreshold = 100*1024*1024 # 100MB 

        devices = self.root.split(',') 

        totaldevicesize = 0 

        for device in devices: 

            totaldevicesize = totaldevicesize + scsiutil.getsize(device) 

        if totaldevicesize >= (currentvgsize + resizethreshold): 

            try: 

                if hasattr(self, 'SCSIid'): 

                    # LVHDoHBASR, LVHDoISCSISR might have slaves 

                    scsiutil.refresh_lun_size_by_SCSIid_on_slaves(self.session, 

                                                       getattr(self, 'SCSIid')) 

                util.SMlog("LVHDSR._expand_size for %s will resize the pv." 

                           % self.uuid) 

                for device in devices: 

                    lvutil.resizePV(device) 

            except: 

                util.logException("LVHDSR._expand_size for %s failed to resize" 

                                  " the PV" % self.uuid) 

 

    @deviceCheck 

    def create(self, uuid, size): 

        util.SMlog("LVHDSR.create for %s" % self.uuid) 

        if not self.isMaster: 

            util.SMlog('sr_create blocked for non-master') 

            raise xs_errors.XenError('LVMMaster') 

 

        if lvutil._checkVG(self.vgname): 

            raise xs_errors.XenError('SRExists') 

 

        # Check none of the devices already in use by other PBDs 

        if util.test_hostPBD_devs(self.session, uuid, self.root): 

            raise xs_errors.XenError('SRInUse') 

 

        # Check serial number entry in SR records 

        for dev in self.root.split(','): 

            if util.test_scsiserial(self.session, dev): 

                raise xs_errors.XenError('SRInUse') 

 

        lvutil.createVG(self.root, self.vgname) 

 

        #Update serial number string 

        scsiutil.add_serial_record(self.session, self.sr_ref, \ 

                scsiutil.devlist_to_serialstring(self.root.split(','))) 

 

        # since this is an SR.create turn off legacy mode 

        self.session.xenapi.SR.add_to_sm_config(self.sr_ref, \ 

                                                self.FLAG_USE_VHD, 'true') 

 

    def delete(self, uuid): 

        util.SMlog("LVHDSR.delete for %s" % self.uuid) 

        if not self.isMaster: 

            raise xs_errors.XenError('LVMMaster') 

        cleanup.gc_force(self.session, self.uuid) 

 

        success = True 

        for fileName in \ 

            filter(lambda x: util.extractSRFromDevMapper(x) == self.uuid, \ 

                glob.glob(DEV_MAPPER_ROOT + '*')): 

            if util.doesFileHaveOpenHandles(fileName): 

                util.SMlog("LVHDSR.delete: The dev mapper entry %s has open " \ 

                           "handles" % fileName) 

                success = False 

                continue 

 

            # Now attempt to remove the dev mapper entry 

            if not lvutil.removeDevMapperEntry(fileName, False): 

                success = False 

                continue 

 

            try: 

                lvname = os.path.basename(fileName.replace('-','/').\ 

                                          replace('//', '-')) 

                lpath = os.path.join(self.path, lvname) 

                os.unlink(lpath) 

            except OSError, e: 

                if e.errno != errno.ENOENT: 

                    util.SMlog("LVHDSR.delete: failed to remove the symlink for " \ 

                               "file %s. Error: %s" % (fileName, str(e))) 

                    success = False 

 

        if success: 

            try: 

                if util.pathexists(self.path): 

                    os.rmdir(self.path) 

            except Exception, e: 

                util.SMlog("LVHDSR.delete: failed to remove the symlink " \ 

                           "directory %s. Error: %s" % (self.path, str(e))) 

                success = False 

 

        self._removeMetadataVolume() 

        self.lvmCache.refresh() 

        if len(lvhdutil.getLVInfo(self.lvmCache)) > 0: 

            raise xs_errors.XenError('SRNotEmpty') 

 

        if not success: 

            raise Exception("LVHDSR delete failed, please refer to the log " \ 

                            "for details.") 

 

        lvutil.removeVG(self.root, self.vgname) 

        self._cleanup() 

 

    def attach(self, uuid): 

        util.SMlog("LVHDSR.attach for %s" % self.uuid) 

 

        self._cleanup(True) # in case of host crashes, if detach wasn't called 

 

        if not util.match_uuid(self.uuid) or not lvutil._checkVG(self.vgname): 

            raise xs_errors.XenError('SRUnavailable', \ 

                    opterr='no such volume group: %s' % self.vgname) 

 

        # Refresh the metadata status 

        self._checkMetadataVolume() 

 

        refreshsizeok = self._refresh_size() 

 

        if self.isMaster: 

            if refreshsizeok: 

                self._expand_size() 

            #Update SCSIid string 

            util.SMlog("Calling devlist_to_serial") 

            scsiutil.add_serial_record(self.session, self.sr_ref, \ 

                    scsiutil.devlist_to_serialstring(self.root.split(','))) 

 

        # Test Legacy Mode Flag and update if VHD volumes exist 

        if self.isMaster and self.legacyMode: 

            vdiInfo = lvhdutil.getVDIInfo(self.lvmCache) 

            for uuid, info in vdiInfo.iteritems(): 

                if info.vdiType == vhdutil.VDI_TYPE_VHD: 

                    self.legacyMode = False 

                    map = self.session.xenapi.SR.get_sm_config(self.sr_ref) 

                    self._introduceMetaDataVolume() 

                    break 

 

        # Set the block scheduler 

        for dev in self.root.split(','): self.block_setscheduler(dev) 

 

    def detach(self, uuid): 

        util.SMlog("LVHDSR.detach for %s" % self.uuid) 

        cleanup.abort(self.uuid) 

 

        # Do a best effort cleanup of the dev mapper entries 

        # go through all devmapper entries for this VG 

        success = True 

        for fileName in \ 

            filter(lambda x: util.extractSRFromDevMapper(x) == self.uuid, \ 

                glob.glob(DEV_MAPPER_ROOT + '*')): 

            #   check if any file has open handles 

            if util.doesFileHaveOpenHandles(fileName): 

                #   if yes, log this and signal failure 

                util.SMlog("LVHDSR.detach: The dev mapper entry %s has open " \ 

                           "handles" % fileName) 

                success = False 

                continue 

 

            # Now attempt to remove the dev mapper entry 

            if not lvutil.removeDevMapperEntry(fileName, False): 

                success = False 

                continue 

 

            # also remove the symlinks from /dev/VG-XenStorage-SRUUID/* 

            try: 

                lvname = os.path.basename(fileName.replace('-','/').\ 

                                          replace('//', '-')) 

                lvname = os.path.join(self.path, lvname) 

                util.force_unlink(lvname) 

            except Exception, e: 

                util.SMlog("LVHDSR.detach: failed to remove the symlink for " \ 

                           "file %s. Error: %s" % (fileName, str(e))) 

                success = False 

 

        # now remove the directory where the symlinks are 

        # this should pass as the directory should be empty by now 

        if success: 

            try: 

                if util.pathexists(self.path): 

                    os.rmdir(self.path) 

            except Exception, e: 

                util.SMlog("LVHDSR.detach: failed to remove the symlink " \ 

                           "directory %s. Error: %s" % (self.path, str(e))) 

                success = False 

 

        if not success: 

            raise Exception("SR detach failed, please refer to the log " \ 

                            "for details.") 

 

        # Don't delete lock files on the master as it will break the locking  

        # between SM and any GC thread that survives through SR.detach.   

        # However, we should still delete lock files on slaves as it is the  

        # only place to do so. 

        self._cleanup(self.isMaster) 

 

    def forget_vdi(self, uuid): 

        if not self.legacyMode: 

            LVMMetadataHandler(self.mdpath).deleteVdiFromMetadata(uuid) 

        super(LVHDSR, self).forget_vdi(uuid) 

 

    def scan(self, uuid): 

        try: 

            lvname = '' 

            activated = True 

            util.SMlog("LVHDSR.scan for %s" % self.uuid) 

            if not self.isMaster: 

                util.SMlog('sr_scan blocked for non-master') 

                raise xs_errors.XenError('LVMMaster') 

 

            if self._refresh_size(): 

                self._expand_size() 

            self.lvmCache.refresh() 

            cbt_vdis = self.lvmCache.getTagged(CBTLOG_TAG) 

            self._loadvdis() 

            stats = lvutil._getVGstats(self.vgname) 

            self.physical_size = stats['physical_size'] 

            self.physical_utilisation = stats['physical_utilisation'] 

 

            # Now check if there are any VDIs in the metadata, which are not in  

            # XAPI 

            if self.mdexists: 

                vdiToSnaps = {} 

                # get VDIs from XAPI 

                vdis = self.session.xenapi.SR.get_VDIs(self.sr_ref) 

                vdi_uuids = set([]) 

                for vdi in vdis: 

                    vdi_uuids.add(self.session.xenapi.VDI.get_uuid(vdi)) 

 

                Dict = LVMMetadataHandler(self.mdpath, False).getMetadata()[1] 

 

                for vdi in Dict.keys(): 

                    vdi_uuid = Dict[vdi][UUID_TAG] 

                    if bool(int(Dict[vdi][IS_A_SNAPSHOT_TAG])): 

                        if vdiToSnaps.has_key(Dict[vdi][SNAPSHOT_OF_TAG]): 

                            vdiToSnaps[Dict[vdi][SNAPSHOT_OF_TAG]].append(vdi_uuid) 

                        else: 

                            vdiToSnaps[Dict[vdi][SNAPSHOT_OF_TAG]] = [vdi_uuid] 

 

                    if vdi_uuid not in vdi_uuids: 

                        util.SMlog("Introduce VDI %s as it is present in " \ 

                                   "metadata and not in XAPI." % vdi_uuid) 

                        sm_config = {} 

                        sm_config['vdi_type'] = Dict[vdi][VDI_TYPE_TAG] 

                        lvname = "%s%s" % \ 

                            (lvhdutil.LV_PREFIX[sm_config['vdi_type']],vdi_uuid) 

                        self.lvmCache.activateNoRefcount(lvname) 

                        activated = True 

                        lvPath = os.path.join(self.path, lvname) 

 

                        if Dict[vdi][VDI_TYPE_TAG] == vhdutil.VDI_TYPE_RAW: 

                            size = self.lvmCache.getSize( \ 

                                lvhdutil.LV_PREFIX[vhdutil.VDI_TYPE_RAW] + \ 

                                    vdi_uuid) 

                            utilisation = \ 

                                        util.roundup(lvutil.LVM_SIZE_INCREMENT, 

                                                       long(size)) 

                        else: 

                            parent = \ 

                                vhdutil._getVHDParentNoCheck(lvPath) 

 

                            if parent != None: 

                                sm_config['vhd-parent'] = parent[len( \ 

                                    lvhdutil.LV_PREFIX[vhdutil.VDI_TYPE_VHD]):] 

                            size = vhdutil.getSizeVirt(lvPath) 

                            if self.provision == "thin": 

                                utilisation = \ 

                                    util.roundup(lvutil.LVM_SIZE_INCREMENT, 

                                      vhdutil.calcOverheadEmpty(lvhdutil.MSIZE)) 

                            else: 

                                utilisation = lvhdutil.calcSizeVHDLV(long(size)) 

 

                        vdi_ref = self.session.xenapi.VDI.db_introduce( 

                                        vdi_uuid, 

                                        Dict[vdi][NAME_LABEL_TAG], 

                                        Dict[vdi][NAME_DESCRIPTION_TAG], 

                                        self.sr_ref, 

                                        Dict[vdi][TYPE_TAG], 

                                        False, 

                                        bool(int(Dict[vdi][READ_ONLY_TAG])), 

                                        {}, 

                                        vdi_uuid, 

                                        {}, 

                                        sm_config) 

 

                        self.session.xenapi.VDI.set_managed(vdi_ref, 

                                                    bool(int(Dict[vdi][MANAGED_TAG]))) 

                        self.session.xenapi.VDI.set_virtual_size(vdi_ref, 

                                                                 str(size)) 

                        self.session.xenapi.VDI.set_physical_utilisation( \ 

                            vdi_ref, str(utilisation)) 

                        self.session.xenapi.VDI.set_is_a_snapshot( \ 

                            vdi_ref, bool(int(Dict[vdi][IS_A_SNAPSHOT_TAG]))) 

                        if bool(int(Dict[vdi][IS_A_SNAPSHOT_TAG])): 

                            self.session.xenapi.VDI.set_snapshot_time( \ 

                                vdi_ref, DateTime(Dict[vdi][SNAPSHOT_TIME_TAG])) 

                        if Dict[vdi][TYPE_TAG] == 'metadata': 

                            self.session.xenapi.VDI.set_metadata_of_pool( \ 

                                vdi_ref, Dict[vdi][METADATA_OF_POOL_TAG]) 

 

                    # Update CBT status of disks either just added 

                    # or already in XAPI 

                    cbt_logname = "%s.%s" % (vdi_uuid, CBTLOG_TAG) 

                    if cbt_logname in cbt_vdis: 

                        vdi_ref = self.session.xenapi.VDI.get_by_uuid(vdi_uuid) 

                        self.session.xenapi.VDI.set_cbt_enabled(vdi_ref, True) 

                        # For existing VDIs, update local state too 

                        # Scan in base class SR updates existing VDIs  

                        # again based on local states 

                        if self.vdis.has_key(vdi_uuid): 

                            self.vdis[vdi_uuid].cbt_enabled = True 

                        cbt_vdis.remove(cbt_logname) 

 

                # Now set the snapshot statuses correctly in XAPI 

                for srcvdi in vdiToSnaps.keys(): 

                    try: 

                        srcref = self.session.xenapi.VDI.get_by_uuid(srcvdi) 

                    except: 

                        # the source VDI no longer exists, continue 

                        continue 

 

                    for snapvdi in vdiToSnaps[srcvdi]: 

                        try: 

                            # this might fail in cases where its already set 

                            snapref = \ 

                                self.session.xenapi.VDI.get_by_uuid(snapvdi) 

                            self.session.xenapi.VDI.set_snapshot_of(snapref, srcref) 

                        except Exception, e: 

                            util.SMlog("Setting snapshot failed. "\ 

                                       "Error: %s" % str(e)) 

 

            if cbt_vdis: 

                # If we have items remaining in this list,  

                # they are cbt_metadata VDI that XAPI doesn't know about 

                # Add them to self.vdis and they'll get added to the DB 

                for cbt_vdi in cbt_vdis: 

                    cbt_uuid = cbt_vdi.split(".")[0] 

                    new_vdi = self.vdi(cbt_uuid) 

                    new_vdi.ty = "cbt_metadata" 

                    new_vdi.cbt_enabled = True 

                    self.vdis[cbt_uuid] = new_vdi 

 

            ret = super(LVHDSR, self).scan(uuid) 

            self._kickGC() 

            return ret 

 

        finally: 

            if lvname != '' and activated: 

                self.lvmCache.deactivateNoRefcount(lvname) 

 

    def update(self, uuid): 

        if not lvutil._checkVG(self.vgname): 

            return 

        self._updateStats(uuid, 0) 

 

        if self.legacyMode: 

            return 

 

        # synch name_label in metadata with XAPI 

        update_map = {} 

        update_map = {METADATA_UPDATE_OBJECT_TYPE_TAG: \ 

                        METADATA_OBJECT_TYPE_SR, 

                        NAME_LABEL_TAG: util.to_plain_string( \ 

                            self.session.xenapi.SR.get_name_label(self.sr_ref)), 

                        NAME_DESCRIPTION_TAG: util.to_plain_string( \ 

                        self.session.xenapi.SR.get_name_description(self.sr_ref)) 

                        } 

        LVMMetadataHandler(self.mdpath).updateMetadata(update_map) 

 

    def _updateStats(self, uuid, virtAllocDelta): 

        valloc = int(self.session.xenapi.SR.get_virtual_allocation(self.sr_ref)) 

        self.virtual_allocation = valloc + virtAllocDelta 

        util.SMlog("Setting virtual_allocation of SR %s to %d" % 

                   (uuid, self.virtual_allocation)) 

        stats = lvutil._getVGstats(self.vgname) 

        self.physical_size = stats['physical_size'] 

        self.physical_utilisation = stats['physical_utilisation'] 

        self._db_update() 

 

    @deviceCheck 

    def probe(self): 

        return lvutil.srlist_toxml( 

                lvutil.scan_srlist(lvhdutil.VG_PREFIX, self.root), 

                lvhdutil.VG_PREFIX, 

                (self.srcmd.params['sr_sm_config'].has_key('metadata') and \ 

                 self.srcmd.params['sr_sm_config']['metadata'] == 'true')) 

 

    def vdi(self, uuid): 

        return LVHDVDI(self, uuid) 

 

    def _loadvdis(self): 

        self.virtual_allocation = 0 

        self.vdiInfo = lvhdutil.getVDIInfo(self.lvmCache) 

        self.allVDIs = {} 

 

        for uuid, info in self.vdiInfo.iteritems(): 

871            if uuid.startswith(cleanup.SR.TMP_RENAME_PREFIX): 

                continue 

873            if info.scanError: 

                raise xs_errors.XenError('VDIUnavailable', \ 

                        opterr='Error scanning VDI %s' % uuid) 

            self.vdis[uuid] = self.allVDIs[uuid] = self.vdi(uuid) 

869            if not self.vdis[uuid].hidden: 

                self.virtual_allocation += self.vdis[uuid].utilisation 

 

        for uuid, vdi in self.vdis.iteritems(): 

881            if vdi.parent: 

                if self.vdis.has_key(vdi.parent): 

                    self.vdis[vdi.parent].read_only = True 

                if geneology.has_key(vdi.parent): 

                    geneology[vdi.parent].append(uuid) 

                else: 

                    geneology[vdi.parent] = [uuid] 

 

        # Now remove all hidden leaf nodes to avoid introducing records that 

        # will be GC'ed 

        for uuid in self.vdis.keys(): 

892            if not geneology.has_key(uuid) and self.vdis[uuid].hidden: 

                util.SMlog("Scan found hidden leaf (%s), ignoring" % uuid) 

                del self.vdis[uuid] 

 

    def _ensureSpaceAvailable(self, amount_needed): 

        space_available = lvutil._getVGstats(self.vgname)['freespace'] 

        if (space_available < amount_needed): 

            util.SMlog("Not enough space! free space: %d, need: %d" % \ 

                    (space_available, amount_needed)) 

            raise xs_errors.XenError('SRNoSpace') 

 

    def _handleInterruptedCloneOps(self): 

        entries = self.journaler.getAll(LVHDVDI.JRN_CLONE) 

        for uuid, val in entries.iteritems(): 

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

            self._handleInterruptedCloneOp(uuid, val) 

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

            self.journaler.remove(LVHDVDI.JRN_CLONE, uuid) 

 

    def _handleInterruptedCoalesceLeaf(self): 

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

        if len(entries) > 0: 

            util.SMlog("*** INTERRUPTED COALESCE-LEAF OP DETECTED ***") 

            cleanup.gc_force(self.session, self.uuid) 

            self.lvmCache.refresh() 

 

    def _handleInterruptedCloneOp(self, origUuid, jval, forceUndo = False): 

        """Either roll back or finalize the interrupted snapshot/clone 

        operation. Rolling back is unsafe if the leaf VHDs have already been 

        in use and written to. However, it is always safe to roll back while 

        we're still in the context of the failed snapshot operation since the 

        VBD is paused for the duration of the operation""" 

        util.SMlog("*** INTERRUPTED CLONE OP: for %s (%s)" % (origUuid, jval)) 

        lvs = lvhdutil.getLVInfo(self.lvmCache) 

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

 

        # is there a "base copy" VDI? 

        if not lvs.get(baseUuid): 

            # no base copy: make sure the original is there 

            if lvs.get(origUuid): 

                util.SMlog("*** INTERRUPTED CLONE OP: nothing to do") 

                return 

            raise util.SMException("base copy %s not present, "\ 

                    "but no original %s found" % (baseUuid, origUuid)) 

 

        if forceUndo: 

            util.SMlog("Explicit revert") 

            self._undoCloneOp(lvs, origUuid, baseUuid, clonUuid) 

            return 

 

        if not lvs.get(origUuid) or (clonUuid and not lvs.get(clonUuid)): 

            util.SMlog("One or both leaves missing => revert") 

            self._undoCloneOp(lvs, origUuid, baseUuid, clonUuid) 

            return 

 

        vdis = lvhdutil.getVDIInfo(self.lvmCache) 

        if vdis[origUuid].scanError or (clonUuid and vdis[clonUuid].scanError): 

            util.SMlog("One or both leaves invalid => revert") 

            self._undoCloneOp(lvs, origUuid, baseUuid, clonUuid) 

            return 

 

        orig = vdis[origUuid] 

        base = vdis[baseUuid] 

        self.lvActivator.activate(baseUuid, base.lvName, False) 

        self.lvActivator.activate(origUuid, orig.lvName, False) 

        if orig.parentUuid != baseUuid: 

            parent = vdis[orig.parentUuid] 

            self.lvActivator.activate(parent.uuid, parent.lvName, False) 

        origPath = os.path.join(self.path, orig.lvName) 

        if not vhdutil.check(origPath): 

            util.SMlog("Orig VHD invalid => revert") 

            self._undoCloneOp(lvs, origUuid, baseUuid, clonUuid) 

            return 

 

        if clonUuid: 

            clon = vdis[clonUuid] 

            clonPath = os.path.join(self.path, clon.lvName) 

            self.lvActivator.activate(clonUuid, clon.lvName, False) 

            if not vhdutil.check(clonPath): 

                util.SMlog("Clon VHD invalid => revert") 

                self._undoCloneOp(lvs, origUuid, baseUuid, clonUuid) 

                return 

 

        util.SMlog("Snapshot appears valid, will not roll back") 

        self._completeCloneOp(vdis, origUuid, baseUuid, clonUuid) 

 

    def _undoCloneOp(self, lvs, origUuid, baseUuid, clonUuid): 

        base = lvs[baseUuid] 

        basePath = os.path.join(self.path, base.name) 

 

        # make the parent RW 

        if base.readonly: 

            self.lvmCache.setReadonly(base.name, False) 

 

        ns = lvhdutil.NS_PREFIX_LVM + self.uuid 

        origRefcountBinary = RefCounter.check(origUuid, ns)[1] 

        origRefcountNormal = 0 

 

        # un-hide the parent 

        if base.vdiType == vhdutil.VDI_TYPE_VHD: 

            self.lvActivator.activate(baseUuid, base.name, False) 

            origRefcountNormal = 1 

            vhdInfo = vhdutil.getVHDInfo(basePath, lvhdutil.extractUuid, False) 

        if base.vdiType == vhdutil.VDI_TYPE_VHD and vhdInfo.hidden: 

            vhdutil.setHidden(basePath, False) 

        elif base.vdiType == vhdutil.VDI_TYPE_RAW and base.hidden: 

            self.lvmCache.setHidden(base.name, False) 

 

        # remove the child nodes 

        if clonUuid and lvs.get(clonUuid): 

            if lvs[clonUuid].vdiType != vhdutil.VDI_TYPE_VHD: 

                raise util.SMException("clone %s not VHD" % clonUuid) 

            self.lvmCache.remove(lvs[clonUuid].name) 

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

                self.lvActivator.remove(clonUuid, False) 

        if lvs.get(origUuid): 

            self.lvmCache.remove(lvs[origUuid].name) 

 

        # inflate the parent to fully-allocated size 

        if base.vdiType == vhdutil.VDI_TYPE_VHD: 

            fullSize = lvhdutil.calcSizeVHDLV(vhdInfo.sizeVirt) 

            lvhdutil.inflate(self.journaler, self.uuid, baseUuid, fullSize) 

 

        # rename back 

        origLV = lvhdutil.LV_PREFIX[base.vdiType] + origUuid 

        self.lvmCache.rename(base.name, origLV) 

        RefCounter.reset(baseUuid, ns) 

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

            self.lvActivator.replace(baseUuid, origUuid, origLV, False) 

        RefCounter.set(origUuid, origRefcountNormal, origRefcountBinary, ns) 

 

        # At this stage, tapdisk and SM vdi will be in paused state. Remove 

        # flag to facilitate vm deactivate 

        origVdiRef = self.session.xenapi.VDI.get_by_uuid(origUuid) 

        self.session.xenapi.VDI.remove_from_sm_config(origVdiRef, 'paused') 

 

        # update LVM metadata on slaves  

        slaves = util.get_slaves_attached_on(self.session, [origUuid]) 

        lvhdutil.lvRefreshOnSlaves(self.session, self.uuid, self.vgname, 

                origLV, origUuid, slaves) 

 

        util.SMlog("*** INTERRUPTED CLONE OP: rollback success") 

 

    def _completeCloneOp(self, vdis, origUuid, baseUuid, clonUuid): 

        """Finalize the interrupted snapshot/clone operation. This must not be 

        called from the live snapshot op context because we attempt to pause/ 

        unpause the VBD here (the VBD is already paused during snapshot, so it 

        would cause a deadlock)""" 

        base = vdis[baseUuid] 

        clon = None 

        if clonUuid: 

            clon = vdis[clonUuid] 

 

        cleanup.abort(self.uuid) 

 

        # make sure the parent is hidden and read-only 

        if not base.hidden: 

            if base.vdiType == vhdutil.VDI_TYPE_RAW: 

                self.lvmCache.setHidden(base.lvName) 

            else: 

                basePath = os.path.join(self.path, base.lvName) 

                vhdutil.setHidden(basePath) 

        if not base.lvReadonly: 

            self.lvmCache.setReadonly(base.lvName, True) 

 

        # NB: since this snapshot-preserving call is only invoked outside the  

        # snapshot op context, we assume the LVM metadata on the involved slave  

        # has by now been refreshed and do not attempt to do it here 

 

        # Update the original record 

        try: 

            vdi_ref = self.session.xenapi.VDI.get_by_uuid(origUuid) 

            sm_config = self.session.xenapi.VDI.get_sm_config(vdi_ref) 

            type = self.session.xenapi.VDI.get_type(vdi_ref) 

            sm_config["vdi_type"] = vhdutil.VDI_TYPE_VHD 

            sm_config['vhd-parent'] = baseUuid 

            self.session.xenapi.VDI.set_sm_config(vdi_ref, sm_config) 

        except XenAPI.Failure: 

            util.SMlog("ERROR updating the orig record") 

 

        # introduce the new VDI records 

        if clonUuid: 

            try: 

                clon_vdi = VDI.VDI(self, clonUuid) 

                clon_vdi.read_only = False 

                clon_vdi.location = clonUuid 

                clon_vdi.utilisation = clon.sizeLV 

                clon_vdi.sm_config = { 

                        "vdi_type": vhdutil.VDI_TYPE_VHD, 

                        "vhd-parent": baseUuid } 

 

                if not self.legacyMode: 

                    LVMMetadataHandler(self.mdpath).\ 

                                       ensureSpaceIsAvailableForVdis(1) 

 

                clon_vdi_ref = clon_vdi._db_introduce() 

                util.SMlog("introduced clon VDI: %s (%s)" % \ 

                        (clon_vdi_ref, clonUuid)) 

 

                vdi_info = { UUID_TAG: clonUuid, 

                                NAME_LABEL_TAG: clon_vdi.label, 

                                NAME_DESCRIPTION_TAG: clon_vdi.description, 

                                IS_A_SNAPSHOT_TAG: 0, 

                                SNAPSHOT_OF_TAG: '', 

                                SNAPSHOT_TIME_TAG: '', 

                                TYPE_TAG: type, 

                                VDI_TYPE_TAG: clon_vdi.sm_config['vdi_type'], 

                                READ_ONLY_TAG: int(clon_vdi.read_only), 

                                MANAGED_TAG: int(clon_vdi.managed), 

                                METADATA_OF_POOL_TAG: '' 

                } 

 

                if not self.legacyMode: 

                    LVMMetadataHandler(self.mdpath).addVdi(vdi_info) 

 

            except XenAPI.Failure: 

                util.SMlog("ERROR introducing the clon record") 

 

        try: 

            base_vdi = VDI.VDI(self, baseUuid) # readonly parent 

            base_vdi.label = "base copy" 

            base_vdi.read_only = True 

            base_vdi.location = baseUuid 

            base_vdi.size = base.sizeVirt 

            base_vdi.utilisation = base.sizeLV 

            base_vdi.managed = False 

            base_vdi.sm_config = { 

                    "vdi_type": vhdutil.VDI_TYPE_VHD, 

                    "vhd-parent": baseUuid } 

 

            if not self.legacyMode: 

                LVMMetadataHandler(self.mdpath).ensureSpaceIsAvailableForVdis(1) 

 

            base_vdi_ref = base_vdi._db_introduce() 

            util.SMlog("introduced base VDI: %s (%s)" % \ 

                    (base_vdi_ref, baseUuid)) 

 

            vdi_info = { UUID_TAG: baseUuid, 

                                NAME_LABEL_TAG: base_vdi.label, 

                                NAME_DESCRIPTION_TAG: base_vdi.description, 

                                IS_A_SNAPSHOT_TAG: 0, 

                                SNAPSHOT_OF_TAG: '', 

                                SNAPSHOT_TIME_TAG: '', 

                                TYPE_TAG: type, 

                                VDI_TYPE_TAG: base_vdi.sm_config['vdi_type'], 

                                READ_ONLY_TAG: int(base_vdi.read_only), 

                                MANAGED_TAG: int(base_vdi.managed), 

                                METADATA_OF_POOL_TAG: '' 

                } 

 

            if not self.legacyMode: 

                LVMMetadataHandler(self.mdpath).addVdi(vdi_info) 

        except XenAPI.Failure: 

            util.SMlog("ERROR introducing the base record") 

 

        util.SMlog("*** INTERRUPTED CLONE OP: complete") 

 

    def _undoAllJournals(self): 

        """Undo all VHD & SM interrupted journaled operations. This call must 

        be serialized with respect to all operations that create journals""" 

        # undoing interrupted inflates must be done first, since undoing VHD  

        # ops might require inflations 

        self.lock.acquire() 

        try: 

            self._undoAllInflateJournals() 

            self._undoAllVHDJournals() 

            self._handleInterruptedCloneOps() 

            self._handleInterruptedCoalesceLeaf() 

        finally: 

            self.lock.release() 

            self.cleanup() 

 

    def _undoAllInflateJournals(self): 

        entries = self.journaler.getAll(lvhdutil.JRN_INFLATE) 

1166        if len(entries) == 0: 

            return 

        self._loadvdis() 

        for uuid, val in entries.iteritems(): 

            vdi = self.vdis.get(uuid) 

1185            if vdi: 

                util.SMlog("Found inflate journal %s, deflating %s to %s" % \ 

                        (uuid, vdi.path, val)) 

1174                if vdi.readonly: 

                    self.lvmCache.setReadonly(vdi.lvname, False) 

                self.lvActivator.activate(uuid, vdi.lvname, False) 

                currSizeLV = self.lvmCache.getSize(vdi.lvname) 

                util.zeroOut(vdi.path, currSizeLV - vhdutil.VHD_FOOTER_SIZE, 

                        vhdutil.VHD_FOOTER_SIZE) 

                lvhdutil.deflate(self.lvmCache, vdi.lvname, int(val)) 

1181                if vdi.readonly: 

                    self.lvmCache.setReadonly(vdi.lvname, True) 

1183                if "true" == self.session.xenapi.SR.get_shared(self.sr_ref): 

                    lvhdutil.lvRefreshOnAllSlaves(self.session, self.uuid, 

                            self.vgname, vdi.lvname, uuid) 

            self.journaler.remove(lvhdutil.JRN_INFLATE, uuid) 

        delattr(self,"vdiInfo") 

        delattr(self,"allVDIs") 

 

    def _undoAllVHDJournals(self): 

        """check if there are VHD journals in existence and revert them""" 

        journals = lvhdutil.getAllVHDJournals(self.lvmCache) 

        if len(journals) == 0: 

            return 

        self._loadvdis() 

        for uuid, jlvName in journals: 

            vdi = self.vdis[uuid] 

            util.SMlog("Found VHD journal %s, reverting %s" % (uuid, vdi.path)) 

            self.lvActivator.activate(uuid, vdi.lvname, False) 

            self.lvmCache.activateNoRefcount(jlvName) 

            fullSize = lvhdutil.calcSizeVHDLV(vdi.size) 

            lvhdutil.inflate(self.journaler, self.uuid, vdi.uuid, fullSize) 

            try: 

                jFile = os.path.join(self.path, jlvName) 

                vhdutil.revert(vdi.path, jFile) 

            except util.CommandException: 

                util.logException("VHD journal revert") 

                vhdutil.check(vdi.path) 

                util.SMlog("VHD revert failed but VHD ok: removing journal") 

            # Attempt to reclaim unused space 

            vhdInfo = vhdutil.getVHDInfo(vdi.path, lvhdutil.extractUuid, False) 

            NewSize = lvhdutil.calcSizeVHDLV(vhdInfo.sizeVirt) 

            if NewSize < fullSize: 

                lvhdutil.deflate(self.lvmCache, vdi.lvname, int(NewSize)) 

            lvhdutil.lvRefreshOnAllSlaves(self.session, self.uuid, 

                    self.vgname, vdi.lvname, uuid) 

            self.lvmCache.remove(jlvName) 

        delattr(self,"vdiInfo") 

        delattr(self,"allVDIs") 

 

    def _updateSlavesPreClone(self, hostRefs, origOldLV): 

        masterRef = util.get_this_host_ref(self.session) 

        args = {"vgName": self.vgname, 

                "action1": "deactivateNoRefcount", 

                "lvName1": origOldLV} 

        for hostRef in hostRefs: 

            if hostRef == masterRef: 

                continue 

            util.SMlog("Deactivate VDI on %s" % hostRef) 

            rv = eval(self.session.xenapi.host.call_plugin(hostRef, self.PLUGIN_ON_SLAVE, "multi", args)) 

            util.SMlog("call-plugin returned: %s" % rv) 

            if not rv: 

                raise Exception('plugin %s failed' % self.PLUGIN_ON_SLAVE) 

 

    def _updateSlavesOnClone(self, hostRefs, origOldLV, origLV, 

            baseUuid, baseLV): 

        """We need to reactivate the original LV on each slave (note that the 

        name for the original LV might change), as well as init the refcount 

        for the base LV""" 

        args = {"vgName" : self.vgname, 

                "action1": "refresh", 

                "lvName1": origLV, 

                "action2": "activate", 

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

                "lvName2": baseLV, 

                "uuid2"  : baseUuid} 

 

        masterRef = util.get_this_host_ref(self.session) 

        for hostRef in hostRefs: 

            if hostRef == masterRef: 

                continue 

            util.SMlog("Updating %s, %s, %s on slave %s" % \ 

                    (origOldLV, origLV, baseLV, hostRef)) 

            rv = eval(self.session.xenapi.host.call_plugin( 

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

            util.SMlog("call-plugin returned: %s" % rv) 

            if not rv: 

                raise Exception('plugin %s failed' % self.PLUGIN_ON_SLAVE) 

 

    def _updateSlavesOnCBTClone(self, hostRefs, cbtlog): 

        """Reactivate and refresh CBT log file on slaves""" 

        args = {"vgName" : self.vgname, 

                "action1": "deactivateNoRefcount", 

                "lvName1": cbtlog, 

                "action2": "refresh", 

                "lvName2": cbtlog} 

 

        masterRef = util.get_this_host_ref(self.session) 

        for hostRef in hostRefs: 

            if hostRef == masterRef: 

                continue 

            util.SMlog("Updating %s on slave %s" % (cbtlog, hostRef)) 

            rv = eval(self.session.xenapi.host.call_plugin( 

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

            util.SMlog("call-plugin returned: %s" % rv) 

            if not rv: 

                raise Exception('plugin %s failed' % self.PLUGIN_ON_SLAVE) 

 

    def _updateSlavesOnRemove(self, hostRefs, baseUuid, baseLV): 

        """Tell the slave we deleted the base image""" 

        args = {"vgName" : self.vgname, 

                "action1": "cleanupLockAndRefcount", 

                "uuid1": baseUuid, 

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

 

        masterRef = util.get_this_host_ref(self.session) 

        for hostRef in hostRefs: 

            if hostRef == masterRef: 

                continue 

            util.SMlog("Cleaning locks for %s on slave %s" % (baseLV, hostRef)) 

            rv = eval(self.session.xenapi.host.call_plugin( 

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

            util.SMlog("call-plugin returned: %s" % rv) 

            if not rv: 

                raise Exception('plugin %s failed' % self.PLUGIN_ON_SLAVE) 

 

    def _cleanup(self, skipLockCleanup = False): 

        """delete stale refcounter, flag, and lock files""" 

        RefCounter.resetAll(lvhdutil.NS_PREFIX_LVM + self.uuid) 

        IPCFlag(self.uuid).clearAll() 

        if not skipLockCleanup: 

            Lock.cleanupAll(self.uuid) 

            Lock.cleanupAll(lvhdutil.NS_PREFIX_LVM + self.uuid) 

 

    def _prepareTestMode(self): 

        util.SMlog("Test mode: %s" % self.testMode) 

        if self.ENV_VAR_VHD_TEST.get(self.testMode): 

            os.environ[self.ENV_VAR_VHD_TEST[self.testMode]] = "yes" 

            util.SMlog("Setting env %s" % self.ENV_VAR_VHD_TEST[self.testMode]) 

 

    def _kickGC(self): 

        # don't bother if an instance already running (this is just an  

        # optimization to reduce the overhead of forking a new process if we  

        # don't have to, but the process will check the lock anyways) 

        lockRunning = Lock(cleanup.LOCK_TYPE_RUNNING, self.uuid) 

        if not lockRunning.acquireNoblock(): 

            if cleanup.should_preempt(self.session, self.uuid): 

                util.SMlog("Aborting currently-running coalesce of garbage VDI") 

                try: 

                    if not cleanup.abort(self.uuid, soft=True): 

                        util.SMlog("The GC has already been scheduled to " 

                                "re-start") 

                except util.CommandException, e: 

                    if e.code != errno.ETIMEDOUT: 

                        raise 

                    util.SMlog('failed to abort the GC') 

            else: 

                util.SMlog("A GC instance already running, not kicking") 

                return 

        else: 

            lockRunning.release() 

 

        util.SMlog("Kicking GC") 

        cleanup.gc(self.session, self.uuid, True) 

 

    def ensureCBTSpace(self): 

        # Ensure we have space for at least one LV 

        self._ensureSpaceAvailable(self.journaler.LV_SIZE) 

 

 

class LVHDVDI(VDI.VDI): 

 

    JRN_CLONE = "clone" # journal entry type for the clone operation 

 

    def load(self, vdi_uuid): 

        self.lock = self.sr.lock 

        self.lvActivator = self.sr.lvActivator 

        self.loaded   = False 

        self.vdi_type = vhdutil.VDI_TYPE_VHD 

1351        if self.sr.legacyMode or util.fistpoint.is_active("xenrt_default_vdi_type_legacy"): 

            self.vdi_type = vhdutil.VDI_TYPE_RAW 

        self.uuid     = vdi_uuid 

        self.location = self.uuid 

        self.exists   = True 

 

1364        if hasattr(self.sr, "vdiInfo") and self.sr.vdiInfo.get(self.uuid): 

            self._initFromVDIInfo(self.sr.vdiInfo[self.uuid]) 

1358            if self.parent: 

                self.sm_config_override['vhd-parent'] = self.parent 

            else: 

                self.sm_config_override['vhd-parent'] = None 

            return 

 

        # scan() didn't run: determine the type of the VDI manually 

        if self._determineType(): 

            return 

 

        # the VDI must be in the process of being created 

        self.exists = False 

        if self.sr.srcmd.params.has_key("vdi_sm_config") and \ 

                self.sr.srcmd.params["vdi_sm_config"].has_key("type"): 

            type = self.sr.srcmd.params["vdi_sm_config"]["type"] 

            if type == PARAM_RAW: 

                self.vdi_type = vhdutil.VDI_TYPE_RAW 

            elif type == PARAM_VHD: 

                self.vdi_type = vhdutil.VDI_TYPE_VHD 

                if self.sr.cmd == 'vdi_create' and self.sr.legacyMode: 

                    raise xs_errors.XenError('VDICreate', \ 

                        opterr='Cannot create VHD type disk in legacy mode') 

            else: 

                raise xs_errors.XenError('VDICreate', opterr='bad type') 

        self.lvname = "%s%s" % (lvhdutil.LV_PREFIX[self.vdi_type], vdi_uuid) 

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

 

    def create(self, sr_uuid, vdi_uuid, size): 

        util.SMlog("LVHDVDI.create for %s" % self.uuid) 

        if not self.sr.isMaster: 

            raise xs_errors.XenError('LVMMaster') 

        if self.exists: 

            raise xs_errors.XenError('VDIExists') 

 

        size = vhdutil.validate_and_round_vhd_size(long(size)) 

 

        util.SMlog("LVHDVDI.create: type = %s, %s (size=%s)" %\ 

                (self.vdi_type, self.path, size)) 

        lvSize = 0 

        self.sm_config = self.sr.srcmd.params["vdi_sm_config"] 

        if self.vdi_type == vhdutil.VDI_TYPE_RAW: 

            lvSize = util.roundup(lvutil.LVM_SIZE_INCREMENT, long(size)) 

        else: 

            if self.sr.provision == "thin": 

                lvSize = util.roundup(lvutil.LVM_SIZE_INCREMENT, 

                        vhdutil.calcOverheadEmpty(lvhdutil.MSIZE)) 

            elif self.sr.provision == "thick": 

                lvSize = lvhdutil.calcSizeVHDLV(long(size)) 

 

        self.sr._ensureSpaceAvailable(lvSize) 

 

        try: 

            self.sr.lvmCache.create(self.lvname, lvSize) 

            if self.vdi_type == vhdutil.VDI_TYPE_RAW: 

                self.size = self.sr.lvmCache.getSize(self.lvname) 

            else: 

               vhdutil.create(self.path, long(size), False, lvhdutil.MSIZE_MB) 

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

            self.sr.lvmCache.deactivateNoRefcount(self.lvname) 

        except util.CommandException, e: 

            util.SMlog("Unable to create VDI"); 

            self.sr.lvmCache.remove(self.lvname) 

            raise xs_errors.XenError('VDICreate', opterr='error %d' % e.code) 

 

        self.utilisation = lvSize 

        self.sm_config["vdi_type"] = self.vdi_type 

 

        if not self.sr.legacyMode: 

            LVMMetadataHandler(self.sr.mdpath).ensureSpaceIsAvailableForVdis(1) 

 

        self.ref = self._db_introduce() 

        self.sr._updateStats(self.sr.uuid, self.size) 

 

        vdi_info = { UUID_TAG: self.uuid, 

                                NAME_LABEL_TAG: util.to_plain_string(self.label), 

                                NAME_DESCRIPTION_TAG: util.to_plain_string(self.description), 

                                IS_A_SNAPSHOT_TAG: 0, 

                                SNAPSHOT_OF_TAG: '', 

                                SNAPSHOT_TIME_TAG: '', 

                                TYPE_TAG: self.ty, 

                                VDI_TYPE_TAG: self.vdi_type, 

                                READ_ONLY_TAG: int(self.read_only), 

                                MANAGED_TAG: int(self.managed), 

                                METADATA_OF_POOL_TAG: '' 

                } 

 

        if not self.sr.legacyMode: 

            LVMMetadataHandler(self.sr.mdpath).addVdi(vdi_info) 

 

        return VDI.VDI.get_params(self) 

 

    def delete(self, sr_uuid, vdi_uuid, data_only = False): 

        util.SMlog("LVHDVDI.delete for %s" % self.uuid) 

        try: 

            self._loadThis() 

        except SR.SRException, e: 

            # Catch 'VDI doesn't exist' exception 

            if e.errno == 46: 

                return super(LVHDVDI, self).delete(sr_uuid, vdi_uuid, data_only) 

            raise 

 

        vdi_ref = self.sr.srcmd.params['vdi_ref'] 

        if not self.session.xenapi.VDI.get_managed(vdi_ref): 

            raise xs_errors.XenError("VDIDelete", \ 

                          opterr="Deleting non-leaf node not permitted") 

 

        if not self.hidden: 

            self._markHidden() 

 

        if not data_only: 

            # Remove from XAPI and delete from MGT 

            self._db_forget() 

        else: 

            # If this is a data_destroy call, don't remove from XAPI db 

            # Only delete from MGT 

            if not self.sr.legacyMode: 

                LVMMetadataHandler(self.sr.mdpath).deleteVdiFromMetadata(self.uuid) 

 

        # deactivate here because it might be too late to do it in the "final"  

        # step: GC might have removed the LV by then 

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

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

 

        try: 

            self.sr.lvmCache.remove(self.lvname) 

            self.sr.lock.cleanup(vdi_uuid, lvhdutil.NS_PREFIX_LVM + sr_uuid) 

            self.sr.lock.cleanupAll(vdi_uuid) 

        except SR.SRException, e: 

            util.SMlog( 

                "Failed to remove the volume (maybe is leaf coalescing) " 

                "for %s err:%d" % (self.uuid, e.errno)) 

 

        self.sr._updateStats(self.sr.uuid, -self.size) 

        self.sr._kickGC() 

        return super(LVHDVDI, self).delete(sr_uuid, vdi_uuid, data_only) 

 

    def attach(self, sr_uuid, vdi_uuid): 

        util.SMlog("LVHDVDI.attach for %s" % self.uuid) 

        if self.sr.journaler.hasJournals(self.uuid): 

            raise xs_errors.XenError('VDIUnavailable', 

                    opterr='Interrupted operation detected on this VDI, ' 

                    'scan SR first to trigger auto-repair') 

 

        writable = ('args' not in self.sr.srcmd.params) or \ 

                (self.sr.srcmd.params['args'][0] == "true") 

        needInflate = True 

        if self.vdi_type == vhdutil.VDI_TYPE_RAW or not writable: 

            needInflate = False 

        else: 

            self._loadThis() 

            if self.utilisation >= lvhdutil.calcSizeVHDLV(self.size): 

                needInflate = False 

 

        if needInflate: 

            try: 

                self._prepareThin(True) 

            except: 

                util.logException("attach") 

                raise xs_errors.XenError('LVMProvisionAttach') 

 

        try: 

            return self._attach() 

        finally: 

            if not self.sr.lvActivator.deactivateAll(): 

                util.SMlog("Failed to deactivate LVs back (%s)" % self.uuid) 

 

 

    def detach(self, sr_uuid, vdi_uuid): 

        util.SMlog("LVHDVDI.detach for %s" % self.uuid) 

        self._loadThis() 

        already_deflated = (self.utilisation < \ 

                lvhdutil.calcSizeVHDLV(self.size)) 

        needDeflate = True 

        if self.vdi_type == vhdutil.VDI_TYPE_RAW or already_deflated: 

            needDeflate = False 

        elif self.sr.provision == "thick": 

            needDeflate = False 

            # except for snapshots, which are always deflated 

            vdi_ref = self.sr.srcmd.params['vdi_ref'] 

            snap = self.session.xenapi.VDI.get_is_a_snapshot(vdi_ref) 

            if snap: 

                needDeflate = True 

 

        if needDeflate: 

            try: 

                self._prepareThin(False) 

            except: 

                util.logException("_prepareThin") 

                raise xs_errors.XenError('VDIUnavailable', opterr='deflate') 

 

        try: 

            self._detach() 

        finally: 

            if not self.sr.lvActivator.deactivateAll(): 

                raise xs_errors.XenError("SMGeneral", opterr="deactivation") 

 

    # We only support offline resize 

    def resize(self, sr_uuid, vdi_uuid, size): 

        util.SMlog("LVHDVDI.resize for %s" % self.uuid) 

        if not self.sr.isMaster: 

            raise xs_errors.XenError('LVMMaster') 

 

        self._loadThis() 

        if self.hidden: 

            raise xs_errors.XenError('VDIUnavailable', opterr='hidden VDI') 

 

        if size < self.size: 

            util.SMlog('vdi_resize: shrinking not supported: ' + \ 

                    '(current size: %d, new size: %d)' % (self.size, size)) 

            raise xs_errors.XenError('VDISize', opterr='shrinking not allowed') 

 

        size = vhdutil.validate_and_round_vhd_size(long(size)) 

 

        if size == self.size: 

            return VDI.VDI.get_params(self) 

 

        if self.vdi_type == vhdutil.VDI_TYPE_RAW: 

            lvSizeOld = self.size 

            lvSizeNew = util.roundup(lvutil.LVM_SIZE_INCREMENT, size) 

        else: 

            lvSizeOld = self.utilisation 

            lvSizeNew = lvhdutil.calcSizeVHDLV(size) 

            if self.sr.provision == "thin": 

                # VDI is currently deflated, so keep it deflated 

                lvSizeNew = lvSizeOld 

        assert(lvSizeNew >= lvSizeOld) 

        spaceNeeded = lvSizeNew - lvSizeOld 

        self.sr._ensureSpaceAvailable(spaceNeeded) 

 

        oldSize = self.size 

        if self.vdi_type == vhdutil.VDI_TYPE_RAW: 

            self.sr.lvmCache.setSize(self.lvname, lvSizeNew) 

            self.size = self.sr.lvmCache.getSize(self.lvname) 

            self.utilisation = self.size 

        else: 

            if lvSizeNew != lvSizeOld: 

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

                        lvSizeNew) 

            vhdutil.setSizeVirtFast(self.path, size) 

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

            self.utilisation = self.sr.lvmCache.getSize(self.lvname) 

 

        vdi_ref = self.sr.srcmd.params['vdi_ref'] 

        self.session.xenapi.VDI.set_virtual_size(vdi_ref, str(self.size)) 

        self.session.xenapi.VDI.set_physical_utilisation(vdi_ref, 

                str(self.utilisation)) 

        self.sr._updateStats(self.sr.uuid, self.size - oldSize) 

        super(LVHDVDI, self).resize_cbt(self.sr.uuid, self.uuid, self.size) 

        return VDI.VDI.get_params(self) 

 

    def clone(self, sr_uuid, vdi_uuid): 

        return self._do_snapshot( 

                     sr_uuid, vdi_uuid, VDI.SNAPSHOT_DOUBLE, cloneOp=True) 

 

    def compose(self, sr_uuid, vdi1, vdi2): 

        util.SMlog("LVHDSR.compose for %s -> %s" % (vdi2, vdi1)) 

        if self.vdi_type != vhdutil.VDI_TYPE_VHD: 

            raise xs_errors.XenError('Unimplemented') 

 

        parent_uuid = vdi1 

        parent_lvname = lvhdutil.LV_PREFIX[vhdutil.VDI_TYPE_VHD] + parent_uuid 

        assert(self.sr.lvmCache.checkLV(parent_lvname)) 

        parent_path = os.path.join(self.sr.path, parent_lvname) 

 

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

        self.sr.lvActivator.activate(parent_uuid, parent_lvname, False) 

 

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

        vhdutil.setHidden(parent_path) 

        self.sr.session.xenapi.VDI.set_managed(self.sr.srcmd.params['args'][0], False) 

 

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

                True): 

            raise util.SMException("failed to refresh VDI %s" % self.uuid) 

 

        util.SMlog("Compose done") 

 

    def reset_leaf(self, sr_uuid, vdi_uuid): 

        util.SMlog("LVHDSR.reset_leaf for %s" % vdi_uuid) 

        if self.vdi_type != vhdutil.VDI_TYPE_VHD: 

            raise xs_errors.XenError('Unimplemented') 

 

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

 

        # safety check 

        if not vhdutil.hasParent(self.path): 

            raise util.SMException("ERROR: VDI %s has no parent, " + \ 

                    "will not reset contents" % self.uuid) 

 

        vhdutil.killData(self.path) 

 

    def _attach(self): 

        self._chainSetActive(True, True, True) 

        if not util.pathexists(self.path): 

            raise xs_errors.XenError('VDIUnavailable', \ 

                    opterr='Could not find: %s' % self.path) 

 

        if not hasattr(self,'xenstore_data'): 

            self.xenstore_data = {} 

 

        self.xenstore_data.update(scsiutil.update_XS_SCSIdata(self.uuid, \ 

                                                                  scsiutil.gen_synthetic_page_data(self.uuid))) 

 

        self.xenstore_data['storage-type']='lvm' 

        self.xenstore_data['vdi-type']=self.vdi_type 

 

        self.attached = True 

        self.sr.lvActivator.persist() 

        return VDI.VDI.attach(self, self.sr.uuid, self.uuid) 

 

    def _detach(self): 

        self._chainSetActive(False, True) 

        self.attached = False 

 

    def _do_snapshot(self, sr_uuid, vdi_uuid, snapType, 

                     cloneOp=False, secondary=None, cbtlog=None): 

        # If cbt enabled, save file consistency state 

        if cbtlog is not None: 

            if blktap2.VDI.tap_status(self.session, vdi_uuid): 

                consistency_state = False 

            else: 

                consistency_state = True 

            util.SMlog("Saving log consistency state of %s for vdi: %s" % 

                       (consistency_state, vdi_uuid)) 

        else: 

            consistency_state = None 

 

        pause_time = time.time() 

        if not blktap2.VDI.tap_pause(self.session, sr_uuid, vdi_uuid): 

            raise util.SMException("failed to pause VDI %s" % vdi_uuid) 

 

        snapResult = None 

        try: 

            snapResult = self._snapshot(snapType, cloneOp, cbtlog, consistency_state) 

        except Exception, e1: 

            try: 

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

                                        secondary=None) 

            except Exception, e2: 

                util.SMlog('WARNING: failed to clean up failed snapshot: ' 

                        '%s (error ignored)' % e2) 

            raise 

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

        unpause_time = time.time() 

        if (unpause_time - pause_time) > LONG_SNAPTIME: 

            util.SMlog('WARNING: snapshot paused VM for %s seconds' % 

                       (unpause_time - pause_time)) 

        return snapResult 

 

    def _snapshot(self, snapType, cloneOp = False, cbtlog = None, cbt_consistency = None): 

        util.SMlog("LVHDVDI._snapshot for %s (type %s)" % (self.uuid, snapType)) 

 

        if not self.sr.isMaster: 

            raise xs_errors.XenError('LVMMaster') 

        if self.sr.legacyMode: 

            raise xs_errors.XenError('Unimplemented', opterr='In legacy mode') 

 

        self._loadThis() 

        if self.hidden: 

            raise xs_errors.XenError('VDISnapshot', opterr='hidden VDI') 

 

        self.sm_config = self.session.xenapi.VDI.get_sm_config( \ 

                self.sr.srcmd.params['vdi_ref']) 

        if self.sm_config.has_key("type") and self.sm_config['type']=='raw': 

            if not util.fistpoint.is_active("testsm_clone_allow_raw"): 

                raise xs_errors.XenError('Unimplemented', \ 

                        opterr='Raw VDI, snapshot or clone not permitted') 

 

        # we must activate the entire VHD chain because the real parent could  

        # theoretically be anywhere in the chain if all VHDs under it are empty 

        self._chainSetActive(True, False) 

        if not util.pathexists(self.path): 

            raise xs_errors.XenError('VDIUnavailable', \ 

                    opterr='VDI unavailable: %s' % (self.path)) 

 

        if self.vdi_type == vhdutil.VDI_TYPE_VHD: 

            depth = vhdutil.getDepth(self.path) 

            if depth == -1: 

                raise xs_errors.XenError('VDIUnavailable', \ 

                        opterr='failed to get VHD depth') 

            elif depth >= vhdutil.MAX_CHAIN_SIZE: 

                raise xs_errors.XenError('SnapshotChainTooLong') 

 

        self.issnap = self.session.xenapi.VDI.get_is_a_snapshot( \ 

                                                self.sr.srcmd.params['vdi_ref']) 

 

        fullpr = lvhdutil.calcSizeVHDLV(self.size) 

        thinpr = util.roundup(lvutil.LVM_SIZE_INCREMENT, \ 

                vhdutil.calcOverheadEmpty(lvhdutil.MSIZE)) 

        lvSizeOrig = thinpr 

        lvSizeClon = thinpr 

 

        hostRefs = [] 

        if self.sr.cmd == "vdi_snapshot": 

            hostRefs = util.get_hosts_attached_on(self.session, [self.uuid]) 

            if hostRefs: 

                lvSizeOrig = fullpr 

        if self.sr.provision == "thick": 

            if not self.issnap: 

                lvSizeOrig = fullpr 

            if self.sr.cmd != "vdi_snapshot": 

                lvSizeClon = fullpr 

 

        if (snapType == VDI.SNAPSHOT_SINGLE or 

                snapType == VDI.SNAPSHOT_INTERNAL): 

            lvSizeClon = 0 

 

        # the space required must include 2 journal LVs: a clone journal and an  

        # inflate journal (for the failure handling 

        size_req = lvSizeOrig + lvSizeClon + 2 * self.sr.journaler.LV_SIZE 

        lvSizeBase = self.size 

        if self.vdi_type == vhdutil.VDI_TYPE_VHD: 

            lvSizeBase = util.roundup(lvutil.LVM_SIZE_INCREMENT, 

                    vhdutil.getSizePhys(self.path)) 

            size_req -= (self.utilisation - lvSizeBase) 

        self.sr._ensureSpaceAvailable(size_req) 

 

        if hostRefs: 

            self.sr._updateSlavesPreClone(hostRefs, self.lvname) 

 

        baseUuid = util.gen_uuid() 

        origUuid = self.uuid 

        clonUuid = "" 

        if snapType == VDI.SNAPSHOT_DOUBLE: 

            clonUuid = util.gen_uuid() 

        jval = "%s_%s" % (baseUuid, clonUuid) 

        with lvutil.LvmLockContext(): 

            # This makes multiple LVM calls so take the lock early 

            self.sr.journaler.create(self.JRN_CLONE, origUuid, jval) 

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

 

        try: 

            with lvutil.LvmLockContext(): 

                # self becomes the "base vdi" 

                origOldLV = self.lvname 

                baseLV = lvhdutil.LV_PREFIX[self.vdi_type] + baseUuid 

                self.sr.lvmCache.rename(self.lvname, baseLV) 

                self.sr.lvActivator.replace(self.uuid, baseUuid, baseLV, False) 

                RefCounter.set(baseUuid, 1, 0, lvhdutil.NS_PREFIX_LVM + self.sr.uuid) 

                self.uuid = baseUuid 

                self.lvname = baseLV 

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

                self.label = "base copy" 

                self.read_only = True 

                self.location = self.uuid 

                self.managed = False 

 

                # shrink the base copy to the minimum - we do it before creating 

                # the snapshot volumes to avoid requiring double the space 

                if self.vdi_type == vhdutil.VDI_TYPE_VHD: 

                    lvhdutil.deflate(self.sr.lvmCache, self.lvname, lvSizeBase) 

                    self.utilisation = lvSizeBase 

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

 

                snapVDI = self._createSnap(origUuid, lvSizeOrig, False) 

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

                snapVDI2 = None 

                if snapType == VDI.SNAPSHOT_DOUBLE: 

                    snapVDI2 = self._createSnap(clonUuid, lvSizeClon, True) 

                    # If we have CBT enabled on the VDI, 

                    # set CBT status for the new snapshot disk 

                    if cbtlog: 

                        snapVDI2.cbt_enabled = True 

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

 

                # note: it is important to mark the parent hidden only AFTER the 

                # new VHD children have been created, which are referencing it; 

                # otherwise we would introduce a race with GC that could reclaim 

                # the parent before we snapshot it 

                if self.vdi_type == vhdutil.VDI_TYPE_RAW: 

                    self.sr.lvmCache.setHidden(self.lvname) 

                else: 

                    vhdutil.setHidden(self.path) 

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

 

            # set the base copy to ReadOnly 

            # Do this outside the LvmLockContext to avoid deadlock 

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

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

 

            if hostRefs: 

                self.sr._updateSlavesOnClone(hostRefs, origOldLV, 

                        snapVDI.lvname, self.uuid, self.lvname) 

 

            # Update cbt files if user created snapshot (SNAPSHOT_DOUBLE) 

            if snapType == VDI.SNAPSHOT_DOUBLE and cbtlog: 

                snapVDI._cbt_snapshot(clonUuid, cbt_consistency) 

                if hostRefs: 

                    cbtlog_file = self._get_cbt_logname(snapVDI.uuid) 

                    try: 

                        self.sr._updateSlavesOnCBTClone(hostRefs, cbtlog_file) 

                    except: 

                        alert_name = "VDI_CBT_SNAPSHOT_FAILED" 

                        alert_str = ("Creating CBT snapshot for {} failed" 

                                     .format(snapVDI.uuid)) 

                        snapVDI._disable_cbt_on_error(alert_name, alert_str) 

                        pass 

 

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

            util.logException("LVHDVDI._snapshot") 

            self._failClone(origUuid, jval, str(e)) 

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

 

        with lvutil.LvmLockContext(): 

            # This makes multiple LVM calls so take the lock early 

            self.sr.journaler.remove(self.JRN_CLONE, origUuid) 

 

        return self._finishSnapshot(snapVDI, snapVDI2, hostRefs, cloneOp, snapType) 

 

 

    def _createSnap(self, snapUuid, snapSizeLV, isNew): 

        """Snapshot self and return the snapshot VDI object""" 

        snapLV = lvhdutil.LV_PREFIX[vhdutil.VDI_TYPE_VHD] + snapUuid 

        snapPath = os.path.join(self.sr.path, snapLV) 

        self.sr.lvmCache.create(snapLV, long(snapSizeLV)) 

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

        if isNew: 

            RefCounter.set(snapUuid, 1, 0, lvhdutil.NS_PREFIX_LVM + self.sr.uuid) 

        self.sr.lvActivator.add(snapUuid, snapLV, False) 

        parentRaw = (self.vdi_type == vhdutil.VDI_TYPE_RAW) 

        vhdutil.snapshot(snapPath, self.path, parentRaw, lvhdutil.MSIZE_MB) 

        snapParent = vhdutil.getParent(snapPath, lvhdutil.extractUuid) 

 

        snapVDI = LVHDVDI(self.sr, snapUuid) 

        snapVDI.read_only = False 

        snapVDI.location = snapUuid 

        snapVDI.size = self.size 

        snapVDI.utilisation = snapSizeLV 

        snapVDI.sm_config = dict() 

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

            if key not in ["type", "vdi_type", "vhd-parent", "paused"] and \ 

                    not key.startswith("host_"): 

                snapVDI.sm_config[key] = val 

        snapVDI.sm_config["vdi_type"] = vhdutil.VDI_TYPE_VHD 

        snapVDI.sm_config["vhd-parent"] = snapParent 

        snapVDI.lvname = snapLV 

        return snapVDI 

 

    def _finishSnapshot(self, snapVDI, snapVDI2, hostRefs, cloneOp = False, snapType=None): 

        if snapType is not VDI.SNAPSHOT_INTERNAL: 

            self.sr._updateStats(self.sr.uuid, self.size) 

        basePresent = True 

 

        # Verify parent locator field of both children and delete basePath if  

        # unused 

        snapParent = snapVDI.sm_config["vhd-parent"] 

        snap2Parent = "" 

        if snapVDI2: 

            snap2Parent = snapVDI2.sm_config["vhd-parent"] 

        if snapParent != self.uuid and \ 

                (not snapVDI2 or snap2Parent != self.uuid): 

            util.SMlog("%s != %s != %s => deleting unused base %s" % \ 

                    (snapParent, self.uuid, snap2Parent, self.lvname)) 

            RefCounter.put(self.uuid, False, lvhdutil.NS_PREFIX_LVM + self.sr.uuid) 

            self.sr.lvmCache.remove(self.lvname) 

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

            if hostRefs: 

                self.sr._updateSlavesOnRemove(hostRefs, self.uuid, self.lvname) 

            basePresent = False 

        else: 

            # assign the _binary_ refcount of the original VDI to the new base  

            # VDI (but as the normal refcount, since binary refcounts are only  

            # for leaf nodes). The normal refcount of the child is not  

            # transferred to to the base VDI because normal refcounts are  

            # incremented and decremented individually, and not based on the  

            # VHD chain (i.e., the child's normal refcount will be decremented  

            # independently of its parent situation). Add 1 for this clone op. 

            # Note that we do not need to do protect the refcount operations  

            # below with per-VDI locking like we do in lvutil because at this  

            # point we have exclusive access to the VDIs involved. Other SM  

            # operations are serialized by the Agent or with the SR lock, and  

            # any coalesce activations are serialized with the SR lock.  (The  

            # coalesce activates the coalesced VDI pair in the beginning, which  

            # cannot affect the VDIs here because they cannot  possibly be  

            # involved in coalescing at this point, and at the relinkSkip step  

            # that activates the children, which takes the SR lock.) 

            ns = lvhdutil.NS_PREFIX_LVM + self.sr.uuid 

            (cnt, bcnt) = RefCounter.check(snapVDI.uuid, ns) 

            RefCounter.set(self.uuid, bcnt + 1, 0, ns) 

 

        # the "paused" and "host_*" sm-config keys are special and must stay on  

        # the leaf without being inherited by anyone else 

        for key in filter(lambda x: x == "paused" or x.startswith("host_"), 

                self.sm_config.keys()): 

            snapVDI.sm_config[key] = self.sm_config[key] 

            del self.sm_config[key] 

 

        # Introduce any new VDI records & update the existing one 

        type = self.session.xenapi.VDI.get_type( \ 

                                    self.sr.srcmd.params['vdi_ref']) 

        if snapVDI2: 

            LVMMetadataHandler(self.sr.mdpath).ensureSpaceIsAvailableForVdis(1) 

            vdiRef = snapVDI2._db_introduce() 

            if cloneOp: 

                vdi_info = { UUID_TAG: snapVDI2.uuid, 

                                NAME_LABEL_TAG: util.to_plain_string(\ 

                                    self.session.xenapi.VDI.get_name_label( \ 

                                    self.sr.srcmd.params['vdi_ref'])), 

                                NAME_DESCRIPTION_TAG: util.to_plain_string(\ 

                                  self.session.xenapi.VDI.get_name_description\ 

                                  (self.sr.srcmd.params['vdi_ref'])), 

                                IS_A_SNAPSHOT_TAG: 0, 

                                SNAPSHOT_OF_TAG: '', 

                                SNAPSHOT_TIME_TAG: '', 

                                TYPE_TAG: type, 

                                VDI_TYPE_TAG: snapVDI2.sm_config['vdi_type'], 

                                READ_ONLY_TAG: 0, 

                                MANAGED_TAG: int(snapVDI2.managed), 

                                METADATA_OF_POOL_TAG: '' 

                } 

            else: 

                util.SMlog("snapshot VDI params: %s" % \ 

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

                vdi_info = { UUID_TAG: snapVDI2.uuid, 

                                NAME_LABEL_TAG: util.to_plain_string(\ 

                                    self.session.xenapi.VDI.get_name_label( \ 

                                    self.sr.srcmd.params['vdi_ref'])), 

                                NAME_DESCRIPTION_TAG: util.to_plain_string(\ 

                                  self.session.xenapi.VDI.get_name_description\ 

                                  (self.sr.srcmd.params['vdi_ref'])), 

                                IS_A_SNAPSHOT_TAG: 1, 

                                SNAPSHOT_OF_TAG: snapVDI.uuid, 

                                SNAPSHOT_TIME_TAG: '', 

                                TYPE_TAG: type, 

                                VDI_TYPE_TAG: snapVDI2.sm_config['vdi_type'], 

                                READ_ONLY_TAG: 0, 

                                MANAGED_TAG: int(snapVDI2.managed), 

                                METADATA_OF_POOL_TAG: '' 

                } 

 

            LVMMetadataHandler(self.sr.mdpath).addVdi(vdi_info) 

            util.SMlog("vdi_clone: introduced 2nd snap VDI: %s (%s)" % \ 

                       (vdiRef, snapVDI2.uuid)) 

 

        if basePresent: 

            LVMMetadataHandler(self.sr.mdpath).ensureSpaceIsAvailableForVdis(1) 

            vdiRef = self._db_introduce() 

            vdi_info = { UUID_TAG: self.uuid, 

                                NAME_LABEL_TAG: self.label, 

                                NAME_DESCRIPTION_TAG: self.description, 

                                IS_A_SNAPSHOT_TAG: 0, 

                                SNAPSHOT_OF_TAG: '', 

                                SNAPSHOT_TIME_TAG: '', 

                                TYPE_TAG: type, 

                                VDI_TYPE_TAG: self.sm_config['vdi_type'], 

                                READ_ONLY_TAG: 1, 

                                MANAGED_TAG: 0, 

                                METADATA_OF_POOL_TAG: '' 

            } 

 

            LVMMetadataHandler(self.sr.mdpath).addVdi(vdi_info) 

            util.SMlog("vdi_clone: introduced base VDI: %s (%s)" % \ 

                    (vdiRef, self.uuid)) 

 

        # Update the original record 

        vdi_ref = self.sr.srcmd.params['vdi_ref'] 

        self.session.xenapi.VDI.set_sm_config(vdi_ref, snapVDI.sm_config) 

        self.session.xenapi.VDI.set_physical_utilisation(vdi_ref, \ 

                str(snapVDI.utilisation)) 

 

        # Return the info on the new snap VDI 

        snap = snapVDI2 

        if not snap: 

            snap = self 

            if not basePresent: 

                # a single-snapshot of an empty VDI will be a noop, resulting  

                # in no new VDIs, so return the existing one. The GC wouldn't  

                # normally try to single-snapshot an empty VHD of course, but  

                # if an external snapshot operation manages to sneak in right  

                # before a snapshot-coalesce phase, we would get here 

                snap = snapVDI 

        return snap.get_params() 

 

    def _initFromVDIInfo(self, vdiInfo): 

        self.vdi_type    = vdiInfo.vdiType 

        self.lvname      = vdiInfo.lvName 

        self.size        = vdiInfo.sizeVirt 

        self.utilisation = vdiInfo.sizeLV 

        self.hidden      = vdiInfo.hidden 

2037        if self.hidden: 

            self.managed = False 

        self.active      = vdiInfo.lvActive 

        self.readonly    = vdiInfo.lvReadonly 

        self.parent      = vdiInfo.parentUuid 

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

2045        if hasattr(self, "sm_config_override"): 

            self.sm_config_override["vdi_type"] = self.vdi_type 

        else: 

            self.sm_config_override = {'vdi_type': self.vdi_type} 

        self.loaded = True 

 

    def _initFromLVInfo(self, lvInfo): 

        self.vdi_type    = lvInfo.vdiType 

        self.lvname      = lvInfo.name 

        self.size        = lvInfo.size 

        self.utilisation = lvInfo.size 

        self.hidden      = lvInfo.hidden 

        self.active      = lvInfo.active 

        self.readonly    = lvInfo.readonly 

        self.parent      = '' 

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

        if hasattr(self, "sm_config_override"): 

            self.sm_config_override["vdi_type"] = self.vdi_type 

        else: 

            self.sm_config_override = {'vdi_type': self.vdi_type} 

        if self.vdi_type == vhdutil.VDI_TYPE_RAW: 

            self.loaded = True 

 

    def _initFromVHDInfo(self, vhdInfo): 

        self.size   = vhdInfo.sizeVirt 

        self.parent = vhdInfo.parentUuid 

        self.hidden = vhdInfo.hidden 

        self.loaded = True 

 

    def _determineType(self): 

        """Determine whether this is a raw or a VHD VDI""" 

        if self.sr.srcmd.params.has_key("vdi_ref"): 

            vdi_ref = self.sr.srcmd.params["vdi_ref"] 

            sm_config = self.session.xenapi.VDI.get_sm_config(vdi_ref) 

            if sm_config.get("vdi_type"): 

                self.vdi_type = sm_config["vdi_type"] 

                prefix = lvhdutil.LV_PREFIX[self.vdi_type] 

                self.lvname = "%s%s" % (prefix, self.uuid) 

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

                self.sm_config_override = sm_config 

                return True 

 

        # LVM commands can be costly, so check the file directly first in case  

        # the LV is active 

        found = False 

        for t in lvhdutil.VDI_TYPES: 

            lvname = "%s%s" % (lvhdutil.LV_PREFIX[t], self.uuid) 

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

            if util.pathexists(path): 

                if found: 

                    raise xs_errors.XenError('VDILoad', 

                            opterr="multiple VDI's: uuid %s" % self.uuid) 

                found = True 

                self.vdi_type = t 

                self.lvname   = lvname 

                self.path     = path 

        if found: 

            return True 

 

        # now list all LV's 

        if not lvutil._checkVG(self.sr.vgname): 

            # when doing attach_from_config, the VG won't be there yet 

            return False 

 

        lvs = lvhdutil.getLVInfo(self.sr.lvmCache) 

        if lvs.get(self.uuid): 

            self._initFromLVInfo(lvs[self.uuid]) 

            return True 

        return False 

 

    def _loadThis(self): 

        """Load VDI info for this VDI and activate the LV if it's VHD. We 

        don't do it in VDI.load() because not all VDI operations need it.""" 

        if self.loaded: 

            if self.vdi_type == vhdutil.VDI_TYPE_VHD: 

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

            return 

        try: 

            lvs = lvhdutil.getLVInfo(self.sr.lvmCache, self.lvname) 

        except util.CommandException, e: 

            raise xs_errors.XenError('VDIUnavailable', 

                    opterr= '%s (LV scan error)' % os.strerror(abs(e.code))) 

        if not lvs.get(self.uuid): 

            raise xs_errors.XenError('VDIUnavailable', opterr='LV not found') 

        self._initFromLVInfo(lvs[self.uuid]) 

        if self.vdi_type == vhdutil.VDI_TYPE_VHD: 

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

            vhdInfo = vhdutil.getVHDInfo(self.path, lvhdutil.extractUuid, False) 

            if not vhdInfo: 

                raise xs_errors.XenError('VDIUnavailable', \ 

                        opterr='getVHDInfo failed') 

            self._initFromVHDInfo(vhdInfo) 

        self.loaded = True 

 

    def _chainSetActive(self, active, binary, persistent = False): 

        if binary: 

            (count, bcount) = RefCounter.checkLocked(self.uuid, 

                lvhdutil.NS_PREFIX_LVM + self.sr.uuid) 

            if (active and bcount > 0) or (not active and bcount == 0): 

                return # this is a redundant activation/deactivation call 

 

        vdiList = {self.uuid: self.lvname} 

        if self.vdi_type == vhdutil.VDI_TYPE_VHD: 

            vdiList = vhdutil.getParentChain(self.lvname, 

                    lvhdutil.extractUuid, self.sr.vgname) 

        for uuid, lvName in vdiList.iteritems(): 

            binaryParam = binary 

            if uuid != self.uuid: 

                binaryParam = False # binary param only applies to leaf nodes 

            if active: 

                self.sr.lvActivator.activate(uuid, lvName, binaryParam, 

                        persistent) 

            else: 

                # just add the LVs for deactivation in the final (cleanup)  

                # step. The LVs must not have been activated during the current  

                # operation 

                self.sr.lvActivator.add(uuid, lvName, binaryParam) 

 

    def _failClone(self, uuid, jval, msg): 

        try: 

            self.sr._handleInterruptedCloneOp(uuid, jval, True) 

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

        except Exception, e: 

            util.SMlog('WARNING: failed to clean up failed snapshot: ' \ 

                    ' %s (error ignored)' % e) 

        raise xs_errors.XenError('VDIClone', opterr=msg) 

 

    def _markHidden(self): 

        if self.vdi_type == vhdutil.VDI_TYPE_RAW: 

            self.sr.lvmCache.setHidden(self.lvname) 

        else: 

            vhdutil.setHidden(self.path) 

        self.hidden = 1 

 

    def _prepareThin(self, attach): 

        origUtilisation = self.sr.lvmCache.getSize(self.lvname) 

        if self.sr.isMaster: 

            # the master can prepare the VDI locally 

            if attach: 

                lvhdutil.attachThin(self.sr.journaler, self.sr.uuid, self.uuid) 

            else: 

                lvhdutil.detachThin(self.session, self.sr.lvmCache, 

                        self.sr.uuid, self.uuid) 

        else: 

            fn = "attach" 

            if not attach: 

                fn = "detach" 

            pools = self.session.xenapi.pool.get_all() 

            master = self.session.xenapi.pool.get_master(pools[0]) 

            rv = self.session.xenapi.host.call_plugin( 

                    master, self.sr.THIN_PLUGIN, fn, 

                    {"srUuid": self.sr.uuid, "vdiUuid": self.uuid}) 

            util.SMlog("call-plugin returned: %s" % rv) 

            if not rv: 

                raise Exception('plugin %s failed' % self.sr.THIN_PLUGIN) 

            # refresh to pick up the size change on this slave 

            self.sr.lvmCache.activateNoRefcount(self.lvname, True) 

 

        self.utilisation = self.sr.lvmCache.getSize(self.lvname) 

        if origUtilisation != self.utilisation: 

            vdi_ref = self.sr.srcmd.params['vdi_ref'] 

            self.session.xenapi.VDI.set_physical_utilisation(vdi_ref, 

                    str(self.utilisation)) 

            stats = lvutil._getVGstats(self.sr.vgname) 

            sr_utilisation = stats['physical_utilisation'] 

            self.session.xenapi.SR.set_physical_utilisation(self.sr.sr_ref, 

                    str(sr_utilisation)) 

 

    def update(self, sr_uuid, vdi_uuid): 

        if self.sr.legacyMode: 

            return 

 

        #Synch the name_label of this VDI on storage with the name_label in XAPI 

        vdi_ref = self.session.xenapi.VDI.get_by_uuid(self.uuid) 

        update_map = {} 

        update_map[METADATA_UPDATE_OBJECT_TYPE_TAG] = \ 

            METADATA_OBJECT_TYPE_VDI 

        update_map[UUID_TAG] = self.uuid 

        update_map[NAME_LABEL_TAG] = util.to_plain_string(\ 

            self.session.xenapi.VDI.get_name_label(vdi_ref)) 

        update_map[NAME_DESCRIPTION_TAG] = util.to_plain_string(\ 

            self.session.xenapi.VDI.get_name_description(vdi_ref)) 

        update_map[SNAPSHOT_TIME_TAG] = \ 

            self.session.xenapi.VDI.get_snapshot_time(vdi_ref) 

        update_map[METADATA_OF_POOL_TAG] = \ 

            self.session.xenapi.VDI.get_metadata_of_pool(vdi_ref) 

        LVMMetadataHandler(self.sr.mdpath).updateMetadata(update_map) 

 

    def _ensure_cbt_space(self): 

        self.sr.ensureCBTSpace() 

 

    def _create_cbt_log(self): 

        logname = self._get_cbt_logname(self.uuid) 

        self.sr.lvmCache.create(logname, self.sr.journaler.LV_SIZE, CBTLOG_TAG) 

        logpath = super(LVHDVDI, self)._create_cbt_log() 

        self.sr.lvmCache.deactivateNoRefcount(logname) 

        return logpath 

 

    def _delete_cbt_log(self): 

        logpath = self._get_cbt_logpath(self.uuid) 

        if self._cbt_log_exists(logpath): 

            logname = self._get_cbt_logname(self.uuid) 

            self.sr.lvmCache.remove(logname) 

 

    def _rename(self, oldpath, newpath): 

        oldname = os.path.basename(oldpath) 

        newname = os.path.basename(newpath) 

        self.sr.lvmCache.rename(oldname, newname) 

 

    def _activate_cbt_log(self, lv_name): 

        self.sr.lvmCache.refresh() 

        if not self.sr.lvmCache.is_active(lv_name): 

            try: 

                self.sr.lvmCache.activateNoRefcount(lv_name) 

                return True 

            except Exception, e: 

                util.SMlog("Exception in _activate_cbt_log, " 

                           "Error: %s." % str(e)) 

        else: 

            return False 

 

    def _deactivate_cbt_log(self, lv_name): 

        try: 

            self.sr.lvmCache.deactivateNoRefcount(lv_name) 

        except Exception, e: 

            util.SMlog("Exception in _deactivate_cbt_log, Error: %s." % str(e)) 

 

    def _cbt_log_exists(self, logpath): 

        return lvutil.exists(logpath) 

 

2273if __name__ == '__main__': 

    SRCommand.run(LVHDSR, DRIVER_INFO) 

else: 

    SR.registerSR(LVHDSR)