forked from xapi-project/sm
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathblktap2.py
More file actions
executable file
·3147 lines (2477 loc) · 97.3 KB
/
Copy pathblktap2.py
File metadata and controls
executable file
·3147 lines (2477 loc) · 97.3 KB
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
#!/usr/bin/python3
#
# 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
#
# blktap2: blktap/tapdisk management layer
#
from sm_typing import Any, Callable, ClassVar, Dict, override, List, Union
from abc import abstractmethod
import grp
import os
import re
import stat
import time
import copy
from lock import Lock
import util
import xmlrpc.client
import http.client
import errno
import signal
import subprocess
import syslog as _syslog
import glob
import json
import xs_errors
import XenAPI # pylint: disable=import-error
import scsiutil
from constants import NS_PREFIX_LVM
from syslog import openlog, syslog
from stat import * # S_ISBLK(), ...
from vditype import VdiType
import resetvdis
import VDI as sm
from cowutil import getCowUtil
# For RRDD Plugin Registration
from xmlrpc.client import ServerProxy, Transport
from socket import socket, AF_UNIX, SOCK_STREAM
try:
from linstorvolumemanager import get_controller_uri, get_all_volume_openers, LinstorVolumeManager
LINSTOR_AVAILABLE = True
except ImportError:
LINSTOR_AVAILABLE = False
PLUGIN_TAP_PAUSE = "tapdisk-pause"
PLUGIN_ON_SLAVE = "on-slave"
SOCKPATH = "/var/xapi/xcp-rrdd"
NUM_PAGES_PER_RING = 32 * 11
MAX_FULL_RINGS = 8
POOL_NAME_KEY = "mem-pool"
POOL_SIZE_KEY = "mem-pool-size-rings"
ENABLE_MULTIPLE_ATTACH = "/etc/xensource/allow_multiple_vdi_attach"
NO_MULTIPLE_ATTACH = not (os.path.exists(ENABLE_MULTIPLE_ATTACH))
# Including DRBD in the pattern to prevent matching with other SRs than LinstorSR
TAP_CTL_ERROR_PATTERN = re.compile(
r"(?P<status>ERROR|SUCCESS)\s"
r"\[(?P<code>-?[0-9]+)\s-\s(?P<category>.+?)]:\s"
r"(?P<message>.*)\sReason:\s(?P<reason>.+drbd.+)"
)
def locking(excType, override=True):
def locking2(op):
def wrapper(self, *args):
self.lock.acquire()
try:
try:
ret = op(self, * args)
except (util.CommandException, util.SMException, XenAPI.Failure) as e:
util.logException("BLKTAP2:%s" % op)
msg = str(e)
if isinstance(e, util.CommandException):
msg = "Command %s failed (%s): %s" % \
(e.cmd, e.code, e.reason)
if override:
raise xs_errors.XenError(excType, opterr=msg)
else:
raise
except:
util.logException("BLKTAP2:%s" % op)
raise
finally:
self.lock.release()
return ret
return wrapper
return locking2
class RetryLoop(object):
def __init__(self, backoff, limit):
self.backoff = backoff
self.limit = limit
def __call__(self, f):
def loop(*__t, **__d):
attempt = 0
while True:
attempt += 1
try:
return f( * __t, ** __d)
except self.TransientFailure as e:
e = e.exception
if attempt >= self.limit:
raise e
time.sleep(self.backoff)
return loop
class TransientFailure(Exception):
def __init__(self, exception):
self.exception = exception
def retried(**args):
return RetryLoop( ** args)
class TapCtl(object):
"""Tapdisk IPC utility calls."""
PATH = "/usr/sbin/tap-ctl"
def __init__(self, cmd, p):
self.cmd = cmd
self._p = p
self.stdout = p.stdout
class CommandFailure(Exception):
"""TapCtl cmd failure."""
def __init__(self, cmd, **info):
self.cmd = cmd
self.info = info
@override
def __str__(self) -> str:
items = self.info.items()
info = ", ".join("%s=%s" % item
for item in items)
return "%s failed: %s" % (self.cmd, info)
# Trying to get a non-existent attribute throws an AttributeError
# exception
def __getattr__(self, key):
if key in self.info:
return self.info[key]
return object.__getattribute__(self, key)
@property
def has_status(self):
return 'status' in self.info
@property
def has_signal(self):
return 'signal' in self.info
# Retrieves the error code returned by the command. If the error code
# was not supplied at object-construction time, zero is returned.
def get_error_code(self):
key = 'status'
if key in self.info:
return self.info[key]
else:
return 0
@classmethod
def __mkcmd_real(cls, args):
return [cls.PATH] + [str(x) for x in args]
__next_mkcmd = __mkcmd_real
@classmethod
def _mkcmd(cls, args):
__next_mkcmd = cls.__next_mkcmd
cls.__next_mkcmd = cls.__mkcmd_real
return __next_mkcmd(args)
@classmethod
def _call(cls, args, quiet=False, input=None, text_mode=True):
"""
Spawn a tap-ctl process. Return a TapCtl invocation.
Raises a TapCtl.CommandFailure if subprocess creation failed.
"""
cmd = cls._mkcmd(args)
if not quiet:
util.SMlog(cmd)
try:
p = subprocess.Popen(cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True,
universal_newlines=text_mode)
if input:
p.stdin.write(input)
except OSError as e:
raise cls.CommandFailure(cmd, errno=e.errno)
return cls(cmd, p)
def _errmsg(self, stderr):
output = map(str.rstrip, stderr)
return "; ".join(output)
def _wait(self, quiet=False, text_mode=True):
"""
Reap the child tap-ctl process of this invocation.
Raises a TapCtl.CommandFailure on non-zero exit status.
"""
stdout, stderr = self._p.communicate()
status = self._p.returncode
if not quiet:
util.SMlog(" = %d" % status)
if status == 0:
return stdout
info = {'errmsg': self._errmsg(
stderr if text_mode else stderr.decode()),
'pid': self._p.pid}
if status < 0:
info['signal'] = -status
else:
info['status'] = status
raise self.CommandFailure(self.cmd, ** info)
@classmethod
def _pread(cls, args, quiet=False, input=None, text_mode=True):
"""
Spawn a tap-ctl invocation and read a single line.
"""
tapctl = cls._call(args=args, quiet=quiet, input=input,
text_mode=text_mode)
output = tapctl._wait(quiet=quiet, text_mode=text_mode)
return output
@staticmethod
def _maybe(opt, parm):
if parm is not None:
return [opt, parm]
return []
@classmethod
def __list(cls, minor=None, pid=None, _type=None, path=None):
args = ["list"]
args += cls._maybe("-m", minor)
args += cls._maybe("-p", pid)
args += cls._maybe("-t", _type)
args += cls._maybe("-f", path)
tapctl = cls._call(args, quiet=True)
stdout = tapctl._wait(quiet=True)
for stdout_line in stdout.splitlines():
# FIXME: tap-ctl writes error messages to stdout and
# confuses this parser
if stdout_line == "blktap kernel module not installed\n":
# This isn't pretty but (a) neither is confusing stdout/stderr
# and at least causes the error to describe the fix
raise Exception("blktap kernel module not installed: try 'modprobe blktap'")
row = {}
for field in stdout_line.rstrip().split(' ', 3):
bits = field.split('=')
if len(bits) == 2:
key, val = field.split('=')
if key in ('pid', 'minor'):
row[key] = int(val, 10)
elif key in ('state'):
row[key] = int(val, 0x10)
else:
row[key] = val
else:
util.SMlog("Ignoring unexpected tap-ctl output: %s" % repr(field))
yield row
@classmethod
@retried(backoff=.5, limit=10)
def list(cls, **args):
# FIXME. We typically get an EPROTO when uevents interleave
# with SM ops and a tapdisk shuts down under our feet. Should
# be fixed in SM.
try:
return list(cls.__list( ** args))
except cls.CommandFailure as e:
transient = [errno.EPROTO, errno.ENOENT]
if e.has_status and e.status in transient:
raise RetryLoop.TransientFailure(e)
raise
@classmethod
def allocate(cls, devpath=None):
args = ["allocate"]
args += cls._maybe("-d", devpath)
return cls._pread(args)
@classmethod
def free(cls, minor):
args = ["free", "-m", minor]
cls._pread(args)
@classmethod
@retried(backoff=.5, limit=10)
def spawn(cls):
args = ["spawn"]
try:
pid = cls._pread(args)
return int(pid)
except cls.CommandFailure as ce:
# intermittent failures to spawn. CA-292268
if ce.status == 1:
raise RetryLoop.TransientFailure(ce)
raise
@classmethod
def attach(cls, pid, minor):
args = ["attach", "-p", pid, "-m", minor]
cls._pread(args)
@classmethod
def detach(cls, pid, minor):
args = ["detach", "-p", pid, "-m", minor]
cls._pread(args)
@classmethod
def _load_key(cls, key_hash, vdi_uuid):
import plugins
return plugins.load_key(key_hash, vdi_uuid)
@classmethod
def open(cls, pid, minor, _type, _file, options):
params = Tapdisk.Arg(_type, _file)
args = ["open", "-p", pid, "-m", minor, '-a', str(params)]
text_mode = True
input = None
if options.get("rdonly"):
args.append('-R')
if options.get("lcache"):
args.append("-r")
if options.get("existing_prt") is not None:
args.append("-e")
args.append(str(options["existing_prt"]))
if options.get("secondary"):
args.append("-2")
args.append(options["secondary"])
if options.get("standby"):
args.append("-s")
if options.get("timeout"):
args.append("-t")
args.append(str(options["timeout"]))
if not options.get("o_direct", True):
args.append("-D")
if options.get('cbtlog'):
args.extend(['-C', options['cbtlog']])
if options.get('key_hash'):
key_hash = options['key_hash']
vdi_uuid = options['vdi_uuid']
key = cls._load_key(key_hash, vdi_uuid)
if not key:
raise util.SMException("No key found with key hash {}".format(key_hash))
input = key
text_mode = False
args.append('-E')
cls._pread(args=args, input=input, text_mode=text_mode)
@classmethod
def close(cls, pid, minor, force=False):
args = ["close", "-p", pid, "-m", minor, "-t", "120"]
if force:
args += ["-f"]
cls._pread(args)
@classmethod
def pause(cls, pid, minor):
args = ["pause", "-p", pid, "-m", minor]
cls._pread(args)
@classmethod
def unpause(cls, pid, minor, _type=None, _file=None, mirror=None,
cbtlog=None):
args = ["unpause", "-p", pid, "-m", minor]
if mirror:
args.extend(["-2", mirror])
if _type and _file:
params = Tapdisk.Arg(_type, _file)
args += ["-a", str(params)]
if cbtlog:
args.extend(["-c", cbtlog])
@retried(backoff=.5, limit=3)
def unpause_impl():
drbd_path = _file
try:
cls._pread(args)
except TapCtl.CommandFailure as e:
match = TAP_CTL_ERROR_PATTERN.search(e.info.get("errmsg", ""))
if match and match.group("reason"):
drbd_path = match.group("reason")
if e.get_error_code() in (errno.EROFS, errno.EMEDIUMTYPE) and Tapdisk.abort_linstor_gc(drbd_path):
raise RetryLoop.TransientFailure(e)
raise
unpause_impl()
@classmethod
def shutdown(cls, pid):
# TODO: This should be a real tap-ctl command
os.kill(pid, signal.SIGTERM)
os.waitpid(pid, 0)
@classmethod
def stats(cls, pid, minor):
args = ["stats", "-p", pid, "-m", minor]
return cls._pread(args, quiet=True)
@classmethod
def major(cls):
args = ["major"]
major = cls._pread(args)
return int(major)
@classmethod
def commit(cls, pid, minor, vdi_type, path):
args = ["commit", "-p", pid, "-m", minor, "-a", path]
cls._pread(args)
@classmethod
def query(cls, pid, minor, quiet=False):
args = ["query", "-p", pid, "-m", minor]
output = cls._pread(args, quiet=quiet)
m = re.match(r"Commit status '(.+)' \((\d+)\/(\d+)\)", output)
status = m.group(1)
coalesced = int(m.group(2))
total_coalesce = int(m.group(3))
return (status, coalesced, total_coalesce)
@classmethod
def cancel_commit(cls, pid, minor, wait=True):
args = ["cancel", "-p", pid, "-m", minor]
if wait:
args.append("-w")
cls._pread(args)
class TapdiskExists(Exception):
"""Tapdisk already running."""
def __init__(self, tapdisk):
self.tapdisk = tapdisk
@override
def __str__(self) -> str:
return "%s already running" % self.tapdisk
class TapdiskNotRunning(Exception):
"""No such Tapdisk."""
def __init__(self, **attrs):
self.attrs = attrs
@override
def __str__(self) -> str:
items = iter(self.attrs.items())
attrs = ", ".join("%s=%s" % attr
for attr in items)
return "No such Tapdisk(%s)" % attrs
class TapdiskNotUnique(Exception):
"""More than one tapdisk on one path."""
def __init__(self, tapdisks):
self.tapdisks = tapdisks
@override
def __str__(self) -> str:
tapdisks = map(str, self.tapdisks)
return "Found multiple tapdisks: %s" % tapdisks
class TapdiskFailed(Exception):
"""Tapdisk launch failure."""
def __init__(self, arg, err):
self.arg = arg
self.err = err
@override
def __str__(self) -> str:
return "Tapdisk(%s): %s" % (self.arg, self.err)
def get_error(self):
return self.err
class TapdiskInvalidState(Exception):
"""Tapdisk pause/unpause failure"""
def __init__(self, tapdisk):
self.tapdisk = tapdisk
@override
def __str__(self) -> str:
return str(self.tapdisk)
def mkdirs(path, mode=0o777):
if not os.path.exists(path):
parent, subdir = os.path.split(path)
assert parent != path
try:
if parent:
mkdirs(parent, mode)
if subdir:
os.mkdir(path, mode)
except OSError as e:
if e.errno != errno.EEXIST:
raise
class KObject(object):
SYSFS_CLASSTYPE: ClassVar[str] = ""
@abstractmethod
def sysfs_devname(self) -> str:
pass
class Attribute(object):
SYSFS_NODENAME: ClassVar[str] = ""
def __init__(self, path):
self.path = path
@classmethod
def from_kobject(cls, kobj):
path = "%s/%s" % (kobj.sysfs_path(), cls.SYSFS_NODENAME)
return cls(path)
class NoSuchAttribute(Exception):
def __init__(self, name):
self.name = name
@override
def __str__(self) -> str:
return "No such attribute: %s" % self.name
def _open(self, mode='r'):
try:
return open(self.path, mode)
except IOError as e:
if e.errno == errno.ENOENT:
raise self.NoSuchAttribute(self)
raise
def readline(self):
f = self._open('r')
s = f.readline().rstrip()
f.close()
return s
def writeline(self, val):
f = self._open('w')
f.write(val)
f.close()
class ClassDevice(KObject):
@classmethod
def sysfs_class_path(cls):
return "/sys/class/%s" % cls.SYSFS_CLASSTYPE
def sysfs_path(self):
return "%s/%s" % (self.sysfs_class_path(),
self.sysfs_devname())
class Blktap(ClassDevice):
DEV_BASEDIR = '/dev/xen/blktap-2'
SYSFS_CLASSTYPE = "blktap2"
def __init__(self, minor):
self.minor = minor
self._pool = None
self._task = None
@classmethod
def allocate(cls):
# FIXME. Should rather go into init.
mkdirs(cls.DEV_BASEDIR)
devname = TapCtl.allocate()
minor = Tapdisk._parse_minor(devname)
return cls(minor)
def free(self):
TapCtl.free(self.minor)
@override
def __str__(self) -> str:
return "%s(minor=%d)" % (self.__class__.__name__, self.minor)
@override
def sysfs_devname(self) -> str:
return "blktap!blktap%d" % self.minor
class Pool(Attribute):
SYSFS_NODENAME = "pool"
def get_pool_attr(self):
if not self._pool:
self._pool = self.Pool.from_kobject(self)
return self._pool
def get_pool_name(self):
return self.get_pool_attr().readline()
def set_pool_name(self, name):
self.get_pool_attr().writeline(name)
def set_pool_size(self, pages):
self.get_pool().set_size(pages)
def get_pool(self):
return BlktapControl.get_pool(self.get_pool_name())
def set_pool(self, pool):
self.set_pool_name(pool.name)
class Task(Attribute):
SYSFS_NODENAME = "task"
def get_task_attr(self):
if not self._task:
self._task = self.Task.from_kobject(self)
return self._task
def get_task_pid(self):
pid = self.get_task_attr().readline()
try:
return int(pid)
except ValueError:
return None
def find_tapdisk(self):
pid = self.get_task_pid()
if pid is None:
return None
return Tapdisk.find(pid=pid, minor=self.minor)
def get_tapdisk(self):
tapdisk = self.find_tapdisk()
if not tapdisk:
raise TapdiskNotRunning(minor=self.minor)
return tapdisk
class Tapdisk(object):
TYPES = ['aio', 'vhd', 'qcow2']
def __init__(self, pid, minor, _type, path, state):
self.pid = pid
self.minor = minor
self.type = _type
self.path = path
self.state = state
self._dirty = False
self._blktap = None
@override
def __str__(self) -> str:
state = self.pause_state()
return "Tapdisk(%s, pid=%d, minor=%s, state=%s)" % \
(self.get_arg(), self.pid, self.minor, state)
@classmethod
def list(cls, **args):
for row in TapCtl.list( ** args):
args = {'pid': None,
'minor': None,
'state': None,
'_type': None,
'path': None}
for key, val in row.items():
if key in args:
args[key] = val
if 'args' in row:
image = Tapdisk.Arg.parse(row['args'])
args['_type'] = image.type
args['path'] = image.path
if None in args.values():
continue
yield Tapdisk( ** args)
@classmethod
def find(cls, **args):
found = list(cls.list( ** args))
if len(found) > 1:
raise TapdiskNotUnique(found)
if found:
return found[0]
return None
@classmethod
def find_by_path(cls, path):
return cls.find(path=path)
@classmethod
def find_by_minor(cls, minor):
return cls.find(minor=minor)
@classmethod
def get(cls, **attrs):
tapdisk = cls.find( ** attrs)
if not tapdisk:
raise TapdiskNotRunning( ** attrs)
return tapdisk
@classmethod
def from_path(cls, path):
return cls.get(path=path)
@classmethod
def get_pid_for_path(cls, path: str) -> str:
return util.pread2(['/usr/sbin/lsof', '-t', path]).strip()
@classmethod
def from_minor(cls, minor):
pid = None
dev_path = os.path.join(Blktap.DEV_BASEDIR, f"blktap{minor}")
if os.path.exists(dev_path):
pid = cls.get_pid_for_path(dev_path)
return cls.get(minor=minor, pid=pid)
@classmethod
def __from_blktap(cls, blktap):
tapdisk = cls.from_minor(minor=blktap.minor)
tapdisk._blktap = blktap
return tapdisk
def get_blktap(self):
if not self._blktap:
self._blktap = Blktap(self.minor)
return self._blktap
class Arg:
def __init__(self, _type, path):
self.type = _type
self.path = path
@override
def __str__(self) -> str:
return "%s:%s" % (self.type, self.path)
@classmethod
def parse(cls, arg):
try:
_type, path = arg.split(":", 1)
except ValueError:
raise cls.InvalidArgument(arg)
if _type not in Tapdisk.TYPES:
raise cls.InvalidType(_type)
return cls(_type, path)
class InvalidType(Exception):
def __init__(self, _type):
self.type = _type
@override
def __str__(self) -> str:
return "Not a Tapdisk type: %s" % self.type
class InvalidArgument(Exception):
def __init__(self, arg):
self.arg = arg
@override
def __str__(self) -> str:
return "Not a Tapdisk image: %s" % self.arg
def get_arg(self):
return self.Arg(self.type, self.path)
def get_devpath(self):
return "%s/tapdev%d" % (Blktap.DEV_BASEDIR, self.minor)
@classmethod
def launch_from_arg(cls, arg):
arg = cls.Arg.parse(arg)
return cls.launch(arg.path, arg.type, False)
@staticmethod
def cgclassify(pid):
# We dont provide any <controllers>:<path>
# so cgclassify uses /etc/cgrules.conf which
# we have configured in the spec file.
cmd = ["cgclassify", str(pid)]
try:
util.pread2(cmd)
except util.CommandException as e:
util.logException(e)
@staticmethod
def abort_linstor_gc(drbd_path: str) -> bool:
if not LINSTOR_AVAILABLE or not drbd_path.startswith("/dev/drbd/by-res/xcp-volume-"):
return False
_, volume_name, _ = drbd_path.rsplit("/", 2)
group_name = LinstorVolumeManager.get_volume_group_name(volume_name)
openers = get_all_volume_openers(volume_name, "0")
api_session = util.timeout(5, util.ApiSession, "SM-blktap2-abort_linstor_gc")
try:
srs = util.get_linstor_srs_uuid(api_session.session)
pbd_ref = util.find_pbd_ref_from_dconf_value(
api_session.session, srs, "group-name", group_name,
LinstorVolumeManager.build_group_name,
)
if pbd_ref:
pbd_rec = api_session.session.xenapi.PBD.get_record(pbd_ref)
sr_ref = pbd_rec["SR"]
sr_uuid = api_session.session.xenapi.SR.get_uuid(sr_ref)
import cleanup # pylint: disable=C0415
if cleanup.LinstorSR.abort_gc_from_openers_sr(sr_uuid, openers):
return True
else:
util.SMlog(f"Unable to find PBD of LINSTOR group `{group_name}`...")
util.SMlog(f"Unable to run tapdisk, openers of DRBD resource `{drbd_path}`: {openers}")
finally:
api_session.logout()
return False
@classmethod
def launch_on_tap(cls, blktap, path, _type, options):
drbd_path = path
tapdisk = cls.find_by_path(path)
if tapdisk:
raise TapdiskExists(tapdisk)
minor = blktap.minor
try:
pid = TapCtl.spawn()
cls.cgclassify(pid)
try:
TapCtl.attach(pid, minor)
try:
retry_open = 0
while True:
try:
TapCtl.open(pid, minor, _type, path, options)
break
except TapCtl.CommandFailure as e:
err = e.get_error_code()
match = TAP_CTL_ERROR_PATTERN.search(e.info.get("errmsg", ""))
if match and match.group("reason"):
drbd_path = match.group("reason")
if err in (errno.EROFS, errno.EMEDIUMTYPE) and cls.abort_linstor_gc(drbd_path):
continue
if err in (errno.EIO, errno.EAGAIN, errno.EROFS, errno.EMEDIUMTYPE) and retry_open < 1:
retry_open += 1
time.sleep(1)
continue
raise
try:
tapdisk = cls.__from_blktap(blktap)
node = '/sys/dev/block/%d:%d' % (tapdisk.major(), tapdisk.minor)
util.set_scheduler_sysfs_node(node, ['none', 'noop'])
return tapdisk
except:
TapCtl.close(pid, minor)
raise
except:
TapCtl.detach(pid, minor)
raise
except:
try:
TapCtl.shutdown(pid)
except:
# Best effort to shutdown
pass
raise
except TapCtl.CommandFailure as ctl:
util.logException(ctl)
if ((path.startswith('/dev/xapi/cd/') or path.startswith('/dev/sr')) and
ctl.has_status and ctl.get_error_code() == 123): # ENOMEDIUM (No medium found)
raise xs_errors.XenError('TapdiskDriveEmpty')
else:
raise TapdiskFailed(cls.Arg(_type, path), ctl)
@classmethod
def launch(cls, path, _type, rdonly):
blktap = Blktap.allocate()
try:
return cls.launch_on_tap(blktap, path, _type, {"rdonly": rdonly})
except:
blktap.free()
raise
def shutdown(self, force=False):
TapCtl.close(self.pid, self.minor, force)
TapCtl.detach(self.pid, self.minor)
self.get_blktap().free()
def pause(self):
if not self.is_running():
raise TapdiskInvalidState(self)
TapCtl.pause(self.pid, self.minor)
self._set_dirty()
def unpause(self, _type=None, path=None, mirror=None, cbtlog=None):
if not self.is_paused():