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

#!/usr/bin/env python 

# 

# Copyright (C) 2020  Vates SAS - ronan.abhamon@vates.fr 

# 

# This program is free software: you can redistribute it and/or modify 

# it under the terms of the GNU General Public License as published by 

# the Free Software Foundation, either version 3 of the License, or 

# (at your option) any later version. 

# 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 General Public License for more details. 

# 

# You should have received a copy of the GNU General Public License 

# along with this program.  If not, see <https://www.gnu.org/licenses/>. 

 

import base64 

import distutils.util 

import errno 

import json 

import socket 

import util 

import vhdutil 

import xs_errors 

 

MANAGER_PLUGIN = 'linstor-manager' 

 

# EMEDIUMTYPE constant (124) is not available in python2. 

EMEDIUMTYPE = 124 

 

 

def call_vhd_util_on_host(session, host_ref, method, device_path, args): 

    try: 

        response = session.xenapi.host.call_plugin( 

            host_ref, MANAGER_PLUGIN, method, args 

        ) 

    except Exception as e: 

        util.SMlog('call-plugin ({} with {}) exception: {}'.format( 

            method, args, e 

        )) 

        raise 

 

    util.SMlog('call-plugin ({} with {}) returned: {}'.format( 

        method, args, response 

    )) 

 

    return response 

 

 

def linstorhostcall(local_method, remote_method): 

    def decorated(response_parser): 

        def wrapper(*args, **kwargs): 

            self = args[0] 

            vdi_uuid = args[1] 

 

            device_path = self._linstor.build_device_path( 

                self._linstor.get_volume_name(vdi_uuid) 

            ) 

 

            # A. Try a call using directly the DRBD device to avoid 

            # remote request. 

 

            # Try to read locally if the device is not in use or if the device 

            # is up to date and not diskless. 

            (node_names, in_use) = \ 

                self._linstor.find_up_to_date_diskful_nodes(vdi_uuid) 

 

            local_e = None 

            try: 

                if not in_use or socket.gethostname() in node_names: 

                    # Don't call `_call_local_vhd_util`, we don't want to 

                    # trace failed calls now using opener files. It can be 

                    # normal to have an exception. 

                    def local_call(): 

                        return local_method(device_path, *args[2:], **kwargs) 

                    return util.retry(local_call, 5, 2) 

            except util.CommandException as local_e: 

                self._handle_local_vhd_util_error(local_e) 

 

            # B. Execute the plugin on master or slave. 

            remote_args = { 

                'devicePath': device_path, 

                'groupName': self._linstor.group_name 

            } 

            remote_args.update(**kwargs) 

            remote_args = {str(key): str(value) for key, value in remote_args.iteritems()} 

 

            try: 

                def remote_call(): 

                    host_ref = self._get_readonly_host(vdi_uuid, device_path, node_names) 

                    return call_vhd_util_on_host(self._session, host_ref, remote_method, device_path, remote_args) 

                response = util.retry(remote_call, 5, 2) 

            except Exception as remote_e: 

                self._raise_openers_exception(device_path, local_e or remote_e) 

 

            return response_parser(self, vdi_uuid, response) 

        return wrapper 

    return decorated 

 

 

def linstormodifier(): 

    def decorated(func): 

        def wrapper(*args, **kwargs): 

            self = args[0] 

 

            ret = func(*args, **kwargs) 

            self._linstor.invalidate_resource_cache() 

            return ret 

        return wrapper 

    return decorated 

 

 

