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

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

# 

# Miscellaneous utility functions 

# 

 

import os, re, sys, subprocess, shutil, tempfile, signal 

import time, datetime 

import errno, socket 

import xml.dom.minidom 

import scsiutil 

import statvfs 

import stat 

import xs_errors 

import XenAPI,xmlrpclib 

import base64 

import syslog 

import resource 

import exceptions 

import traceback 

import glob 

import copy 

import tempfile 

 

NO_LOGGING_STAMPFILE='/etc/xensource/no_sm_log' 

 

IORETRY_MAX = 20 # retries 

IORETRY_PERIOD = 1.0 # seconds 

 

LOGGING = not (os.path.exists(NO_LOGGING_STAMPFILE)) 

_SM_SYSLOG_FACILITY = syslog.LOG_LOCAL2 

LOG_EMERG   = syslog.LOG_EMERG 

LOG_ALERT   = syslog.LOG_ALERT 

LOG_CRIT    = syslog.LOG_CRIT 

LOG_ERR     = syslog.LOG_ERR 

LOG_WARNING = syslog.LOG_WARNING 

LOG_NOTICE  = syslog.LOG_NOTICE 

LOG_INFO    = syslog.LOG_INFO 

LOG_DEBUG   = syslog.LOG_DEBUG 

 

ISCSI_REFDIR = '/var/run/sr-ref' 

 

CMD_DD = "/bin/dd" 

 

FIST_PAUSE_PERIOD = 30 # seconds 

 

class SMException(Exception): 

    """Base class for all SM exceptions for easier catching & wrapping in  

    XenError""" 

    pass 

 

class CommandException(SMException): 

    def __init__(self, code, cmd = "", reason='exec failed'): 

        self.code = code 

        self.cmd = cmd 

        self.reason = reason 

        Exception.__init__(self, os.strerror(abs(code))) 

 

class SRBusyException(SMException): 

    """The SR could not be locked""" 

    pass 

 

def logException(tag): 

    info = sys.exc_info() 

81    if info[0] == exceptions.SystemExit: 

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

        sys.exit(0) 

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

    str = "***** %s: EXCEPTION %s, %s\n%s" % (tag, info[0], info[1], tb) 

    SMlog(str) 

 

def roundup(divisor, value): 

    """Retruns the rounded up value so it is divisible by divisor.""" 

 

90    if value == 0: 

        value = 1 

    if value % divisor != 0: 

        return ((int(value) / divisor) + 1) * divisor 

    return value 

 

def to_plain_string(obj): 

    if obj is None: 

        return None 

100    if type(obj) == str: 

        return obj 

    if type(obj) == unicode: 

        return obj.encode("utf-8") 

    return str(obj) 

 

def shellquote(arg): 

    return '"%s"' % arg.replace('"', '\\"') 

 

def make_WWN(name): 

    hex_prefix = name.find("0x") 

    if (hex_prefix >=0): 

        name = name[name.find("0x")+2:len(name)] 

    # inject dashes for each nibble 

    if (len(name) == 16): #sanity check 

        name = name[0:2] + "-" + name[2:4] + "-" + name[4:6] + "-" + \ 

               name[6:8] + "-" + name[8:10] + "-" + name[10:12] + "-" + \ 

               name[12:14] + "-" + name[14:16] 

    return name 

 

def _logToSyslog(ident, facility, priority, message): 

    syslog.openlog(ident, 0, facility) 

    syslog.syslog(priority, "[%d] %s" % (os.getpid(), message)) 

    syslog.closelog() 

 

def SMlog(message, ident="SM", priority=LOG_INFO): 

exit    if LOGGING: 

        for message_line in str(message).split('\n'): 

            _logToSyslog(ident, _SM_SYSLOG_FACILITY, priority, message_line) 

 

def _getDateString(): 

    d = datetime.datetime.now() 

    t = d.timetuple() 

    return "%s-%s-%s:%s:%s:%s" % \ 

          (t[0],t[1],t[2],t[3],t[4],t[5]) 

 

def doexec(args, inputtext=None, new_env=None): 

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

    env = None 

    if new_env: 

        env = dict(os.environ) 

        env.update(new_env) 

    proc = subprocess.Popen(args, stdin=subprocess.PIPE, 

                            stdout=subprocess.PIPE, 

                            stderr=subprocess.PIPE, 

                            close_fds=True, env=env) 

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

    # Workaround for a pylint bug, can be removed after upgrade to 

    # python 3.x or maybe a newer version of pylint in the future 

    stdout = str(stdout) 

    stderr = str(stderr) 

    rc = proc.returncode 

    return (rc,stdout,stderr) 

 

def is_string(value): 

    return isinstance(value,basestring) 

 

# These are partially tested functions that replicate the behaviour of 

# the original pread,pread2 and pread3 functions. Potentially these can 

# replace the original ones at some later date. 

# 

# cmdlist is a list of either single strings or pairs of strings. For 

# each pair, the first component is passed to exec while the second is 

# written to the logs. 

def pread(cmdlist, close_stdin=False, scramble=None, expect_rc=0, 

          quiet=False, new_env=None): 

    cmdlist_for_exec = [] 

    cmdlist_for_log = [] 

    for item in cmdlist: 

177        if is_string(item): 

            cmdlist_for_exec.append(item) 

170            if scramble: 

                if item.find(scramble) != -1: 

                    cmdlist_for_log.append("<filtered out>") 

                else: 

                    cmdlist_for_log.append(item) 

            else: 

                cmdlist_for_log.append(item) 

        else: 

            cmdlist_for_exec.append(item[0]) 

            cmdlist_for_log.append(item[1]) 

 

182    if not quiet: 

        SMlog(cmdlist_for_log) 

    (rc,stdout,stderr) = doexec(cmdlist_for_exec, new_env=new_env) 

    if rc != expect_rc: 

        SMlog("FAILED in util.pread: (rc %d) stdout: '%s', stderr: '%s'" % \ 

                (rc, stdout, stderr)) 

187        if quiet: 

            SMlog("Command was: %s" % cmdlist_for_log) 

190        if '' == stderr: 

            stderr = stdout 

        raise CommandException(rc, str(cmdlist), stderr.strip()) 

193    if not quiet: 

        SMlog("  pread SUCCESS") 

    return stdout 

 

 

# POSIX guaranteed atomic within the same file system. 

# Supply directory to ensure tempfile is created 

# in the same directory. 

def atomicFileWrite(targetFile, directory, text): 

 

    file = None 

    try: 

        # Create file only current pid can write/read to 

        # our responsibility to clean it up. 

        _, tempPath = tempfile.mkstemp(dir=directory) 

        file = open(tempPath, 'w') 

        file.write(text) 

 

        # Ensure flushed to disk. 

        file.flush() 

        os.fsync(file.fileno()) 

        file.close() 

 

        os.rename(tempPath, targetFile) 

    except OSError: 

        SMlog("FAILED to atomic write to %s" % (targetFile)) 

 

    finally: 

        if (file is not None) and (not file.closed): 

            file.close() 

 

        if os.path.isfile(tempPath): 

            os.remove(tempPath) 

 

#Read STDOUT from cmdlist and discard STDERR output 

def pread2(cmdlist, quiet = False): 

    return pread(cmdlist, quiet = quiet) 

 

#Read STDOUT from cmdlist, feeding 'text' to STDIN 

def pread3(cmdlist, text): 

    SMlog(cmdlist) 

    (rc,stdout,stderr) = doexec(cmdlist,text) 

    if rc: 

        SMlog("FAILED in util.pread3: (errno %d) stdout: '%s', stderr: '%s'" % \ 

                (rc, stdout, stderr)) 

        if '' == stderr: 

            stderr = stdout 

        raise CommandException(rc, str(cmdlist), stderr.strip()) 

    SMlog("  pread3 SUCCESS") 

    return stdout 

 

