-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathblktap2.py
executable file
·2698 lines (2104 loc) · 81.6 KB
/
blktap2.py
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
#
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 syslog import openlog, syslog
from stat import * # S_ISBLK(), ...
import nfs
import resetvdis
import vhdutil
import lvhdutil
import VDI as sm
# For RRDD Plugin Registration
from xmlrpc.client import ServerProxy, Transport
from socket import socket, AF_UNIX, SOCK_STREAM
PLUGIN_TAP_PAUSE = "tapdisk-pause"
SOCKPATH = "/var/xapi/xcp-rrdd"
NUM_PAGES_PER_RING = 32 * 11
MAX_FULL_RINGS = 8
ENABLE_MULTIPLE_ATTACH = "/etc/xensource/allow_multiple_vdi_attach"
NO_MULTIPLE_ATTACH = not (os.path.exists(ENABLE_MULTIPLE_ATTACH))
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
def __str__(self):
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)
p.stdin.close()
except OSError as e:
raise cls.CommandFailure(cmd, errno=e.errno)
return cls(cmd, p)
def _errmsg(self):
output = map(str.rstrip, self._p.stderr)
return "; ".join(output)
def _wait(self, quiet=False):
"""
Reap the child tap-ctl process of this invocation.
Raises a TapCtl.CommandFailure on non-zero exit status.
"""
status = self._p.wait()
if not quiet:
util.SMlog(" = %d" % status)
if status == 0:
return
info = {'errmsg': self._errmsg(),
'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.stdout.readline().rstrip()
tapctl._wait(quiet)
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, True)
for stdout_line in tapctl.stdout:
# 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
tapctl._wait(True)
@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])
cls._pread(args)
@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)
class TapdiskExists(Exception):
"""Tapdisk already running."""
def __init__(self, tapdisk):
self.tapdisk = tapdisk
def __str__(self):
return "%s already running" % self.tapdisk
class TapdiskNotRunning(Exception):
"""No such Tapdisk."""
def __init__(self, **attrs):
self.attrs = attrs
def __str__(self):
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
def __str__(self):
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
def __str__(self):
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
def __str__(self):
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 = None
def sysfs_devname(self):
raise NotImplementedError("sysfs_devname is undefined")
class Attribute(object):
SYSFS_NODENAME = None
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
def __str__(self):
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'
TAP_MINOR_BASE = '/run/blktap-control/tapdisk'
SYSFS_CLASSTYPE = "blktap2"
def __init__(self, minor):
self.minor = minor
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)
def __str__(self):
return "%s(minor=%d)" % (self.__class__.__name__, self.minor)
def sysfs_devname(self):
return "blktap!blktap%d" % self.minor
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']
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
def __str__(self):
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 from_minor(cls, minor):
return cls.get(minor=minor)
@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
def __str__(self):
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
def __str__(self):
return "Not a Tapdisk type: %s" % self.type
class InvalidArgument(Exception):
def __init__(self, arg):
self.arg = arg
def __str__(self):
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)
@classmethod
def launch_on_tap(cls, blktap, path, _type, options):
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:
TapCtl.open(pid, minor, _type, path, options)
try:
return cls.__from_blktap(blktap)
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():
raise TapdiskInvalidState(self)
# FIXME: should the arguments be optional?
if _type is None:
_type = self.type
if path is None:
path = self.path
TapCtl.unpause(self.pid, self.minor, _type, path, mirror=mirror,
cbtlog=cbtlog)
self._set_dirty()
def stats(self):
return json.loads(TapCtl.stats(self.pid, self.minor))
#
# NB. dirty/refresh: reload attributes on next access
#
def _set_dirty(self):
self._dirty = True
def _refresh(self, __get):
t = self.from_minor(__get('minor'))
self.__init__(t.pid, t.minor, t.type, t.path, t.state)
def __getattribute__(self, name):
def __get(name):
# NB. avoid(rec(ursion)
return object.__getattribute__(self, name)
if __get('_dirty') and \
name in ['minor', 'type', 'path', 'state']:
self._refresh(__get)
self._dirty = False
return __get(name)
class PauseState:
RUNNING = 'R'
PAUSING = 'r'
PAUSED = 'P'
class Flags:
DEAD = 0x0001
CLOSED = 0x0002
QUIESCE_REQUESTED = 0x0004
QUIESCED = 0x0008
PAUSE_REQUESTED = 0x0010
PAUSED = 0x0020
SHUTDOWN_REQUESTED = 0x0040
LOCKING = 0x0080
RETRY_NEEDED = 0x0100
LOG_DROPPED = 0x0200
PAUSE_MASK = PAUSE_REQUESTED | PAUSED
def is_paused(self):
return not not (self.state & self.Flags.PAUSED)
def is_running(self):
return not (self.state & self.Flags.PAUSE_MASK)
def pause_state(self):
if self.state & self.Flags.PAUSED:
return self.PauseState.PAUSED
if self.state & self.Flags.PAUSE_REQUESTED:
return self.PauseState.PAUSING
return self.PauseState.RUNNING
@staticmethod
def _parse_minor(devpath):
regex = r'%s/tapdisk-(\d+)$' % Blktap.TAP_MINOR_BASE
pattern = re.compile(regex)
groups = pattern.search(devpath)
if not groups:
raise Exception("malformed tap device: '%s' (%s) " % (devpath, regex))
minor = int(groups.group(1))
return minor
_major = None
@classmethod
def major(cls):
if cls._major:
return cls._major
devices = open("/proc/devices")
for line in devices:
row = line.rstrip().split(' ')
if len(row) != 2:
continue
major, name = row
if name != 'tapdev':
continue
cls._major = int(major)
break
devices.close()
return cls._major
class VDI(object):
"""SR.vdi driver decorator for blktap2"""
CONF_KEY_ALLOW_CACHING = "vdi_allow_caching"
CONF_KEY_MODE_ON_BOOT = "vdi_on_boot"
CONF_KEY_CACHE_SR = "local_cache_sr"
CONF_KEY_O_DIRECT = "o_direct"
LOCK_CACHE_SETUP = "cachesetup"
ATTACH_DETACH_RETRY_SECS = 120
def __init__(self, uuid, target, driver_info):
self.target = self.TargetDriver(target, driver_info)
self._vdi_uuid = uuid
self._session = target.session
self.xenstore_data = scsiutil.update_XS_SCSIdata(uuid, scsiutil.gen_synthetic_page_data(uuid))
self.__o_direct = None
self.__o_direct_reason = None
self.lock = Lock("vdi", uuid)
self.tap = None
def get_o_direct_capability(self, options):
"""Returns True/False based on licensing and caching_params"""
if self.__o_direct is not None:
return self.__o_direct, self.__o_direct_reason
if util.read_caching_is_restricted(self._session):
self.__o_direct = True
self.__o_direct_reason = "LICENSE_RESTRICTION"
elif not ((self.target.vdi.sr.handles("nfs") or self.target.vdi.sr.handles("ext") or self.target.vdi.sr.handles("smb"))):
self.__o_direct = True
self.__o_direct_reason = "SR_NOT_SUPPORTED"
elif options.get("rdonly") and not self.target.vdi.parent:
self.__o_direct = True
self.__o_direct_reason = "RO_WITH_NO_PARENT"
elif options.get(self.CONF_KEY_O_DIRECT):
self.__o_direct = True
self.__o_direct_reason = "SR_OVERRIDE"
if self.__o_direct is None:
self.__o_direct = False
self.__o_direct_reason = ""
return self.__o_direct, self.__o_direct_reason
@classmethod
def from_cli(cls, uuid):
import VDI as sm