class LinstorVhdUtil: 

    def __init__(self, session, linstor): 

        self._session = session 

        self._linstor = linstor 

 

    # -------------------------------------------------------------------------- 

    # Getters: read locally and try on another host in case of failure. 

    # -------------------------------------------------------------------------- 

 

    def check(self, vdi_uuid, ignore_missing_footer=False, fast=False): 

        kwargs = { 

            'ignoreMissingFooter': str(ignore_missing_footer), 

            'fast': str(fast) 

        } 

        return self._check(vdi_uuid, **kwargs) 

 

    @linstorhostcall(vhdutil.check, 'check') 

    def _check(self, vdi_uuid, **kwargs): 

        return distutils.util.strtobool(kwargs['response']) 

 

    def get_vhd_info(self, vdi_uuid, include_parent=True): 

        kwargs = {'includeParent': str(include_parent)} 

        # TODO: Replace pylint comment with this feature when possible: 

        # https://github.com/PyCQA/pylint/pull/2926 

        return self._get_vhd_info(vdi_uuid, self._extract_uuid, **kwargs)  # pylint: disable = E1123 

 

    @linstorhostcall(vhdutil.getVHDInfo, 'getVHDInfo') 

    def _get_vhd_info(self, vdi_uuid, response): 

        obj = json.loads(response) 

 

        vhd_info = vhdutil.VHDInfo(vdi_uuid) 

        vhd_info.sizeVirt = obj['sizeVirt'] 

        vhd_info.sizePhys = obj['sizePhys'] 

        if 'parentPath' in obj: 

            vhd_info.parentPath = obj['parentPath'] 

            vhd_info.parentUuid = obj['parentUuid'] 

        vhd_info.hidden = obj['hidden'] 

        vhd_info.path = obj['path'] 

 

        return vhd_info 

 

    @linstorhostcall(vhdutil.hasParent, 'hasParent') 

    def has_parent(self, vdi_uuid, response): 

        return distutils.util.strtobool(response) 

 

    def get_parent(self, vdi_uuid): 

        return self._get_parent(vdi_uuid, self._extract_uuid) 

 

    @linstorhostcall(vhdutil.getParent, 'getParent') 

    def _get_parent(self, vdi_uuid, response): 

        return response 

 

    @linstorhostcall(vhdutil.getSizeVirt, 'getSizeVirt') 

    def get_size_virt(self, vdi_uuid, response): 

        return int(response) 

 

    @linstorhostcall(vhdutil.getSizePhys, 'getSizePhys') 

    def get_size_phys(self, vdi_uuid, response): 

        return int(response) 

 

    @linstorhostcall(vhdutil.getDepth, 'getDepth') 

    def get_depth(self, vdi_uuid, response): 

        return int(response) 

 

    @linstorhostcall(vhdutil.getKeyHash, 'getKeyHash') 

    def get_key_hash(self, vdi_uuid, response): 

        return response or None 

 

    @linstorhostcall(vhdutil.getBlockBitmap, 'getBlockBitmap') 

    def get_block_bitmap(self, vdi_uuid, response): 

        return base64.b64decode(response) 

 

    # -------------------------------------------------------------------------- 

    # Setters: only used locally. 

    # -------------------------------------------------------------------------- 

 

    @linstormodifier() 

    def create(self, path, size, static, msize=0): 

        return self._call_local_vhd_util(vhdutil.create, path, size, static, msize) 

 

    @linstormodifier() 

    def set_size_virt_fast(self, path, size): 

        return self._call_local_vhd_util(vhdutil.setSizeVirtFast, path, size) 

 

    @linstormodifier() 

    def set_size_phys(self, path, size, debug=True): 

        return self._call_local_vhd_util(vhdutil.setSizePhys, path, size, debug) 

 

    @linstormodifier() 

    def set_parent(self, path, parentPath, parentRaw=False): 

        return self._call_local_vhd_util(vhdutil.setParent, path, parentPath, parentRaw) 

 

    @linstormodifier() 

    def set_hidden(self, path, hidden=True): 

        return self._call_local_vhd_util(vhdutil.setHidden, path, hidden) 

 

    @linstormodifier() 

    def set_key(self, path, key_hash): 

        return self._call_local_vhd_util(vhdutil.setKey, path, key_hash) 

 

    @linstormodifier() 

    def kill_data(self, path): 

        return self._call_local_vhd_util(vhdutil.killData, path) 

 

    @linstormodifier() 

    def snapshot(self, path, parent, parentRaw, msize=0, checkEmpty=True): 

        return self._call_local_vhd_util(vhdutil.snapshot, path, parent, parentRaw, msize, checkEmpty) 

 

    # -------------------------------------------------------------------------- 

    # Remote setters: write locally and try on another host in case of failure. 

    # -------------------------------------------------------------------------- 

 

    @linstormodifier() 

    def force_parent(self, path, parentPath, parentRaw=False): 

        kwargs = { 

            'parentPath': str(parentPath), 

            'parentRaw': parentRaw 

        } 

        return self._call_vhd_util(vhdutil.setParent, 'setParent', path, **kwargs) 

 

    @linstormodifier() 

    def force_coalesce(self, path): 

        return self._call_vhd_util(vhdutil.coalesce, 'coalesce', path) 

 

    @linstormodifier() 

    def force_repair(self, path): 

        return self._call_vhd_util(vhdutil.repair, 'repair', path) 

 

    # -------------------------------------------------------------------------- 

    # Helpers. 

    # -------------------------------------------------------------------------- 

 

    def _extract_uuid(self, device_path): 

        # TODO: Remove new line in the vhdutil module. Not here. 

        return self._linstor.get_volume_uuid_from_device_path( 

            device_path.rstrip('\n') 

        ) 

 

    def _get_readonly_host(self, vdi_uuid, device_path, node_names): 

        """ 

        When vhd-util is called to fetch VDI info we must find a 

        diskful DRBD disk to read the data. It's the goal of this function. 

        Why? Because when a VHD is open in RO mode, the LVM layer is used 

        directly to bypass DRBD verifications (we can have only one process 

        that reads/writes to disk with DRBD devices). 

        """ 

 

        if not node_names: 

            raise xs_errors.XenError( 

                'VDIUnavailable', 

                opterr='Unable to find diskful node: {} (path={})' 

                .format(vdi_uuid, device_path) 

            ) 

 

        hosts = self._session.xenapi.host.get_all_records() 

        for host_ref, host_record in hosts.items(): 

            if host_record['hostname'] in node_names: 

                return host_ref 

 

        raise xs_errors.XenError( 

            'VDIUnavailable', 

            opterr='Unable to find a valid host from VDI: {} (path={})' 

            .format(vdi_uuid, device_path) 

        ) 

 

    # -------------------------------------------------------------------------- 

 

    def _raise_openers_exception(self, device_path, e): 

        e_with_openers = None 

        try: 

            volume_uuid = self._linstor.get_volume_uuid_from_device_path( 

                device_path 

            ) 

            e_wrapper = util.CommandException( 

                e.code, 

                e.cmd, 

                e.reason + ' (openers: {})'.format( 

                    self._linstor.get_volume_openers(volume_uuid) 

                ) 

            ) 

        except Exception as illformed_e: 

            e_wrapper = util.CommandException( 

                e.code, 

                e.cmd, 

                e.reason + ' (unable to get openers: {})'.format(illformed_e) 

            ) 

        util.SMlog('raise opener exception: {} ({})'.format(e_wrapper, e_wrapper.reason)) 

        raise e_wrapper  # pylint: disable = E0702 

 

    @staticmethod 

    def _handle_local_vhd_util_error(e): 

        if e.code != errno.EROFS and e.code != EMEDIUMTYPE: 

            util.SMlog('failed to execute locally vhd-util (sys {})'.format(e.code)) 

 

    def _call_local_vhd_util(self, local_method, device_path, *args, **kwargs): 

        try: 

            def local_call(): 

                return local_method(device_path, *args, **kwargs) 

            return util.retry(local_call, 5, 2) 

        except util.CommandException as e: 

            self._handle_local_vhd_util_error(e) 

 

        # Volume is locked on a host, find openers. 

        self._raise_openers_exception(device_path, e) 

 

    def _call_vhd_util(self, local_method, remote_method, device_path, *args, **kwargs): 

        # A. Try to write locally... 

        try: 

            def local_call(): 

                return local_method(device_path, *args, **kwargs) 

            return util.retry(local_call, 5, 2) 

        except util.CommandException as e: 

            self._handle_local_vhd_util_error(e) 

 

        # B. Execute the command on another host. 

        # B.1. Get host list. 

        try: 

            hosts = self._session.xenapi.host.get_all_records() 

        except Exception as e: 

            raise xs_errors.XenError( 

                'VDIUnavailable', 

                opterr='Unable to get host list to run vhd-util command `{}` (path={}): {}' 

                .format(remote_method, device_path, e) 

            ) 

 

        # B.2. Prepare remote args. 

        remote_args = { 

            'devicePath': device_path, 

            'groupName': self._linstor.group_name 

        } 

        remote_args.update(**kwargs) 

        remote_args = {str(key): str(value) for key, value in remote_args.iteritems()} 

 

        volume_uuid = self._linstor.get_volume_uuid_from_device_path( 

            device_path 

        ) 

 

        # B.3. Call! 

        def remote_call(): 

            try: 

                all_openers = self._linstor.get_volume_openers(volume_uuid) 

            except Exception as e: 

                raise xs_errors.XenError( 

                    'VDIUnavailable', 

                    opterr='Unable to get DRBD openers to run vhd-util command `{}` (path={}): {}' 

                    .format(remote_method, device_path, e) 

                ) 

 

            no_host_found = True 

            for hostname, openers in all_openers.iteritems(): 

                if not openers: 

                    continue 

 

                try: 

                    host_ref = next(ref for ref, rec in hosts.iteritems() if rec['hostname'] == hostname) 

                except StopIteration: 

                    continue 

 

                no_host_found = False 

                try: 

                    return call_vhd_util_on_host(self._session, host_ref, remote_method, device_path, remote_args) 

                except Exception: 

                    pass 

 

            if no_host_found: 

                try: 

                    return local_method(device_path, *args, **kwargs) 

                except Exception as e: 

                    self._raise_openers_exception(device_path, e) 

 

            raise xs_errors.XenError( 

                'VDIUnavailable', 

                opterr='No valid host found to run vhd-util command `{}` (path=`{}`, openers=`{}`): {}' 

                .format(remote_method, device_path, openers, e) 

            ) 

        return util.retry(remote_call, 5, 2)