def listdir(path, quiet = False): 

    cmd = ["ls", path, "-1", "--color=never"] 

    try: 

        text = pread2(cmd, quiet = quiet)[:-1] 

        if len(text) == 0: 

            return [] 

        return text.split('\n') 

    except CommandException, inst: 

        if inst.code == errno.ENOENT: 

            raise CommandException(errno.EIO, inst.cmd, inst.reason) 

        else: 

            raise CommandException(inst.code, inst.cmd, inst.reason) 

 

def gen_uuid(): 

    cmd = ["uuidgen", "-r"] 

    return pread(cmd)[:-1] 

 

def match_uuid(s): 

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

    return regex.search(s, 0) 

 

def findall_uuid(s): 

    regex = re.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") 

    return regex.findall(s, 0) 

 

def exactmatch_uuid(s): 

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

    return regex.search(s, 0) 

 

def start_log_entry(srpath, path, args): 

    logstring = str(datetime.datetime.now()) 

    logstring += " log: " 

    logstring += srpath 

    logstring +=  " " + path 

    for element in args: 

        logstring += " " + element 

    try: 

        file = open(srpath + "/filelog.txt", "a") 

        file.write(logstring) 

        file.write("\n") 

        file.close() 

    except: 

        pass 

        # failed to write log ...  

 

def end_log_entry(srpath, path, args): 

    # for teminating, use "error" or "done" 

    logstring = str(datetime.datetime.now()) 

    logstring += " end: " 

    logstring += srpath 

    logstring +=  " " + path 

    for element in args: 

        logstring += " " + element 

    try: 

        file = open(srpath + "/filelog.txt", "a") 

        file.write(logstring) 

        file.write("\n") 

        file.close() 

    except: 

        pass 

        # failed to write log ...  

    # for now print 

    # print "%s" % logstring 

 

def rotate_string(x, n): 

    transtbl = "" 

    for a in range(0, 256): 

        transtbl = transtbl + chr(a) 

    transtbl = transtbl[n:] + transtbl[0:n] 

    return x.translate(transtbl) 

 

def untransform_string(str, remove_trailing_nulls=False): 

    """De-obfuscate string. To cope with an obfuscation bug in Rio, the argument 

    remove_trailing_nulls should be set to True""" 

    tmp = base64.decodestring(str) 

    if remove_trailing_nulls: 

        tmp = tmp.rstrip('\x00') 

    return rotate_string(tmp, -13) 

 

def transform_string(str): 

    """Re-obfuscate string""" 

    tmp = rotate_string(str, 13) 

    return base64.encodestring(tmp) 

 

def ioretry(f, errlist=[errno.EIO], maxretry=IORETRY_MAX, period=IORETRY_PERIOD, **ignored): 

    retries = 0 

    while True: 

        try: 

            return f() 

        except OSError, inst: 

             err = int(inst.errno) 

             inst = CommandException(err, str(f), "OSError") 

340             if not err in errlist: 

                 raise inst 

        except CommandException, inst: 

338            if not int(inst.code) in errlist: 

                raise 

 

        retries += 1 

        if retries >= maxretry: 

            break 

 

        time.sleep(period) 

 

    raise inst 

 

def ioretry_stat(f, maxretry=IORETRY_MAX): 

    # this ioretry is similar to the previous method, but 

    # stat does not raise an error -- so check its return 

    retries = 0 

    while retries < maxretry: 

        stat = f() 

        if stat[statvfs.F_BLOCKS] != -1: 

            return stat 

        time.sleep(1) 

        retries += 1 

    raise CommandException(errno.EIO, str(f)) 

 

def sr_get_capability(sr_uuid): 

    result = [] 

    session = get_localAPI_session() 

    sr_ref = session.xenapi.SR.get_by_uuid(sr_uuid) 

    sm_type = session.xenapi.SR.get_record(sr_ref)['type'] 

    sm_rec = session.xenapi.SM.get_all_records_where( \ 

                              "field \"type\" = \"%s\"" % sm_type) 

 

    # SM expects atleast one entry of any SR type 

    if len(sm_rec) > 0: 

        result = sm_rec.values()[0]['capabilities'] 

 

    session.xenapi.logout() 

    return result 

 

def sr_get_driver_info(driver_info): 

    results = {} 

    # first add in the vanilla stuff 

    for key in [ 'name', 'description', 'vendor', 'copyright', \ 

                 'driver_version', 'required_api_version' ]: 

        results[key] = driver_info[key] 

    # add the capabilities (xmlrpc array) 

    # enforcing activate/deactivate for blktap2 

    caps = driver_info['capabilities'] 

    if "ATOMIC_PAUSE" in caps: 

        for cap in ("VDI_ACTIVATE", "VDI_DEACTIVATE"): 

            if not cap in caps: 

                caps.append(cap) 

    elif "VDI_ACTIVATE" in caps or "VDI_DEACTIVATE" in caps: 

        SMlog("Warning: vdi_[de]activate present for %s" % driver_info["name"]) 

 

    results['capabilities'] = caps 

    # add in the configuration options 

    options = [] 

    for option in driver_info['configuration']: 

        options.append({ 'key': option[0], 'description': option[1] }) 

    results['configuration'] = options 

    return xmlrpclib.dumps((results,), "", True) 

 

def return_nil(): 

    return xmlrpclib.dumps((None,), "", True, allow_none=True) 

 

def SRtoXML(SRlist): 

    dom = xml.dom.minidom.Document() 

    driver = dom.createElement("SRlist") 

    dom.appendChild(driver) 

 

    for key in SRlist.keys(): 

        dict = SRlist[key] 

        entry = dom.createElement("SR") 

        driver.appendChild(entry) 

 

        e = dom.createElement("UUID") 

        entry.appendChild(e) 

        textnode = dom.createTextNode(key) 

        e.appendChild(textnode) 

 

        if dict.has_key('size'): 

            e = dom.createElement("Size") 

            entry.appendChild(e) 

            textnode = dom.createTextNode(str(dict['size'])) 

            e.appendChild(textnode) 

 

        if dict.has_key('storagepool'): 

            e = dom.createElement("StoragePool") 

            entry.appendChild(e) 

            textnode = dom.createTextNode(str(dict['storagepool'])) 

            e.appendChild(textnode) 

 

        if dict.has_key('aggregate'): 

            e = dom.createElement("Aggregate") 

            entry.appendChild(e) 

            textnode = dom.createTextNode(str(dict['aggregate'])) 

            e.appendChild(textnode) 

 

    return dom.toprettyxml() 

 

def pathexists(path): 

    try: 

        os.lstat(path) 

        return True 

    except OSError, inst: 

443        if inst.errno == errno.EIO: 

            time.sleep(1) 

            try: 

                listdir(os.path.realpath(os.path.dirname(path))) 

                os.lstat(path) 

                return True 

            except: 

                pass 

            raise CommandException(errno.EIO, "os.lstat(%s)" % path, "failed") 

        return False 

 

def force_unlink(path): 

    try: 

        os.unlink(path) 

    except OSError, e: 

        if e.errno != errno.ENOENT: 

            raise 

 

def create_secret(session, secret): 

    ref = session.xenapi.secret.create({'value' : secret}) 

    return session.xenapi.secret.get_uuid(ref) 

 

def get_secret(session, uuid): 

    try: 

        ref = session.xenapi.secret.get_by_uuid(uuid) 

        return session.xenapi.secret.get_value(ref) 

    except: 

        raise xs_errors.XenError('InvalidSecret', opterr='Unable to look up secret [%s]' % uuid) 

 

def get_real_path(path): 

    "Follow symlinks to the actual file" 

    absPath = path 

    directory = '' 

    while os.path.islink(absPath): 

        directory = os.path.dirname(absPath) 

        absPath = os.readlink(absPath) 

        absPath = os.path.join(directory, absPath) 

    return absPath 

 

def wait_for_path(path,timeout): 

486    for i in range(0,timeout): 

485        if len(glob.glob(path)): 

            return True 

        time.sleep(1) 

    return False 

 

def wait_for_nopath(path,timeout): 

    for i in range(0,timeout): 

        if not os.path.exists(path): 

            return True 

        time.sleep(1) 

    return False 

 

