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

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

# 

# nfs.py: NFS related utility functions 

 

import util 

import errno 

import os 

import xml.dom.minidom 

import time 

 

# The algorithm for tcp and udp (at least in the linux kernel) for 

# NFS timeout on softmounts is as follows: 

# 

# UDP: 

# As long as the request wasn't started more than timeo * (2 ^ retrans) 

# in the past, keep doubling the timeout. 

# 

# TCP: 

# As long as the request wasn't started more than timeo * (1 + retrans) 

# in the past, keep increaing the timeout by timeo. 

# 

# The time when the retrans may retry has been made will be: 

# For udp: timeo * (2 ^ retrans * 2 - 1) 

# For tcp: timeo * n! where n is the smallest n for which n! > 1 + retrans 

# 

# thus for retrans=1, timeo can be the same for both tcp and udp, 

# because the first doubling (timeo*2) is the same as the first increment 

# (timeo+timeo). 

 

RPCINFO_BIN = "/usr/sbin/rpcinfo" 

SHOWMOUNT_BIN = "/usr/sbin/showmount" 

NFS_STAT = "/usr/sbin/nfsstat" 

 

DEFAULT_NFSVERSION = '3' 

 

NFS_VERSION = [ 

    'nfsversion', 'for type=nfs, NFS protocol version - 3, 4, 4.1'] 

 

NFS_SERVICE_WAIT = 30 

NFS_SERVICE_RETRY = 6 

 

NFS4_PSEUDOFS = "/" 

NFS4_TMP_MOUNTPOINT = "/tmp/mnt" 

 

class NfsException(Exception): 

 

    def __init__(self, errstr): 

        self.errstr = errstr 

 

 

def check_server_tcp(server, transport, nfsversion=DEFAULT_NFSVERSION): 

    """Make sure that NFS over TCP/IP V3 is supported on the server. 

 

    Returns True if everything is OK 

    False otherwise. 

    """ 

    try: 

        sv = get_supported_nfs_versions(server, transport) 

        return (nfsversion[0] in sv) 

    except util.CommandException, inst: 

        raise NfsException("rpcinfo failed or timed out: return code %d" % 

                           inst.code) 

 

def check_server_service(server, transport): 

    """Ensure NFS service is up and available on the remote server. 

 

    Returns False if fails to detect service after  

    NFS_SERVICE_RETRY * NFS_SERVICE_WAIT 

    """ 

 

    try: 

        sv = get_supported_nfs_versions(server, transport) 

        # Services are not present in NFS4 only, this doesn't mean there's no NFS 

90        if "4" in sv: 

            return True 

    except NfsException: 

        # Server failed to give us supported versions 

        pass 

 

    retries = 0 

    errlist = [errno.EPERM, errno.EPIPE, errno.EIO] 

 

    while True: 

        try: 

            services = util.pread([RPCINFO_BIN, "-s", "%s" % server]) 

            services = services.split("\n") 

            for i in range(len(services)): 

                if services[i].find("nfs") > 0: 

                    return True 

        except util.CommandException, inst: 

            if not int(inst.code) in errlist: 

                raise 

 

        util.SMlog("NFS service not ready on server %s" % server) 

        retries += 1 

        if retries >= NFS_SERVICE_RETRY: 

            break 

 

        time.sleep(NFS_SERVICE_WAIT) 

 

    return False 

 

 

def validate_nfsversion(nfsversion): 

    """Check the validity of 'nfsversion'. 

 

    Raise an exception for any invalid version. 

    """ 

    if not nfsversion: 

        nfsversion = DEFAULT_NFSVERSION 

    else: 

        if nfsversion not in ['3', '4', '4.1']: 

            raise NfsException("Invalid nfsversion.") 

    return nfsversion 

 

 

def soft_mount(mountpoint, remoteserver, remotepath, transport, useroptions='', 

               timeout=None, nfsversion=DEFAULT_NFSVERSION, retrans=None): 

    """Mount the remote NFS export at 'mountpoint'. 

 

    The 'timeout' param here is in deciseconds (tenths of a second). See 

    nfs(5) for details. 

    """ 

    try: 

148        if not util.ioretry(lambda: util.isdir(mountpoint)): 

            util.ioretry(lambda: util.makedirs(mountpoint)) 

    except util.CommandException, inst: 

        raise NfsException("Failed to make directory: code is %d" % 

                           inst.code) 

 

 

 

    mountcommand = 'mount.nfs' 

    if nfsversion == '4': 

        mountcommand = 'mount.nfs4' 

 

