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

"""Fake util module""" 

 

 

from past.builtins import basestring 

import os 

import subprocess 

import time 

import re 

import glob 

import syslog 

import signal 

import socket 

 

from . import f_exceptions 

 

SCSI_ID_BIN = '/usr/lib/udev/scsi_id' 

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

 

NO_LOGGING_STAMPFILE = '/etc/xensource/no_sm_log' 

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 

 

 

def doexec(args, inputtext=None): 

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

 

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

                            stdout=subprocess.PIPE, 

                            stderr=subprocess.PIPE, 

                            close_fds=True) 

    inputtext = inputtext.encode('utf-8') if inputtext else inputtext 

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

    stdout = stdout.decode('utf-8') 

    stderr = stderr.decode('utf-8') 

    ret = proc.returncode 

    return (ret, stdout, stderr) 

 

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

    for _ in range(timeout): 

        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 scsi_id_sanitise(str_): 

    """scsi_id_sanitise""" 

    text = re.sub("^\s+", "", str_)  # pylint: disable=W1401 

    return re.sub("\s+", "_", text)  # pylint: disable=W1401 

 

 

def is_string(value): 

    """trivial""" 

    return isinstance(value, basestring) 

 

 

def pread(cmdlist, scramble=None, expect_rc=0): 

    """ported from SM util""" 

    cmdlist_for_exec = [] 

    cmdlist_for_log = [] 

    for item in cmdlist: 

        if is_string(item): 

            cmdlist_for_exec.append(item) 

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

 

    (ret, stdout, stderr) = doexec(cmdlist_for_exec) 

    if ret != expect_rc: 

        if stderr == '': 

            stderr = stdout 

        raise f_exceptions.XenError("Command", stderr.strip()) 

    return stdout 

 

 

def pread2(cmdlist): 

    """Ditto""" 

    return pread(cmdlist) 

 

 

def get_scsi_id(path): 

    """Get the SCSI id of a block device 

 

        Input: 

            path -- (str) path to block device; can be symlink 

 

        Return: 

            scsi_id -- (str) the device's SCSI id 

 

        Raise: 

            f_exceptions.XenError 

    """ 

 

    if not path.startswith('/dev/'): 

        path = '/dev/' + path.lstrip('/') 

 

    stdout = pread2([SCSI_ID_BIN, '-g', '--device', path]) 

 

    return scsi_id_sanitise(stdout[:-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) 

 

 

class TimeoutException(Exception): 

    pass 

 

 

def timeout_call(timeoutseconds, function, *arguments): 

    def handler(signum, frame): 

        raise TimeoutException() 

    signal.signal(signal.SIGALRM, handler) 

    signal.alarm(timeoutseconds) 

    try: 

        function(*arguments) 

    finally: 

        # Cancel the alarm signal so that it isn't fired later on 

        signal.alarm(0) 

 

 

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 f_exceptions.XenError('LVMRefCount', 

                                    message='file %s' % filename) 

 

    f.seek(0) 

    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 f_exceptions.XenError('LVMRefCount', 

                                    message='file %s' % filename) 

    f.seek(0) 

    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 

 

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 retry(f, maxretry=20, period=3): 

    retries = 0 

    while True: 

        try: 

            return f() 

        except Exception as e: 

            SMlog("Got exception: %s. Retry number: %s" % (str(e),retries)) 

 

        retries += 1 

        if retries >= maxretry: 

            break 

 

        time.sleep(period) 

 

    return f() 

 

def testHost(hostname, port): 

    """ 

    Modified from _testHost in sm.util 

    """ 

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

    try: 

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

    except: 

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

        return False 

 

    timeout = 10 

 

    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(b'\n') 

        sock.close() 

        return True 

    except socket.error as reason: 

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

                   % (timeout, hostname, reason)) 

    return False