def wait_for_path_multi(path,timeout): 

    for i in range(0,timeout): 

        paths = glob.glob(path) 

        SMlog( "_wait_for_paths_multi: paths = %s" % paths ) 

        if len(paths): 

            SMlog( "_wait_for_paths_multi: return first path: %s" % paths[0] ) 

            return paths[0] 

        time.sleep(1) 

    return "" 

 

def isdir(path): 

    try: 

        st = os.stat(path) 

        return stat.S_ISDIR(st.st_mode) 

    except OSError, inst: 

511        if inst.errno == errno.EIO: 

            raise CommandException(errno.EIO, "os.stat(%s)" % path, "failed") 

        return False 

 

def get_single_entry(path): 

    f = open(path, 'r') 

    line = f.readline() 

    f.close() 

    return line.rstrip() 

 

def get_fs_size(path): 

    st = ioretry_stat(lambda: os.statvfs(path)) 

    return st[statvfs.F_BLOCKS] * st[statvfs.F_FRSIZE] 

 

def get_fs_utilisation(path): 

    st = ioretry_stat(lambda: os.statvfs(path)) 

    return (st[statvfs.F_BLOCKS] - st[statvfs.F_BFREE]) * \ 

            st[statvfs.F_FRSIZE] 

 

def ismount(path): 

    """Test whether a path is a mount point""" 

    try: 

        s1 = os.stat(path) 

        s2 = os.stat(os.path.join(path, '..')) 

    except OSError, inst: 

        raise CommandException(inst.errno, "os.stat") 

    dev1 = s1.st_dev 

    dev2 = s2.st_dev 

    if dev1 != dev2: 

        return True     # path/.. on a different device as path 

    ino1 = s1.st_ino 

    ino2 = s2.st_ino 

    if ino1 == ino2: 

        return True     # path/.. is the same i-node as path 

    return False 

 

def makedirs(name, mode=0777): 

    head, tail = os.path.split(name) 

549    if not tail: 

        head, tail = os.path.split(head) 

    if head and tail and not pathexists(head): 

        makedirs(head, mode) 

        if tail == os.curdir: 

            return 

    try: 

        os.mkdir(name, mode) 

    except OSError as exc: 

558        if exc.errno == errno.EEXIST and os.path.isdir(name): 

            if mode: 

                os.chmod(name, mode) 

            pass 

        else: 

            raise 

 

def zeroOut(path, fromByte, bytes): 

    """write 'bytes' zeros to 'path' starting from fromByte (inclusive)""" 

    blockSize = 4096 

 

    fromBlock = fromByte / blockSize 

    if fromByte % blockSize: 

        fromBlock += 1 

        bytesBefore = fromBlock * blockSize - fromByte 

        if bytesBefore > bytes: 

            bytesBefore = bytes 

        bytes -= bytesBefore 

        cmd = [CMD_DD, "if=/dev/zero", "of=%s" % path, "bs=1", \ 

                "seek=%s" % fromByte, "count=%s" % bytesBefore] 

        try: 

            text = pread2(cmd) 

        except CommandException: 

            return False 

 

    blocks = bytes / blockSize 

    bytes -= blocks * blockSize 

    fromByte = fromBlock + blocks * blockSize 

    if blocks: 

        cmd = [CMD_DD, "if=/dev/zero", "of=%s" % path, "bs=%s" % blockSize, \ 

                "seek=%s" % fromBlock, "count=%s" % blocks] 

        try: 

            text = pread2(cmd) 

        except CommandException: 

            return False 

 

    if bytes: 

        cmd = [CMD_DD, "if=/dev/zero", "of=%s" % path, "bs=1", \ 

                "seek=%s" % fromByte, "count=%s" % bytes] 

        try: 

            text = pread2(cmd) 

        except CommandException: 

            return False 

 

    return True 

 

def match_rootdev(s): 

    regex = re.compile("^PRIMARY_DISK") 

    return regex.search(s, 0) 

 

def getrootdev(): 

    filename = '/etc/xensource-inventory' 

    try: 

        f = open(filename, 'r') 

    except: 

        raise xs_errors.XenError('EIO', \ 

              opterr="Unable to open inventory file [%s]" % filename) 

    rootdev = '' 

    for line in filter(match_rootdev, f.readlines()): 

        rootdev = line.split("'")[1] 

618    if not rootdev: 

        raise xs_errors.XenError('NoRootDev') 

    return rootdev 

 

def getrootdevID(): 

    rootdev = getrootdev() 

    try: 

        rootdevID = scsiutil.getSCSIid(rootdev) 

    except: 

        SMlog("util.getrootdevID: Unable to verify serial or SCSIid of device: %s" \ 

                   % rootdev) 

        return '' 

 

    if not len(rootdevID): 

        SMlog("util.getrootdevID: Unable to identify scsi device [%s] via scsiID" \ 

                   % rootdev) 

 

    return rootdevID 

 

def get_localAPI_session(): 

    # First acquire a valid session 

    session = XenAPI.xapi_local() 

    try: 

        session.xenapi.login_with_password('root', '', '', 'SM') 

    except: 

        raise xs_errors.XenError('APISession') 

    return session 

 

def get_this_host(): 

    uuid = None 

    f = open("/etc/xensource-inventory", 'r') 

    for line in f.readlines(): 

        if line.startswith("INSTALLATION_UUID"): 

            uuid = line.split("'")[1] 

    f.close() 

    return uuid 

 

 

def get_master_ref(session): 

    pools = session.xenapi.pool.get_all() 

    return session.xenapi.pool.get_master(pools[0]) 

 

 

def get_master_rec(session): 

    return session.xenapi.host.get_record(get_master_ref(session)) 

 

 

def is_master(session): 

    return get_this_host_ref(session) == get_master_ref(session) 

 

 

def get_master_address(): 

    address = None 

    try: 

        fd = open('/etc/xensource/pool.conf', 'r') 

        try: 

            items = fd.readline().split(':') 

            if items[0].strip() == 'master': 

                address = 'localhost' 

            else: 

                address = items[1].strip() 

        finally: 

            fd.close() 

    except Exception: 

        pass 

    return address 

 

 

# XXX: this function doesn't do what it claims to do 

def get_localhost_uuid(session): 

    filename = '/etc/xensource-inventory' 

    try: 

        f = open(filename, 'r') 

    except: 

        raise xs_errors.XenError('EIO', \ 

              opterr="Unable to open inventory file [%s]" % filename) 

    domid = '' 

    for line in filter(match_domain_id, f.readlines()): 

        domid = line.split("'")[1] 

    if not domid: 

        raise xs_errors.XenError('APILocalhost') 

 

    vms = session.xenapi.VM.get_all_records_where('field "uuid" = "%s"' % domid) 

    for vm in vms: 

        record = vms[vm] 

        if record["uuid"] == domid: 

            hostid = record["resident_on"] 

            return hostid 

    raise xs_errors.XenError('APILocalhost') 

 

def match_domain_id(s): 

    regex = re.compile("^CONTROL_DOMAIN_UUID") 

    return regex.search(s, 0) 

 

def get_hosts_attached_on(session, vdi_uuids): 

    host_refs = {} 

    for vdi_uuid in vdi_uuids: 

        try: 

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

        except XenAPI.Failure: 

            SMlog("VDI %s not in db, ignoring" % vdi_uuid) 

            continue 

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

        for key in filter(lambda x: x.startswith('host_'), sm_config.keys()): 

            host_refs[key[len('host_'):]] = True 

    return host_refs.keys() 

 

def get_this_host_ref(session): 

    host_uuid = get_this_host() 

    host_ref = session.xenapi.host.get_by_uuid(host_uuid) 

    return host_ref 

 

def get_slaves_attached_on(session, vdi_uuids): 

    "assume this host is the SR master" 

    host_refs = get_hosts_attached_on(session, vdi_uuids) 

    master_ref = get_this_host_ref(session) 

    return filter(lambda x: x != master_ref, host_refs) 

 

def get_online_hosts(session): 

    online_hosts = [] 

    hosts = session.xenapi.host.get_all_records() 

    for host_ref, host_rec in hosts.iteritems(): 

        metricsRef = host_rec["metrics"] 

        metrics = session.xenapi.host_metrics.get_record(metricsRef) 

        if metrics["live"]: 

            online_hosts.append(host_ref) 

    return online_hosts 

 

