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

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

 

DEFAULT_NFSVERSION = '3' 

 

NFS_VERSION = [ 

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

 

NFS_SERVICE_WAIT = 30 

NFS_SERVICE_RETRY = 6 

 

class NfsException(Exception): 

 

    def __init__(self, errstr): 

        self.errstr = errstr 

 

 

def check_server_tcp(server, 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) 

        return (True if nfsversion in sv else False) 

    except util.CommandException, inst: 

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

                           inst.code) 

 

def check_server_service(server): 

    """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 

    """ 

 

    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: 

135        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) 

 

 

    # Wait for NFS service to be available 

    try: 

137        if not check_server_service(remoteserver): 

            raise util.CommandException(code=errno.EOPNOTSUPP, 

                    reason="No NFS service on host") 

    except util.CommandException, inst: 

        raise NfsException("Failed to detect NFS service on server %s" 

                           % remoteserver) 

 

    mountcommand = 'mount.nfs' 

    if nfsversion == '4': 

        mountcommand = 'mount.nfs4' 

 

148    if nfsversion == '4.1': 

        mountcommand = 'mount.nfs4' 

 

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

        transport, 

        nfsversion) 

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

 

156    if timeout != None: 

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

158    if retrans != None: 

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

160    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(target): 

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

    util.SMlog("scanning") 

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

    dom = xml.dom.minidom.Document() 

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

    dom.appendChild(element) 

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

196        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_srlist(path, 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')) 

            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_versions(server): 

    """Return list of supported nfs versions.""" 

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

    cv = set() 

    try: 

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

        ns = ns.split("\n") 

270        for i in range(len(ns)): 

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

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

                cv.add(cvi) 

        return list(cv & valid_versions) 

    except: 

        util.SMlog("Unable to obtain list of valid nfs versions") 

        raise NfsException('Failed to read supported NFS version from server' % 

                           (server)) 

 

def get_nfs_timeout(other_config): 

    nfs_timeout = 100 

 

283    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 = 3 

 

295    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