153    if nfsversion == '4.1': 

        mountcommand = 'mount.nfs4' 

 

    options = "soft,proto=%s,vers=%s" % ( 

        transport, 

        nfsversion) 

    options += ',acdirmin=0,acdirmax=0' 

 

161    if timeout != None: 

        options += ",timeo=%s" % timeout 

163    if retrans != None: 

        options += ",retrans=%s" % retrans 

165    if useroptions != '': 

        options += ",%s" % useroptions 

 

    try: 

        util.ioretry(lambda: 

                     util.pread([mountcommand, "%s:%s" 

                                 % (remoteserver, remotepath), 

                                 mountpoint, "-o", options]), 

                     errlist=[errno.EPIPE, errno.EIO], 

                     maxretry=2, nofail=True) 

    except util.CommandException, inst: 

        raise NfsException("mount failed with return code %d" % inst.code) 

 

 

def unmount(mountpoint, rmmountpoint): 

    """Unmount the mounted mountpoint""" 

    try: 

        util.pread(["umount", mountpoint]) 

    except util.CommandException, inst: 

        raise NfsException("umount failed with return code %d" % inst.code) 

 

    if rmmountpoint: 

        try: 

            os.rmdir(mountpoint) 

        except OSError, inst: 

            raise NfsException("rmdir failed with error '%s'" % inst.strerror) 

 

 

def _scan_exports_nfs3(target, dom, element): 

    """ Scan target and return an XML DOM with target, path and accesslist. 

        Using NFS3 services. 

    """ 

    cmd = [SHOWMOUNT_BIN, "--no-headers", "-e", target] 

    for val in util.pread2(cmd).split('\n'): 

199        if not len(val): 

            continue 

        entry = dom.createElement('Export') 

        element.appendChild(entry) 

 

        subentry = dom.createElement("Target") 

        entry.appendChild(subentry) 

        textnode = dom.createTextNode(target) 

        subentry.appendChild(textnode) 

 

        # Access is not always provided by showmount return 

        # If none is provided we need to assume "*" 

        array = val.split() 

        path = array[0] 

        access = array[1] if len(array) >= 2 else "*" 

        subentry = dom.createElement("Path") 

        entry.appendChild(subentry) 

        textnode = dom.createTextNode(path) 

        subentry.appendChild(textnode) 

 

        subentry = dom.createElement("Accesslist") 

        entry.appendChild(subentry) 

        textnode = dom.createTextNode(access) 

        subentry.appendChild(textnode) 

 

    return dom 

 

def _scan_exports_nfs4_only(target, transport, dom, element): 

    """ Scan target and return an XML DOM with target, path and accesslist. 

        Using NFS4 only pseudo FS. 

    """ 

 

    mountpoint = "%s/%s" % (NFS4_TMP_MOUNTPOINT, target) 

    soft_mount(mountpoint, target, NFS4_PSEUDOFS, transport, nfsversion="4") 

    paths = os.listdir(mountpoint) 

    unmount(mountpoint, NFS4_PSEUDOFS) 

    for path in paths: 

        entry = dom.createElement("Export") 

        element.appendChild(entry) 

 

        subentry = dom.createElement("Target") 

        entry.appendChild(subentry) 

        textnode = dom.createTextNode(target) 

        subentry.appendChild(textnode) 

        subentry = dom.createElement("Path") 

        entry.appendChild(subentry) 

        textnode = dom.createTextNode(path) 

        subentry.appendChild(textnode) 

 

        subentry = dom.createElement("Accesslist") 

        entry.appendChild(subentry) 

        # Assume everyone as we do not have any info about it 

        textnode = dom.createTextNode("*") 

        subentry.appendChild(textnode) 

    return dom 

 

def scan_exports(target, transport): 

    """Scan target and return an XML DOM with target, path and accesslist.""" 

    util.SMlog("scanning") 

    dom = xml.dom.minidom.Document() 

    element = dom.createElement("nfs-exports") 

    dom.appendChild(element) 

    try: 

        return _scan_exports_nfs3(target, dom, element) 

    except Exception: 

        util.SMlog("Unable to scan exports with %s, trying NFSv4" % SHOWMOUNT_BIN) 

 

    # NFSv4 only 

    try: 

        return _scan_exports_nfs4_only(target, transport, dom, element) 

    except Exception: 

        util.SMlog("Unable to scan exports with NFSv4 pseudo FS mount") 

 

    raise NfsException("Failed to read NFS export paths from server %s" % 

                           (target)) 

 