def get_all_slaves(session): 

    "assume this host is the SR master" 

    host_refs = get_online_hosts(session) 

    master_ref = get_this_host_ref(session) 

    return filter(lambda x: x != master_ref, host_refs) 

 

def is_attached_rw(sm_config): 

    for key, val in sm_config.iteritems(): 

        if key.startswith("host_") and val == "RW": 

            return True 

    return False 

 

def attached_as(sm_config): 

    for key, val in sm_config.iteritems(): 

        if key.startswith("host_") and (val == "RW" or val == "RO"): 

            return val 

 

def find_my_pbd_record(session, host_ref, sr_ref): 

    try: 

        pbds = session.xenapi.PBD.get_all_records() 

        for pbd_ref in pbds.keys(): 

            if pbds[pbd_ref]['host'] == host_ref and pbds[pbd_ref]['SR'] == sr_ref: 

                return [pbd_ref,pbds[pbd_ref]] 

        return None 

    except Exception, e: 

        SMlog("Caught exception while looking up PBD for host %s SR %s: %s" % (str(host_ref), str(sr_ref), str(e))) 

        return None 

 

def find_my_pbd(session, host_ref, sr_ref): 

    ret = find_my_pbd_record(session, host_ref, sr_ref) 

    if ret <> None: 

        return ret[0] 

    else: 

        return None 

 

def test_hostPBD_devs(session, sr_uuid, devs): 

    host = get_localhost_uuid(session) 

    sr = session.xenapi.SR.get_by_uuid(sr_uuid) 

    try: 

        pbds = session.xenapi.PBD.get_all_records() 

    except: 

        raise xs_errors.XenError('APIPBDQuery') 

    for dev in devs.split(','): 

        for pbd in pbds: 

            record = pbds[pbd] 

            # it's ok if it's *our* PBD 

            if record["SR"] == sr: 

                break 

            if record["host"] == host: 

                devconfig = record["device_config"] 

                if devconfig.has_key('device'): 

                    for device in devconfig['device'].split(','): 

                        if os.path.realpath(device) == os.path.realpath(dev): 

                            return True; 

    return False 

 

def test_hostPBD_lun(session, targetIQN, LUNid): 

    host = get_localhost_uuid(session) 

    try: 

        pbds = session.xenapi.PBD.get_all_records() 

    except: 

        raise xs_errors.XenError('APIPBDQuery') 

    for pbd in pbds: 

        record = pbds[pbd] 

        if record["host"] == host: 

            devconfig = record["device_config"] 

            if devconfig.has_key('targetIQN') and devconfig.has_key('LUNid'): 

                if devconfig['targetIQN'] == targetIQN and \ 

                       devconfig['LUNid'] == LUNid: 

                    return True; 

    return False 

 

def test_SCSIid(session, sr_uuid, SCSIid): 

    if sr_uuid != None: 

        sr = session.xenapi.SR.get_by_uuid(sr_uuid) 

    try: 

        pbds = session.xenapi.PBD.get_all_records() 

    except: 

        raise xs_errors.XenError('APIPBDQuery') 

    for pbd in pbds: 

        record = pbds[pbd] 

        # it's ok if it's *our* PBD 

        # During FC SR creation, devscan.py passes sr_uuid as None 

        if sr_uuid != None: 

            if record["SR"] == sr: 

                break 

        devconfig = record["device_config"] 

        sm_config = session.xenapi.SR.get_sm_config(record["SR"]) 

        if devconfig.has_key('SCSIid') and devconfig['SCSIid'] == SCSIid: 

                    return True; 

        elif sm_config.has_key('SCSIid') and sm_config['SCSIid'] == SCSIid: 

                    return True; 

        elif sm_config.has_key('scsi-' + SCSIid): 

                    return True; 

    return False 

 

 

class TimeoutException(SMException): 

    pass 

 

 

def timeout_call(timeoutseconds, function, *arguments): 

    def handler(signum, frame): 

        raise TimeoutException() 

    signal.signal(signal.SIGALRM, handler) 

    signal.alarm(timeoutseconds) 

    try: 

        function(*arguments) 

    except: 

        signal.alarm(0) 

        raise 

 

 

def _incr_iscsiSR_refcount(targetIQN, uuid): 

    if not os.path.exists(ISCSI_REFDIR): 

        os.mkdir(ISCSI_REFDIR) 

    filename = os.path.join(ISCSI_REFDIR, targetIQN) 

    try: 

        f = open(filename, 'a+') 

    except: 

        raise xs_errors.XenError('LVMRefCount', \ 

                                 opterr='file %s' % filename) 

 

    found = False 

    refcount = 0 

    for line in filter(match_uuid, f.readlines()): 

        refcount += 1 

        if line.find(uuid) != -1: 

            found = True 

    if not found: 

        f.write("%s\n" % uuid) 

        refcount += 1 

    f.close() 

    return refcount 

 

def _decr_iscsiSR_refcount(targetIQN, uuid): 

    filename = os.path.join(ISCSI_REFDIR, targetIQN) 

    if not os.path.exists(filename): 

        return 0 

    try: 

        f = open(filename, 'a+') 

    except: 

        raise xs_errors.XenError('LVMRefCount', \ 

                                 opterr='file %s' % filename) 

    output = [] 

    refcount = 0 

    for line in filter(match_uuid, f.readlines()): 

        if line.find(uuid) == -1: 

            output.append(line[:-1]) 

            refcount += 1 

    if not refcount: 

        os.unlink(filename) 

        return refcount 

 

    # Re-open file and truncate 

    f.close() 

    f = open(filename, 'w') 

    for i in range(0,refcount): 

        f.write("%s\n" % output[i]) 

    f.close() 

    return refcount 

 

# The agent enforces 1 PBD per SR per host, so we 

# check for active SR entries not attached to this host 

def test_activePoolPBDs(session, host, uuid): 

    try: 

        pbds = session.xenapi.PBD.get_all_records() 

    except: 

        raise xs_errors.XenError('APIPBDQuery') 

    for pbd in pbds: 

        record = pbds[pbd] 

        if record["host"] != host and record["SR"] == uuid \ 

               and record["currently_attached"]: 

            return True 

    return False 

 

def remove_mpathcount_field(session, host_ref, sr_ref, SCSIid): 

    try: 

        pbdref = find_my_pbd(session, host_ref, sr_ref) 

        if pbdref <> None: 

            key = "mpath-" + SCSIid 

            session.xenapi.PBD.remove_from_other_config(pbdref, key) 

    except: 

        pass 

 

def _testHost(hostname, port, errstring): 

    SMlog("_testHost: Testing host/port: %s,%d" % (hostname,port)) 

    try: 

        sockinfo = socket.getaddrinfo(hostname, int(port))[0] 

    except: 

        logException('Exception occured getting IP for %s'%hostname) 

        raise xs_errors.XenError('DNSError') 

 

    timeout = 5 

 

    sock = socket.socket(sockinfo[0], socket.SOCK_STREAM) 

    # Only allow the connect to block for up to timeout seconds 

    sock.settimeout(timeout) 

    try: 

        sock.connect(sockinfo[4]) 

        # Fix for MS storage server bug 

        sock.send('\n') 

        sock.close() 

    except socket.error, reason: 

        SMlog("_testHost: Connect failed after %d seconds (%s) - %s" \ 

                   % (timeout, hostname, reason)) 

        raise xs_errors.XenError(errstring) 

 

def match_scsiID(s, id): 

    regex = re.compile(id) 

    return regex.search(s, 0) 

 

def _isSCSIid(s): 

    regex = re.compile("^scsi-") 

    return regex.search(s, 0) 

 

def test_scsiserial(session, device): 

    device = os.path.realpath(device) 

    if not scsiutil._isSCSIdev(device): 

        SMlog("util.test_scsiserial: Not a serial device: %s" % device) 

        return False 

    serial = "" 

    try: 

        serial += scsiutil.getserial(device) 

    except: 

        # Error allowed, SCSIid is the important one 

        pass 

 

    try: 

        scsiID = scsiutil.getSCSIid(device) 

    except: 

        SMlog("util.test_scsiserial: Unable to verify serial or SCSIid of device: %s" \ 

                   % device) 

        return False 

    if not len(scsiID): 

        SMlog("util.test_scsiserial: Unable to identify scsi device [%s] via scsiID" \ 

                   % device) 

        return False 

 

    try: 

        SRs = session.xenapi.SR.get_all_records() 

    except: 

        raise xs_errors.XenError('APIFailure') 

    for SR in SRs: 

        record = SRs[SR] 

        conf = record["sm_config"] 

        if conf.has_key('devserial'): 

            for dev in conf['devserial'].split(','): 

                if _isSCSIid(dev): 

                    if match_scsiID(dev, scsiID): 

                        return True 

                elif len(serial) and dev == serial: 

                    return True 

    return False 

 

def default(self, field, thunk): 

    try: 

        return getattr(self, field) 

    except: 

        return thunk () 

 

def list_VDI_records_in_sr(sr): 

    """Helper function which returns a list of all VDI records for this SR 

    stored in the XenAPI server, useful for implementing SR.scan""" 

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

    vdis = sr.session.xenapi.VDI.get_all_records_where("field \"SR\" = \"%s\"" % sr_ref) 

    return vdis 

 

# Given a partition (e.g. sda1), get a disk name: 

def diskFromPartition(partition): 

    # check whether this is a device mapper device (e.g. /dev/dm-0) 

    m = re.match('(/dev/)?(dm-[0-9]+)(p[0-9]+)?$', partition) 

    if m is not None: 

        return m.group(2) 

 

    numlen = 0 # number of digit characters 

    m = re.match("\D+(\d+)", partition) 

    if m != None: 

        numlen = len(m.group(1)) 

 

    # is it a cciss? 

    if True in [partition.startswith(x) for x in ['cciss', 'ida', 'rd']]: 

        numlen += 1 # need to get rid of trailing 'p' 

 

    # is it a mapper path? 

    if partition.startswith("mapper"): 

        if re.search("p[0-9]*$",partition): 

            numlen = len(re.match("\d+", partition[::-1]).group(0)) + 1 

            SMlog("Found mapper part, len %d" % numlen) 

        else: 

            numlen = 0 

 

    # is it /dev/disk/by-id/XYZ-part<k>? 

    if partition.startswith("disk/by-id"): 

        return partition[:partition.rfind("-part")] 

 

    return partition[:len(partition) - numlen] 

 

def dom0_disks(): 

    """Disks carrying dom0, e.g. ['/dev/sda']""" 

    disks = [] 

1047   1051    for line in open("/etc/mtab").readlines(): 

        (dev, mountpoint, fstype, opts, freq, passno) = line.split(' ') 

        if mountpoint == '/': 

            disk = diskFromPartition(dev) 

            if not (disk in disks): disks.append(disk) 

    SMlog("Dom0 disks: %s" % disks) 

    return disks 

 

def set_scheduler_sysfs_node(node, str): 

    """Set the scheduler for a sysfs node (e.g. '/sys/block/sda')""" 

 

    path = os.path.join(node, "queue", "scheduler") 

    if not os.path.exists(path): 

        SMlog("no path %s" % path) 

        return 

    try: 

        f = open(path, 'w') 

        f.write("%s\n" % str) 

        f.close() 

        SMlog("Set scheduler to [%s] on [%s]" % (str, node)) 

    except: 

        SMlog("Error setting scheduler to [%s] on [%s]" % (str, node)) 

        pass 

 

def set_scheduler(dev, str): 

    devices = [] 

    if not scsiutil.match_dm(dev): 

        # Remove partition numbers 

        devices.append(diskFromPartition(dev).replace('/', '!')) 

    else: 

        rawdev = diskFromPartition(dev) 

        devices = map(lambda x: os.path.realpath(x)[5:], scsiutil._genReverseSCSIidmap(rawdev.split('/')[-1])) 

 

    for d in devices: 

        set_scheduler_sysfs_node("/sys/block/%s" % d, str) 

 

# This function queries XAPI for the existing VDI records for this SR 

def _getVDIs(srobj): 

    VDIs = [] 

    try: 

        sr_ref = getattr(srobj,'sr_ref') 

    except AttributeError: 

        return VDIs 

 

    refs = srobj.session.xenapi.SR.get_VDIs(sr_ref) 

    for vdi in refs: 

        ref = srobj.session.xenapi.VDI.get_record(vdi) 

        ref['vdi_ref'] = vdi 

        VDIs.append(ref) 

    return VDIs 

 

def _getVDI(srobj, vdi_uuid): 

    vdi = srobj.session.xenapi.VDI.get_by_uuid(vdi_uuid) 

    ref = srobj.session.xenapi.VDI.get_record(vdi) 

    ref['vdi_ref'] = vdi 

    return ref 

 

def _convertDNS(name): 

    addr = socket.getaddrinfo(name,None)[0][4][0] 

    return addr 

 

def _containsVDIinuse(srobj): 

    VDIs = _getVDIs(srobj) 

    for vdi in VDIs: 

        if not vdi['managed']: 

            continue 

        sm_config = vdi['sm_config'] 

        if sm_config.has_key('SRRef'): 

            try: 

                PBDs = srobj.session.xenapi.SR.get_PBDs(sm_config['SRRef']) 

                for pbd in PBDs: 

                    record = PBDs[pbd] 

                    if record["host"] == srobj.host_ref and \ 

                       record["currently_attached"]: 

                        return True 

            except: 

                pass 

    return False 

 

def isVDICommand(cmd): 

1129   1129    if cmd == None or cmd in ["vdi_attach", "vdi_detach", 

                              "vdi_activate", "vdi_deactivate", 

                              "vdi_epoch_begin", "vdi_epoch_end"]: 

        return True 

    else: 

        return False 

 

 

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

# Daemon helper functions 

def p_id_fork(): 

    try: 

        p_id = os.fork() 

    except OSError, e: 

        print "Fork failed: %s (%d)" % (e.strerror,e.errno) 

        sys.exit(-1) 

 

    if (p_id == 0): 

        os.setsid() 

        try: 

            p_id = os.fork() 

        except OSError, e: 

            print "Fork failed: %s (%d)" % (e.strerror,e.errno) 

            sys.exit(-1) 

        if (p_id == 0): 

            os.chdir('/opt/xensource/sm') 

            os.umask(0) 

        else: 

            os._exit(0) 

    else: 

        os._exit(0) 

 

def daemon(): 

    p_id_fork() 

    # Query the max file descriptor parameter for this process 

    maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1] 

 

    # Close any fds that are open 

    for fd in range(0, maxfd): 

        try: 

            os.close(fd) 

        except: 

            pass 

 

    # Redirect STDIN to STDOUT and STDERR 

    os.open('/dev/null', os.O_RDWR) 

    os.dup2(0, 1) 

    os.dup2(0, 2) 

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

 

if __debug__: 

    try: 

        XE_IOFI_IORETRY 

    except NameError: 

        XE_IOFI_IORETRY = os.environ.get('XE_IOFI_IORETRY', None) 

1182    if __name__ == 'util' and XE_IOFI_IORETRY is not None: 

        __import__('iofi') 

 

 

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

# 

#  Fist points 

# 

 

# * The global variable 'fistpoint' define the list of all possible fistpoints; 

# 

# * To activate a fistpoint called 'name', you need to create the file '/tmp/fist_name' 

#   on the SR master; 

# 

# * At the moment, activating a fist point can lead to two possible behaviors: 

#   - if '/tmp/fist_LVHDRT_exit' exists, then the function called during the fistpoint is _exit; 

#   - otherwise, the function called is _pause. 

 

def _pause(secs, name): 

    SMlog("Executing fist point %s: sleeping %d seconds ..." % (name, secs)) 

    time.sleep(secs) 

    SMlog("Executing fist point %s: done" % name) 

 