def scan_srlist(path, transport, dconf): 

    """Scan and report SR, UUID.""" 

    dom = xml.dom.minidom.Document() 

    element = dom.createElement("SRlist") 

    dom.appendChild(element) 

    for val in filter(util.match_uuid, util.ioretry( 

            lambda: util.listdir(path))): 

        fullpath = os.path.join(path, val) 

        if not util.ioretry(lambda: util.isdir(fullpath)): 

            continue 

 

        entry = dom.createElement('SR') 

        element.appendChild(entry) 

 

        subentry = dom.createElement("UUID") 

        entry.appendChild(subentry) 

        textnode = dom.createTextNode(val) 

        subentry.appendChild(textnode) 

 

    from NFSSR import PROBEVERSION 

    if dconf.has_key(PROBEVERSION): 

        util.SMlog("Add supported nfs versions to sr-probe") 

        try: 

            supported_versions = get_supported_nfs_versions(dconf.get('server'), transport) 

            supp_ver = dom.createElement("SupportedVersions") 

            element.appendChild(supp_ver) 

 

            for ver in supported_versions: 

                version = dom.createElement('Version') 

                supp_ver.appendChild(version) 

                textnode = dom.createTextNode(ver) 

                version.appendChild(textnode) 

        except NfsException: 

            # Server failed to give us supported versions 

            pass 

 

    return dom.toprettyxml() 

 

 

def _get_supported_nfs_version_rpcinfo(server): 

    """ Return list of supported nfs versions. 

        Using NFS3 services. 

        *Might* return "4" in the list of supported NFS versions, but might not: 

        There is no requirement for NFS4 to register with rpcbind, even though it can, so 

        a server which supports NFS4 might still only return ["3"] from here. 

    """ 

 

    valid_versions = set(["3", "4"]) 

    cv = set() 

    ns = util.pread2([RPCINFO_BIN, "-s", "%s" % server]) 

    ns = ns.split("\n") 

    for i in range(len(ns)): 

        if ns[i].find("nfs") > 0: 

            cvi = ns[i].split()[1].split(",") 

            for j in range(len(cvi)): 

                cv.add(cvi[j]) 

    return sorted(cv & valid_versions) 

 

 

def _is_nfs4_supported(server, transport): 

    """ Return list of supported nfs versions. 

        Using NFS4 pseudo FS. 

    """ 

 

    cv = set() 

    try: 

        mountpoint = "%s/%s" % (NFS4_TMP_MOUNTPOINT, server) 

        soft_mount(mountpoint, server, NFS4_PSEUDOFS, transport, nfsversion='4') 

        util.pread2([NFS_STAT, "-m"]) 

        unmount(mountpoint, NFS4_PSEUDOFS) 

        return True 

    except Exception: 

        return False 

 

 

def get_supported_nfs_versions(server, transport): 

    """ 

    Return list of supported nfs versions. 

    First check list from rpcinfo and if that does not contain NFS4, probe for it and 

    add it to the list if available. 

    """ 

    vers = [] 

    try: 

        vers = _get_supported_nfs_version_rpcinfo(server) 

    except Exception: 

        util.SMlog("Unable to obtain list of valid nfs versions with %s, trying NFSv4" % RPCINFO_BIN) 

 

    # Test for NFS4 if the rpcinfo query did not find it (NFS4 does not *have* to register with rpcbind) 

    if "4" not in vers: 

        if _is_nfs4_supported(server, transport): 

            vers.append("4") 

 

    if vers: 

        return vers 

    else: 

        raise NfsException("Failed to read supported NFS version from server %s" % (server)) 

 

 

def get_nfs_timeout(other_config): 

    nfs_timeout = 200 

 

376    if other_config.has_key('nfs-timeout'): 

        val = int(other_config['nfs-timeout']) 

        if val < 1: 

            util.SMlog("Invalid nfs-timeout value: %d" % val) 

        else: 

            nfs_timeout = val 

 

    return nfs_timeout 

 

def get_nfs_retrans(other_config): 

    nfs_retrans = 4 

 

388    if other_config.has_key('nfs-retrans'): 

        val = int(other_config['nfs-retrans']) 

        if val < 0: 

            util.SMlog("Invalid nfs-retrans value: %d" % val) 

        else: 

            nfs_retrans = val 

 

    return nfs_retrans