def _exit(name): 

    SMlog("Executing fist point %s: exiting the current process ..." % name) 

    raise xs_errors.XenError('FistPoint', opterr='%s' % name) 

 

class FistPoint: 

    def __init__(self, points): 

        #SMlog("Fist points loaded") 

        self.points = points 

 

    def is_legal(self, name): 

        return (name in self.points) 

 

    def is_active(self, name): 

        return os.path.exists("/tmp/fist_%s" % name) 

 

    def mark_sr(self, name, sruuid, started): 

        session=get_localAPI_session() 

        sr=session.xenapi.SR.get_by_uuid(sruuid) 

        if started: 

            session.xenapi.SR.add_to_other_config(sr,name,"active") 

        else: 

            session.xenapi.SR.remove_from_other_config(sr,name) 

 

    def activate(self, name, sruuid): 

        if name in self.points: 

            if self.is_active(name): 

                self.mark_sr(name,sruuid,True) 

                if self.is_active("LVHDRT_exit"): 

                    self.mark_sr(name,sruuid,False) 

                    _exit(name) 

                else: 

                    _pause(FIST_PAUSE_PERIOD, name) 

                self.mark_sr(name,sruuid,False) 

        else: 

            SMlog("Unknown fist point: %s" % name) 

 

    def activate_custom_fn(self, name, fn): 

1247        if name in self.points: 

            if self.is_active(name): 

                SMlog("Executing fist point %s: starting ..." % name) 

                fn() 

                SMlog("Executing fist point %s: done" % name) 

        else: 

            SMlog("Unknown fist point: %s" % name) 

 

def list_find(f, seq): 

    for item in seq: 

        if f(item): 

            return item 

 

GCPAUSE_FISTPOINT = "GCLoop_no_pause" 

 

fistpoint = FistPoint( ["LVHDRT_finding_a_suitable_pair", 

                        "LVHDRT_inflating_the_parent", 

                        "LVHDRT_resizing_while_vdis_are_paused", 

                        "LVHDRT_coalescing_VHD_data", 

                        "LVHDRT_coalescing_before_inflate_grandparent", 

                        "LVHDRT_relinking_grandchildren", 

                        "LVHDRT_before_create_relink_journal", 

                        "LVHDRT_xapiSM_serialization_tests", 

                        "LVHDRT_clone_vdi_after_create_journal", 

                        "LVHDRT_clone_vdi_after_shrink_parent", 

                        "LVHDRT_clone_vdi_after_first_snap", 

                        "LVHDRT_clone_vdi_after_second_snap", 

                        "LVHDRT_clone_vdi_after_parent_hidden", 

                        "LVHDRT_clone_vdi_after_parent_ro", 

                        "LVHDRT_clone_vdi_before_remove_journal", 

                        "LVHDRT_clone_vdi_after_lvcreate", 

                        "LVHDRT_clone_vdi_before_undo_clone", 

                        "LVHDRT_clone_vdi_after_undo_clone", 

                        "LVHDRT_inflate_after_create_journal", 

                        "LVHDRT_inflate_after_setSize", 

                        "LVHDRT_inflate_after_zeroOut", 

                        "LVHDRT_inflate_after_setSizePhys", 

                        "LVHDRT_inflate_after_setSizePhys", 

                        "LVHDRT_coaleaf_before_coalesce", 

                        "LVHDRT_coaleaf_after_coalesce", 

                        "LVHDRT_coaleaf_one_renamed", 

                        "LVHDRT_coaleaf_both_renamed", 

                        "LVHDRT_coaleaf_after_vdirec", 

                        "LVHDRT_coaleaf_before_delete", 

                        "LVHDRT_coaleaf_after_delete", 

                        "LVHDRT_coaleaf_before_remove_j", 

                        "LVHDRT_coaleaf_undo_after_rename", 

                        "LVHDRT_coaleaf_undo_after_rename2", 

                        "LVHDRT_coaleaf_undo_after_refcount", 

                        "LVHDRT_coaleaf_undo_after_deflate", 

                        "LVHDRT_coaleaf_undo_end", 

                        "LVHDRT_coaleaf_stop_after_recovery", 

                        "LVHDRT_coaleaf_finish_after_inflate", 

                        "LVHDRT_coaleaf_finish_end", 

                        "LVHDRT_coaleaf_delay_1", 

                        "LVHDRT_coaleaf_delay_2", 

                        "LVHDRT_coaleaf_delay_3", 

                        "testsm_clone_allow_raw", 

                        "xenrt_default_vdi_type_legacy", 

                        "blktap_activate_inject_failure", 

                        "blktap_activate_error_handling", 

                        GCPAUSE_FISTPOINT, 

                        "cleanup_coalesceVHD_inject_failure", 

                        "FileSR_fail_hardlink", 

                        "FileSR_fail_snap1", 

                        "FileSR_fail_snap2"]) 

 

 

def set_dirty(session, sr): 

    try: 

        session.xenapi.SR.add_to_other_config(sr, "dirty", "") 

        SMlog("set_dirty %s succeeded" % (repr(sr))) 

    except: 

        SMlog("set_dirty %s failed (flag already set?)" % (repr(sr))) 

 

def doesFileHaveOpenHandles(fileName): 

    SMlog("Entering doesFileHaveOpenHandles with file: %s" % fileName) 

    (retVal, processAndPidTuples) = \ 

        findRunningProcessOrOpenFile(fileName, False) 

 

    if not retVal: 

        SMlog("Failed to determine if file %s has open handles." % \ 

                   fileName) 

        # err on the side of caution 

        return True 

    else: 

        if len(processAndPidTuples) > 0: 

            return True 

        else: 

            return False 

 

# extract SR uuid from the passed in devmapper entry and return 

# /dev/mapper/VG_XenStorage--c3d82e92--cb25--c99b--b83a--482eebab4a93-MGT 

def extractSRFromDevMapper(path): 

    try: 

        path=os.path.basename(path) 

        path=path[len('VG_XenStorage-')+1:] 

        path=path.replace('--','/') 

        path=path[0:path.rfind('-')] 

        return path.replace('/','-') 

    except: 

        return '' 

 

# Looks at /proc and figures either 

#   If a process is still running (default), returns open file names 

#   If any running process has open handles to the given file (process = False) 

#       returns process names and pids 

def findRunningProcessOrOpenFile(name, process = True): 

    retVal = True 

    try: 

        SMlog("Entering findRunningProcessOrOpenFile with params: %s" % \ 

                   [name, process]) 

        links = [] 

        processandpids = [] 

 

        # Look at all pids 

        pids = [pid for pid in os.listdir('/proc') if pid.isdigit()] 

        for pid in sorted(pids): 

            try: 

                try: 

                    f = None 

                    f = open(os.path.join('/proc', pid, 'cmdline'), 'rb') 

                    prog = f.read()[:-1] 

                    if prog: 

                        # Just want the process name 

                        argv = prog.split('\x00') 

                        prog =  argv[0] 

                except IOError, e: 

                    if e.errno in (errno.ENOENT, errno.ESRCH): 

                        SMlog("ERROR %s reading %s, ignore" % (e.errno, pid)) 

                    continue 

            finally: 

                if f != None: 

                    f.close() 

 

            try: 

                fd_dir = os.path.join('/proc', pid, 'fd') 

                files = os.listdir(fd_dir) 

            except OSError, e: 

                if e.errno in (errno.ENOENT, errno.ESRCH): 

                    SMlog("ERROR %s reading fds for %s, ignore" % (e.errno, pid)) 

                    # Ignore pid that are no longer valid 

                    continue 

                else: 

                    raise 

 

            for file in files: 

                try: 

                    link = os.readlink(os.path.join(fd_dir, file)) 

                except OSError: 

                    continue 

 

                if process: 

                    if name == prog: 

                        links.append(link) 

                else: 

                    # need to return process name and pid tuples 

                    if link == name: 

                        SMlog("File %s has an open handle with process %s " 

                              "with pid %s" % (name, prog, pid)) 

                        processandpids.append((prog, pid)) 

    except Exception, e: 

        SMlog("Exception checking running process or open file handles. "\ 

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

        retVal = False 

 

    if process: 

        return (retVal, links) 

    else: 

        return (retVal, processandpids) 

 

def retry(f, maxretry=20, period=3, exceptions=[Exception]): 

    retries = 0 

    while True: 

        try: 

            return f() 

        except Exception as e: 

            for exception in exceptions: 

                if isinstance(e, exception): 

                    SMlog('Got exception: {}. Retry number: {}'.format( 

                        str(e), retries 

                    )) 

                    break 

            else: 

                SMlog('Got bad exception: {}. Raising...'.format(e)) 

                raise e 

 

        retries += 1 

        if retries >= maxretry: 

            break 

 

        time.sleep(period) 

 

    return f() 

 

def getCslDevPath(svid): 

    basepath = "/dev/disk/by-csldev/" 

    if svid.startswith("NETAPP_"): 

        # special attention for NETAPP SVIDs 

        svid_parts = svid.split("__") 

        globstr = basepath + "NETAPP__LUN__" + "*" + svid_parts[2] + "*" + svid_parts[-1] + "*" 

    else: 

        globstr = basepath + svid + "*" 

 

    return globstr 

 

# Use device in /dev pointed to by cslg path which consists of svid 

def get_scsiid_from_svid(md_svid): 

    cslg_path = getCslDevPath(md_svid) 

    abs_path = glob.glob(cslg_path) 

    if abs_path: 

        real_path = os.path.realpath(abs_path[0]) 

        return scsiutil.getSCSIid(real_path) 

    else: 

        return None 

 

def get_isl_scsiids(session): 

    # Get cslg type SRs 

    SRs = session.xenapi.SR.get_all_records_where('field "type" = "cslg"') 

 

    # Iterate through the SR to get the scsi ids 

    scsi_id_ret = [] 

    for SR in SRs: 

        sr_rec = SRs[SR] 

        # Use the md_svid to get the scsi id 

        scsi_id = get_scsiid_from_svid(sr_rec['sm_config']['md_svid']) 

        if scsi_id: 

            scsi_id_ret.append(scsi_id) 

 

        # Get the vdis in the SR and do the same procedure 

        vdi_recs = session.xenapi.VDI.get_all_records_where('field "SR" = "%s"' % SR) 

        for vdi_rec in vdi_recs: 

            vdi_rec = vdi_recs[vdi_rec] 

            scsi_id = get_scsiid_from_svid(vdi_rec['sm_config']['SVID']) 

            if scsi_id: 

                scsi_id_ret.append(scsi_id) 

 

    return scsi_id_ret 

 

class extractXVA: 

    # streams files as a set of file and checksum, caller should remove  

    # the files, if not needed. The entire directory (Where the files  

    # and checksum) will only be deleted as part of class cleanup. 

    HDR_SIZE = 512 

    BLOCK_SIZE = 512 

    SIZE_LEN = 12 - 1 # To remove \0 from tail 

    SIZE_OFFSET = 124 

    ZERO_FILLED_REC = 2 

    NULL_IDEN = '\x00' 

    DIR_IDEN = '/' 

    CHECKSUM_IDEN = '.checksum' 

    OVA_FILE = 'ova.xml' 

 

    # Init gunzips the file using a subprocess, and reads stdout later  

    # as and when needed 

    def __init__(self, filename): 

        self.__extract_path = '' 

        self.__filename = filename 

        cmd = 'gunzip -cd %s' % filename 

        try: 

            self.spawn_p = subprocess.Popen( 

                            cmd, shell=True, \ 

                            stdin=subprocess.PIPE, stdout=subprocess.PIPE, \ 

                            stderr=subprocess.PIPE, close_fds=True) 

        except Exception, e: 

            SMlog("Error: %s. Uncompress failed for %s" % (str(e), filename)) 

            raise Exception(str(e)) 

 

        # Create dir to extract the files 

        self.__extract_path = tempfile.mkdtemp() 

 

    def __del__(self): 

        shutil.rmtree(self.__extract_path) 

 

    # Class supports Generator expression. 'for f_name, checksum in getTuple()' 

    #   returns filename, checksum content. Returns filename, '' in case   

    #   of checksum file missing. e.g. ova.xml 

    def getTuple(self): 

        zerod_record = 0 

        ret_f_name = '' 

        ret_base_f_name = '' 

 

        try: 

            # Read tar file as sets of file and checksum.  

            while True: 

                # Read the output of spawned process, or output of gunzip 

                f_hdr = self.spawn_p.stdout.read(self.HDR_SIZE) 

 

                # Break out in case of end of file 

                if f_hdr == '': 

                    if zerod_record == extractXVA.ZERO_FILLED_REC: 

                        break 

                    else: 

                        SMlog('Error. Expects %d zero records', \ 

                               extractXVA.ZERO_FILLED_REC) 

                        raise Exception('Unrecognized end of file') 

 

                # Watch out for zero records, two zero records  

                # denote end of file. 

                if f_hdr == extractXVA.NULL_IDEN * extractXVA.HDR_SIZE: 

                    zerod_record += 1 

                    continue 

 

                f_name = f_hdr[:f_hdr.index(extractXVA.NULL_IDEN)] 

                # File header may be for a folder, if so ignore the header 

                if not f_name.endswith(extractXVA.DIR_IDEN): 

                    f_size_octal = f_hdr[extractXVA.SIZE_OFFSET: \ 

                                 extractXVA.SIZE_OFFSET + extractXVA.SIZE_LEN] 

                    f_size = int(f_size_octal, 8) 

                    if f_name.endswith(extractXVA.CHECKSUM_IDEN): 

                        if f_name.rstrip(extractXVA.CHECKSUM_IDEN) == \ 

                                                        ret_base_f_name: 

                            checksum = self.spawn_p.stdout.read(f_size) 

                            yield(ret_f_name, checksum) 

                        else: 

                            # Expects file followed by its checksum 

                            SMlog('Error. Sequence mismatch starting with %s', \ 

                                     ret_f_name) 

                            raise Exception(\ 

                                    'Files out of sequence starting with %s', \ 

                                    ret_f_name) 

                    else: 

                        # In case of ova.xml, read the contents into a file and  

                        # return the file name to the caller. For other files,  

                        # read the contents into a file, it will 

                        # be used when a .checksum file is encountered. 

                        ret_f_name = '%s/%s' % (self.__extract_path, f_name) 

                        ret_base_f_name = f_name 

 

                        # Check if the folder exists on the target location, 

                        # else create it. 

                        folder_path = ret_f_name[:ret_f_name.rfind('/')] 

                        if not os.path.exists(folder_path): 

                            os.mkdir(folder_path) 

 

                        # Store the file to the tmp folder, strip the tail \0  

                        f = open(ret_f_name, 'w') 

                        f.write(self.spawn_p.stdout.read(f_size)) 

                        f.close() 

                        if f_name == extractXVA.OVA_FILE: 

                            yield(ret_f_name, '') 

 

                    # Skip zero'd portion of data block 

                    round_off = f_size % extractXVA.BLOCK_SIZE 

                    if round_off != 0: 

                        zeros = self.spawn_p.stdout.read( 

                                extractXVA.BLOCK_SIZE - round_off) 

        except Exception, e: 

            SMlog("Error: %s. File set extraction failed %s" % (str(e), \ 

                                                     self.__filename)) 

 

            # Kill and Drain stdout of the gunzip process,  

            # else gunzip might block on stdout 

            os.kill(self.spawn_p.pid, signal.SIGTERM) 

            self.spawn_p.communicate() 

            raise Exception(str(e)) 

 

illegal_xml_chars = [(0x00, 0x08), (0x0B, 0x1F), (0x7F, 0x84), (0x86, 0x9F), 

                (0xD800, 0xDFFF), (0xFDD0, 0xFDDF), (0xFFFE, 0xFFFF), 

                (0x1FFFE, 0x1FFFF), (0x2FFFE, 0x2FFFF), (0x3FFFE, 0x3FFFF), 

                (0x4FFFE, 0x4FFFF), (0x5FFFE, 0x5FFFF), (0x6FFFE, 0x6FFFF), 

                (0x7FFFE, 0x7FFFF), (0x8FFFE, 0x8FFFF), (0x9FFFE, 0x9FFFF), 

                (0xAFFFE, 0xAFFFF), (0xBFFFE, 0xBFFFF), (0xCFFFE, 0xCFFFF), 

                (0xDFFFE, 0xDFFFF), (0xEFFFE, 0xEFFFF), (0xFFFFE, 0xFFFFF), 

                (0x10FFFE, 0x10FFFF)] 

 

illegal_ranges = ["%s-%s" % (unichr(low), unichr(high)) 

        for (low, high) in illegal_xml_chars 

        if low < sys.maxunicode] 

 

illegal_xml_re = re.compile(u'[%s]' % u''.join(illegal_ranges)) 

 

def isLegalXMLString(s): 

    """Tells whether this is a valid XML string (i.e. it does not contain 

    illegal XML characters specified in 

    http://www.w3.org/TR/2004/REC-xml-20040204/#charsets). 

    """ 

 

    if len(s) > 0: 

        return None == re.search(illegal_xml_re, s) 

    else: 

        return True 

 

def unictrunc(string, max_bytes): 

    """ 

    Returns the number of bytes that is smaller than, or equal to, the number 

    of bytes specified, such that the UTF-8 encoded string can be correctly 

    truncated. 

    string: the string to truncate 

    max_bytes: the maximum number of bytes the truncated string can be 

    """ 

    string = string.decode('UTF-8') 

    cur_bytes = 0 

    for char in string: 

        charsize = len(char.encode('UTF-8')) 

        if cur_bytes + charsize > max_bytes: 

            break 

        else: 

            cur_bytes = cur_bytes + charsize 

    return cur_bytes 

 

def hideValuesInPropMap( propmap, propnames ): 

    """ 

    Worker function: input simple map of prop name/value pairs, and 

    a list of specific propnames whose values we want to hide. 

    Loop through the "hide" list, and if any are found, hide the 

    value and return the altered map. 

    If none found, return the original map 

    """ 

    matches = [] 

    for propname in propnames: 

        if propname in propmap: 

            matches.append(propname) 

 

    if matches: 

        deepCopyRec = copy.deepcopy(propmap) 

        for match in matches: 

            deepCopyRec[match] = '******' 

        return deepCopyRec 

 

    return propmap 

 

# define the list of propnames whose value we want to hide 

 

PASSWD_PROP_KEYS = ['password', 'cifspassword', 'chappassword', 'incoming_chappassword'] 

DEFAULT_SEGMENT_LEN = 950 

 

def hidePasswdInConfig( config ): 

    """ 

    Function to hide passwd values in a simple prop map,  

    for example "device_config" 

    """ 

    return hideValuesInPropMap( config, PASSWD_PROP_KEYS ) 

 

def hidePasswdInParams( params, configProp ): 

    """ 

    Function to hide password values in a specified property which  

    is a simple map of prop name/values, and is itself an prop entry 

    in a larger property map. 

    For example, param maps containing "device_config", or  

    "sm_config", etc 

    """ 

    params[configProp] = hideValuesInPropMap( params[configProp], PASSWD_PROP_KEYS ) 

    return params 

 

def hideMemberValuesInXmlParams( xmlParams, propnames = PASSWD_PROP_KEYS ): 

    """ 

    Function to hide password values in XML params, specifically  

    for the XML format of incoming params to SR modules. 

    Uses text parsing: loop through the list of specific propnames  

    whose values we want to hide, and: 

    - Assemble a full "prefix" containing each property name, e.g.,  

        "<member><name>password</name><value>" 

    - Test the XML if it contains that string, save the index. 

    - If found, get the index of the ending tag 

    - Truncate the return string starting with the password value. 

    - Append the substitute "*******" value string. 

    - Restore the rest of the original string starting with the end tag. 

    """ 

    findStrPrefixHead = "<member><name>" 

    findStrPrefixTail = "</name><value>" 

    findStrSuffix = "</value>" 

    strlen = len( xmlParams ) 

 

    for propname in propnames: 

        findStrPrefix = findStrPrefixHead + propname + findStrPrefixTail 

        idx = xmlParams.find( findStrPrefix ) 

        if idx != -1:                           # if found any of them 

            idx += len( findStrPrefix ) 

            idx2 = xmlParams.find( findStrSuffix, idx ); 

            if idx2 != -1: 

                retStr = xmlParams[0:idx] 

                retStr += "******" 

                retStr += xmlParams[idx2:strlen] 

                return retStr 

            else: 

                return xmlParams 

    return xmlParams 

 

def splitXmlText( xmlData, segmentLen = DEFAULT_SEGMENT_LEN, showContd = False ): 

    """ 

    Split xml string data into substrings small enough for the 

    syslog line length limit. Split at tag end markers ( ">" ). 

    Usage: 

        strList = [] 

        strList = splitXmlText( longXmlText, maxLineLen )   # maxLineLen is optional 

    """ 

    remainingData = str( xmlData ) 

 

    # "Un-pretty-print" 

    remainingData = remainingData.replace( '\n', '' ) 

    remainingData = remainingData.replace( '\t', '' ) 

 

    remainingChars = len( remainingData ) 

    returnData = '' 

 

    thisLineNum = 0 

    while remainingChars > segmentLen: 

        thisLineNum = thisLineNum + 1 

        index = segmentLen 

        tmpStr = remainingData[:segmentLen] 

        tmpIndex = tmpStr.rfind( '>' ) 

        if tmpIndex != -1: 

            index = tmpIndex+1 

 

        tmpStr = tmpStr[:index] 

        remainingData = remainingData[index:] 

        remainingChars = len( remainingData ) 

 

        if showContd: 

            if thisLineNum != 1: 

                tmpStr = '(Cont\'d): ' + tmpStr 

            tmpStr = tmpStr + ' (Cont\'d):' 

 

        returnData += tmpStr + '\n' 

 

    if showContd and thisLineNum > 0: 

        remainingData = '(Cont\'d): ' + remainingData 

    returnData += remainingData 

 

    return returnData 

 

def inject_failure(): 

    raise Exception('injected failure') 

 

def open_atomic(path, mode=None): 

    """Atomically creates a file if, and only if it does not already exist. 

    Leaves the file open and returns the file object. 

 

    path: the path to atomically open 

    mode: "r" (read), "w" (write), or "rw" (read/write) 

    returns: an open file object""" 

 

    assert path 

 

    flags = os.O_CREAT | os.O_EXCL 

    modes = {'r': os.O_RDONLY, 'w': os.O_WRONLY, 'rw': os.O_RDWR} 

    if mode: 

        if mode not in modes: 

            raise Exception('invalid access mode ' + mode) 

        flags |= modes[mode] 

    fd = os.open(path, flags) 

    try: 

        if mode: 

            return os.fdopen(fd, mode) 

        else: 

            return os.fdopen(fd) 

    except: 

        os.close(fd) 

        raise 

 

def isInvalidVDI(exception): 

    return exception.details[0] == "HANDLE_INVALID" or \ 

            exception.details[0] == "UUID_INVALID" 

 

def get_pool_restrictions(session): 

    """Returns pool restrictions as a map, @session must be already 

    established.""" 

    return session.xenapi.pool.get_all_records().values()[0]['restrictions'] 

 

def read_caching_is_restricted(session): 

    """Tells whether read caching is restricted.""" 

    if session is None or (isinstance(session, str) and session == ""): 

        return True 

    restrictions = get_pool_restrictions(session) 

    if 'restrict_read_caching' in restrictions and \ 

            restrictions['restrict_read_caching'] == "true": 

        return True 

    return False 

 

def sessions_less_than_targets(other_config, device_config): 

    if device_config.has_key('multihomelist') and other_config.has_key('iscsi_sessions'): 

        sessions = int(other_config['iscsi_sessions']) 

        targets = len(device_config['multihomelist'].split(',')) 

        SMlog("Targets %d and iscsi_sessions %d" %(targets, sessions)) 

        return (sessions < targets) 

    else: 

        return False