-
Notifications
You must be signed in to change notification settings - Fork 91
/
LVHDSR.py
executable file
·2249 lines (1963 loc) · 95.8 KB
/
LVHDSR.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
#
# LVHDSR: VHD on LVM storage repository
#
import SR
from SR import deviceCheck
import VDI
import SRCommand
import util
import lvutil
import lvmcache
import vhdutil
import lvhdutil
import scsiutil
import os
import sys
import time
import errno
import xs_errors
import cleanup
import blktap2
from journaler import Journaler
from lock import Lock
from refcounter import RefCounter
from ipc import IPCFlag
from lvmanager import LVActivator
import XenAPI # pylint: disable=import-error
import re
from srmetadata import ALLOCATION_TAG, NAME_LABEL_TAG, NAME_DESCRIPTION_TAG, \
UUID_TAG, IS_A_SNAPSHOT_TAG, SNAPSHOT_OF_TAG, TYPE_TAG, VDI_TYPE_TAG, \
READ_ONLY_TAG, MANAGED_TAG, SNAPSHOT_TIME_TAG, METADATA_OF_POOL_TAG, \
LVMMetadataHandler, METADATA_OBJECT_TYPE_VDI, \
METADATA_OBJECT_TYPE_SR, METADATA_UPDATE_OBJECT_TYPE_TAG
from metadata import retrieveXMLfromFile, _parseXML
from xmlrpc.client import DateTime
import glob
from constants import CBTLOG_TAG
from fairlock import Fairlock
DEV_MAPPER_ROOT = os.path.join('/dev/mapper', lvhdutil.VG_PREFIX)
geneology = {}
CAPABILITIES = ["SR_PROBE", "SR_UPDATE", "SR_TRIM",
"VDI_CREATE", "VDI_DELETE", "VDI_ATTACH", "VDI_DETACH", "VDI_MIRROR",
"VDI_CLONE", "VDI_SNAPSHOT", "VDI_RESIZE", "ATOMIC_PAUSE",
"VDI_RESET_ON_BOOT/2", "VDI_UPDATE", "VDI_CONFIG_CBT",
"VDI_ACTIVATE", "VDI_DEACTIVATE"]
CONFIGURATION = [['device', 'local device path (required) (e.g. /dev/sda3)']]
DRIVER_INFO = {
'name': 'Local VHD on LVM',
'description': 'SR plugin which represents disks as VHD disks on ' + \
'Logical Volumes within a locally-attached Volume Group',
'vendor': 'XenSource Inc',
'copyright': '(C) 2008 XenSource Inc',
'driver_version': '1.0',
'required_api_version': '1.0',
'capabilities': CAPABILITIES,
'configuration': CONFIGURATION
}
PARAM_VHD = "vhd"
PARAM_RAW = "raw"
OPS_EXCLUSIVE = [
"sr_create", "sr_delete", "sr_attach", "sr_detach", "sr_scan",
"sr_update", "vdi_create", "vdi_delete", "vdi_resize", "vdi_snapshot",
"vdi_clone"]
# Log if snapshot pauses VM for more than this many seconds
LONG_SNAPTIME = 60
class LVHDSR(SR.SR):
DRIVER_TYPE = 'lvhd'
PROVISIONING_TYPES = ["thin", "thick"]
PROVISIONING_DEFAULT = "thick"
THIN_PLUGIN = "lvhd-thin"
PLUGIN_ON_SLAVE = "on-slave"
FLAG_USE_VHD = "use_vhd"
MDVOLUME_NAME = "MGT"
ALLOCATION_QUANTUM = "allocation_quantum"
INITIAL_ALLOCATION = "initial_allocation"
LOCK_RETRY_INTERVAL = 3
LOCK_RETRY_ATTEMPTS = 10
TEST_MODE_KEY = "testmode"
TEST_MODE_VHD_FAIL_REPARENT_BEGIN = "vhd_fail_reparent_begin"
TEST_MODE_VHD_FAIL_REPARENT_LOCATOR = "vhd_fail_reparent_locator"
TEST_MODE_VHD_FAIL_REPARENT_END = "vhd_fail_reparent_end"
TEST_MODE_VHD_FAIL_RESIZE_BEGIN = "vhd_fail_resize_begin"
TEST_MODE_VHD_FAIL_RESIZE_DATA = "vhd_fail_resize_data"
TEST_MODE_VHD_FAIL_RESIZE_METADATA = "vhd_fail_resize_metadata"
TEST_MODE_VHD_FAIL_RESIZE_END = "vhd_fail_resize_end"
ENV_VAR_VHD_TEST = {
TEST_MODE_VHD_FAIL_REPARENT_BEGIN:
"VHD_UTIL_TEST_FAIL_REPARENT_BEGIN",
TEST_MODE_VHD_FAIL_REPARENT_LOCATOR:
"VHD_UTIL_TEST_FAIL_REPARENT_LOCATOR",
TEST_MODE_VHD_FAIL_REPARENT_END:
"VHD_UTIL_TEST_FAIL_REPARENT_END",
TEST_MODE_VHD_FAIL_RESIZE_BEGIN:
"VHD_UTIL_TEST_FAIL_RESIZE_BEGIN",
TEST_MODE_VHD_FAIL_RESIZE_DATA:
"VHD_UTIL_TEST_FAIL_RESIZE_DATA_MOVED",
TEST_MODE_VHD_FAIL_RESIZE_METADATA:
"VHD_UTIL_TEST_FAIL_RESIZE_METADATA_MOVED",
TEST_MODE_VHD_FAIL_RESIZE_END:
"VHD_UTIL_TEST_FAIL_RESIZE_END"
}
testMode = ""
legacyMode = True
def handles(type):
"""Returns True if this SR class understands the given dconf string"""
# we can pose as LVMSR or EXTSR for compatibility purposes
if __name__ == '__main__':
name = sys.argv[0]
else:
name = __name__
if name.endswith("LVMSR"):
return type == "lvm"
elif name.endswith("EXTSR"):
return type == "ext"
return type == LVHDSR.DRIVER_TYPE
handles = staticmethod(handles)
def load(self, sr_uuid):
self.ops_exclusive = OPS_EXCLUSIVE
self.isMaster = False
if 'SRmaster' in self.dconf and self.dconf['SRmaster'] == 'true':
self.isMaster = True
self.lock = Lock(vhdutil.LOCK_TYPE_SR, self.uuid)
self.sr_vditype = SR.DEFAULT_TAP
self.uuid = sr_uuid
self.vgname = lvhdutil.VG_PREFIX + self.uuid
self.path = os.path.join(lvhdutil.VG_LOCATION, self.vgname)
self.mdpath = os.path.join(self.path, self.MDVOLUME_NAME)
self.provision = self.PROVISIONING_DEFAULT
try:
self.lvmCache = lvmcache.LVMCache(self.vgname)
except:
raise xs_errors.XenError('SRUnavailable', \
opterr='Failed to initialise the LVMCache')
self.lvActivator = LVActivator(self.uuid, self.lvmCache)
self.journaler = Journaler(self.lvmCache)
if not self.srcmd.params.get("sr_ref"):
return # must be a probe call
# Test for thick vs thin provisioning conf parameter
if 'allocation' in self.dconf:
if self.dconf['allocation'] in self.PROVISIONING_TYPES:
self.provision = self.dconf['allocation']
else:
raise xs_errors.XenError('InvalidArg', \
opterr='Allocation parameter must be one of %s' % self.PROVISIONING_TYPES)
self.other_conf = self.session.xenapi.SR.get_other_config(self.sr_ref)
if self.other_conf.get(self.TEST_MODE_KEY):
self.testMode = self.other_conf[self.TEST_MODE_KEY]
self._prepareTestMode()
self.sm_config = self.session.xenapi.SR.get_sm_config(self.sr_ref)
# sm_config flag overrides PBD, if any
if self.sm_config.get('allocation') in self.PROVISIONING_TYPES:
self.provision = self.sm_config.get('allocation')
if self.sm_config.get(self.FLAG_USE_VHD) == "true":
self.legacyMode = False
if lvutil._checkVG(self.vgname):
if self.isMaster and not self.cmd in ["vdi_attach", "vdi_detach",
"vdi_activate", "vdi_deactivate"]:
self._undoAllJournals()
if not self.cmd in ["sr_attach", "sr_probe"]:
self._checkMetadataVolume()
self.mdexists = False
# get a VDI -> TYPE map from the storage
contains_uuid_regex = \
re.compile("^.*[0-9a-f]{8}-(([0-9a-f]{4})-){3}[0-9a-f]{12}.*")
self.storageVDIs = {}
for key in self.lvmCache.lvs.keys():
# if the lvname has a uuid in it
type = None
if contains_uuid_regex.search(key) is not None:
if key.startswith(lvhdutil.LV_PREFIX[vhdutil.VDI_TYPE_VHD]):
type = vhdutil.VDI_TYPE_VHD
vdi = key[len(lvhdutil.LV_PREFIX[type]):]
elif key.startswith(lvhdutil.LV_PREFIX[vhdutil.VDI_TYPE_RAW]):
type = vhdutil.VDI_TYPE_RAW
vdi = key[len(lvhdutil.LV_PREFIX[type]):]
else:
continue
if type is not None:
self.storageVDIs[vdi] = type
# check if metadata volume exists
try:
self.mdexists = self.lvmCache.checkLV(self.MDVOLUME_NAME)
except:
pass
def cleanup(self):
# we don't need to hold the lock to dec refcounts of activated LVs
if not self.lvActivator.deactivateAll():
raise util.SMException("failed to deactivate LVs")
def updateSRMetadata(self, allocation):
try:
# Add SR specific SR metadata
sr_info = \
{ALLOCATION_TAG: allocation,
UUID_TAG: self.uuid,
NAME_LABEL_TAG: util.to_plain_string(self.session.xenapi.SR.get_name_label(self.sr_ref)),
NAME_DESCRIPTION_TAG: util.to_plain_string(self.session.xenapi.SR.get_name_description(self.sr_ref))
}
vdi_info = {}
for vdi in self.session.xenapi.SR.get_VDIs(self.sr_ref):
vdi_uuid = self.session.xenapi.VDI.get_uuid(vdi)
# Create the VDI entry in the SR metadata
vdi_info[vdi_uuid] = \
{
UUID_TAG: vdi_uuid,
NAME_LABEL_TAG: util.to_plain_string(self.session.xenapi.VDI.get_name_label(vdi)),
NAME_DESCRIPTION_TAG: util.to_plain_string(self.session.xenapi.VDI.get_name_description(vdi)),
IS_A_SNAPSHOT_TAG: \
int(self.session.xenapi.VDI.get_is_a_snapshot(vdi)),
SNAPSHOT_OF_TAG: \
self.session.xenapi.VDI.get_snapshot_of(vdi),
SNAPSHOT_TIME_TAG: \
self.session.xenapi.VDI.get_snapshot_time(vdi),
TYPE_TAG: \
self.session.xenapi.VDI.get_type(vdi),
VDI_TYPE_TAG: \
self.session.xenapi.VDI.get_sm_config(vdi)['vdi_type'],
READ_ONLY_TAG: \
int(self.session.xenapi.VDI.get_read_only(vdi)),
METADATA_OF_POOL_TAG: \
self.session.xenapi.VDI.get_metadata_of_pool(vdi),
MANAGED_TAG: \
int(self.session.xenapi.VDI.get_managed(vdi))
}
LVMMetadataHandler(self.mdpath).writeMetadata(sr_info, vdi_info)
except Exception as e:
raise xs_errors.XenError('MetadataError', \
opterr='Error upgrading SR Metadata: %s' % str(e))
def syncMetadataAndStorage(self):
try:
# if a VDI is present in the metadata but not in the storage
# then delete it from the metadata
vdi_info = LVMMetadataHandler(self.mdpath, False).getMetadata()[1]
for vdi in list(vdi_info.keys()):
update_map = {}
if not vdi_info[vdi][UUID_TAG] in set(self.storageVDIs.keys()):
# delete this from metadata
LVMMetadataHandler(self.mdpath). \
deleteVdiFromMetadata(vdi_info[vdi][UUID_TAG])
else:
# search for this in the metadata, compare types
# self.storageVDIs is a map of vdi_uuid to vdi_type
if vdi_info[vdi][VDI_TYPE_TAG] != \
self.storageVDIs[vdi_info[vdi][UUID_TAG]]:
# storage type takes authority
update_map[METADATA_UPDATE_OBJECT_TYPE_TAG] \
= METADATA_OBJECT_TYPE_VDI
update_map[UUID_TAG] = vdi_info[vdi][UUID_TAG]
update_map[VDI_TYPE_TAG] = \
self.storageVDIs[vdi_info[vdi][UUID_TAG]]
LVMMetadataHandler(self.mdpath) \
.updateMetadata(update_map)
else:
# This should never happen
pass
except Exception as e:
raise xs_errors.XenError('MetadataError', \
opterr='Error synching SR Metadata and storage: %s' % str(e))
def syncMetadataAndXapi(self):
try:
# get metadata
(sr_info, vdi_info) = \
LVMMetadataHandler(self.mdpath, False).getMetadata()
# First synch SR parameters
self.update(self.uuid)
# Now update the VDI information in the metadata if required
for vdi_offset in vdi_info.keys():
try:
vdi_ref = \
self.session.xenapi.VDI.get_by_uuid( \
vdi_info[vdi_offset][UUID_TAG])
except:
# may be the VDI is not in XAPI yet dont bother
continue
new_name_label = util.to_plain_string(self.session.xenapi.VDI.get_name_label(vdi_ref))
new_name_description = util.to_plain_string(self.session.xenapi.VDI.get_name_description(vdi_ref))
if vdi_info[vdi_offset][NAME_LABEL_TAG] != new_name_label or \
vdi_info[vdi_offset][NAME_DESCRIPTION_TAG] != \
new_name_description:
update_map = {}
update_map[METADATA_UPDATE_OBJECT_TYPE_TAG] = \
METADATA_OBJECT_TYPE_VDI
update_map[UUID_TAG] = vdi_info[vdi_offset][UUID_TAG]
update_map[NAME_LABEL_TAG] = new_name_label
update_map[NAME_DESCRIPTION_TAG] = new_name_description
LVMMetadataHandler(self.mdpath) \
.updateMetadata(update_map)
except Exception as e:
raise xs_errors.XenError('MetadataError', \
opterr='Error synching SR Metadata and XAPI: %s' % str(e))
def _checkMetadataVolume(self):
util.SMlog("Entering _checkMetadataVolume")
self.mdexists = self.lvmCache.checkLV(self.MDVOLUME_NAME)
if self.isMaster:
if self.mdexists and self.cmd == "sr_attach":
try:
# activate the management volume
# will be deactivated at detach time
self.lvmCache.activateNoRefcount(self.MDVOLUME_NAME)
self._synchSmConfigWithMetaData()
util.SMlog("Sync SR metadata and the state on the storage.")
self.syncMetadataAndStorage()
self.syncMetadataAndXapi()
except Exception as e:
util.SMlog("Exception in _checkMetadataVolume, " \
"Error: %s." % str(e))
elif not self.mdexists and not self.legacyMode:
self._introduceMetaDataVolume()
if self.mdexists:
self.legacyMode = False
def _synchSmConfigWithMetaData(self):
util.SMlog("Synching sm-config with metadata volume")
try:
# get SR info from metadata
sr_info = {}
map = {}
sr_info = LVMMetadataHandler(self.mdpath, False).getMetadata()[0]
if sr_info == {}:
raise Exception("Failed to get SR information from metadata.")
if "allocation" in sr_info:
self.provision = sr_info.get("allocation")
map['allocation'] = sr_info.get("allocation")
else:
raise Exception("Allocation key not found in SR metadata. "
"SR info found: %s" % sr_info)
except Exception as e:
raise xs_errors.XenError(
'MetadataError',
opterr='Error reading SR params from '
'metadata Volume: %s' % str(e))
try:
map[self.FLAG_USE_VHD] = 'true'
self.session.xenapi.SR.set_sm_config(self.sr_ref, map)
except:
raise xs_errors.XenError(
'MetadataError',
opterr='Error updating sm_config key')
def _introduceMetaDataVolume(self):
util.SMlog("Creating Metadata volume")
try:
config = {}
self.lvmCache.create(self.MDVOLUME_NAME, 4 * 1024 * 1024)
# activate the management volume, will be deactivated at detach time
self.lvmCache.activateNoRefcount(self.MDVOLUME_NAME)
name_label = util.to_plain_string( \
self.session.xenapi.SR.get_name_label(self.sr_ref))
name_description = util.to_plain_string( \
self.session.xenapi.SR.get_name_description(self.sr_ref))
config[self.FLAG_USE_VHD] = "true"
config['allocation'] = self.provision
self.session.xenapi.SR.set_sm_config(self.sr_ref, config)
# Add the SR metadata
self.updateSRMetadata(self.provision)
except Exception as e:
raise xs_errors.XenError('MetadataError', \
opterr='Error introducing Metadata Volume: %s' % str(e))
def _removeMetadataVolume(self):
if self.mdexists:
try:
self.lvmCache.remove(self.MDVOLUME_NAME)
except:
raise xs_errors.XenError('MetadataError', \
opterr='Failed to delete MGT Volume')
def _refresh_size(self):
"""
Refreshs the size of the backing device.
Return true if all paths/devices agree on the same size.
"""
if hasattr(self, 'SCSIid'):
# LVHDoHBASR, LVHDoISCSISR
return scsiutil.refresh_lun_size_by_SCSIid(getattr(self, 'SCSIid'))
else:
# LVHDSR
devices = self.dconf['device'].split(',')
scsiutil.refreshdev(devices)
return True
def _expand_size(self):
"""
Expands the size of the SR by growing into additional availiable
space, if extra space is availiable on the backing device.
Needs to be called after a successful call of _refresh_size.
"""
currentvgsize = lvutil._getVGstats(self.vgname)['physical_size']
# We are comparing PV- with VG-sizes that are aligned. Need a threshold
resizethreshold = 100 * 1024 * 1024 # 100MB
devices = self.dconf['device'].split(',')
totaldevicesize = 0
for device in devices:
totaldevicesize = totaldevicesize + scsiutil.getsize(device)
if totaldevicesize >= (currentvgsize + resizethreshold):
try:
if hasattr(self, 'SCSIid'):
# LVHDoHBASR, LVHDoISCSISR might have slaves
scsiutil.refresh_lun_size_by_SCSIid_on_slaves(self.session,
getattr(self, 'SCSIid'))
util.SMlog("LVHDSR._expand_size for %s will resize the pv." %
self.uuid)
for pv in lvutil.get_pv_for_vg(self.vgname):
lvutil.resizePV(pv)
except:
util.logException("LVHDSR._expand_size for %s failed to resize"
" the PV" % self.uuid)
@deviceCheck
def create(self, uuid, size):
util.SMlog("LVHDSR.create for %s" % self.uuid)
if not self.isMaster:
util.SMlog('sr_create blocked for non-master')
raise xs_errors.XenError('LVMMaster')
if lvutil._checkVG(self.vgname):
raise xs_errors.XenError('SRExists')
# Check none of the devices already in use by other PBDs
if util.test_hostPBD_devs(self.session, uuid, self.dconf['device']):
raise xs_errors.XenError('SRInUse')
# Check serial number entry in SR records
for dev in self.dconf['device'].split(','):
if util.test_scsiserial(self.session, dev):
raise xs_errors.XenError('SRInUse')
lvutil.createVG(self.dconf['device'], self.vgname)
#Update serial number string
scsiutil.add_serial_record(self.session, self.sr_ref, \
scsiutil.devlist_to_serialstring(self.dconf['device'].split(',')))
# since this is an SR.create turn off legacy mode
self.session.xenapi.SR.add_to_sm_config(self.sr_ref, \
self.FLAG_USE_VHD, 'true')
def delete(self, uuid):
util.SMlog("LVHDSR.delete for %s" % self.uuid)
if not self.isMaster:
raise xs_errors.XenError('LVMMaster')
cleanup.gc_force(self.session, self.uuid)
success = True
for fileName in glob.glob(DEV_MAPPER_ROOT + '*'):
if util.extractSRFromDevMapper(fileName) != self.uuid:
continue
if util.doesFileHaveOpenHandles(fileName):
util.SMlog("LVHDSR.delete: The dev mapper entry %s has open " \
"handles" % fileName)
success = False
continue
# Now attempt to remove the dev mapper entry
if not lvutil.removeDevMapperEntry(fileName, False):
success = False
continue
try:
lvname = os.path.basename(fileName.replace('-', '/'). \
replace('//', '-'))
lpath = os.path.join(self.path, lvname)
os.unlink(lpath)
except OSError as e:
if e.errno != errno.ENOENT:
util.SMlog("LVHDSR.delete: failed to remove the symlink for " \
"file %s. Error: %s" % (fileName, str(e)))
success = False
if success:
try:
if util.pathexists(self.path):
os.rmdir(self.path)
except Exception as e:
util.SMlog("LVHDSR.delete: failed to remove the symlink " \
"directory %s. Error: %s" % (self.path, str(e)))
success = False
self._removeMetadataVolume()
self.lvmCache.refresh()
if len(lvhdutil.getLVInfo(self.lvmCache)) > 0:
raise xs_errors.XenError('SRNotEmpty')
if not success:
raise Exception("LVHDSR delete failed, please refer to the log " \
"for details.")
lvutil.removeVG(self.dconf['device'], self.vgname)
self._cleanup()
def attach(self, uuid):
util.SMlog("LVHDSR.attach for %s" % self.uuid)
self._cleanup(True) # in case of host crashes, if detach wasn't called
if not util.match_uuid(self.uuid) or not lvutil._checkVG(self.vgname):
raise xs_errors.XenError('SRUnavailable', \
opterr='no such volume group: %s' % self.vgname)
# Refresh the metadata status
self._checkMetadataVolume()
refreshsizeok = self._refresh_size()
if self.isMaster:
if refreshsizeok:
self._expand_size()
# Update SCSIid string
util.SMlog("Calling devlist_to_serial")
scsiutil.add_serial_record(
self.session, self.sr_ref,
scsiutil.devlist_to_serialstring(self.dconf['device'].split(',')))
# Test Legacy Mode Flag and update if VHD volumes exist
if self.isMaster and self.legacyMode:
vdiInfo = lvhdutil.getVDIInfo(self.lvmCache)
for uuid, info in vdiInfo.items():
if info.vdiType == vhdutil.VDI_TYPE_VHD:
self.legacyMode = False
map = self.session.xenapi.SR.get_sm_config(self.sr_ref)
self._introduceMetaDataVolume()
break
# Set the block scheduler
for dev in self.dconf['device'].split(','):
self.block_setscheduler(dev)
def detach(self, uuid):
util.SMlog("LVHDSR.detach for %s" % self.uuid)
cleanup.abort(self.uuid)
# Do a best effort cleanup of the dev mapper entries
# go through all devmapper entries for this VG
success = True
for fileName in glob.glob(DEV_MAPPER_ROOT + '*'):
if util.extractSRFromDevMapper(fileName) != self.uuid:
continue
with Fairlock('devicemapper'):
# check if any file has open handles
if util.doesFileHaveOpenHandles(fileName):
# if yes, log this and signal failure
util.SMlog(
f"LVHDSR.detach: The dev mapper entry {fileName} has "
"open handles")
success = False
continue
# Now attempt to remove the dev mapper entry
if not lvutil.removeDevMapperEntry(fileName, False):
success = False
continue
# also remove the symlinks from /dev/VG-XenStorage-SRUUID/*
try:
lvname = os.path.basename(fileName.replace('-', '/'). \
replace('//', '-'))
lvname = os.path.join(self.path, lvname)
util.force_unlink(lvname)
except Exception as e:
util.SMlog("LVHDSR.detach: failed to remove the symlink for " \
"file %s. Error: %s" % (fileName, str(e)))
success = False
# now remove the directory where the symlinks are
# this should pass as the directory should be empty by now
if success:
try:
if util.pathexists(self.path):
os.rmdir(self.path)
except Exception as e:
util.SMlog("LVHDSR.detach: failed to remove the symlink " \
"directory %s. Error: %s" % (self.path, str(e)))
success = False
if not success:
raise Exception("SR detach failed, please refer to the log " \
"for details.")
# Don't delete lock files on the master as it will break the locking
# between SM and any GC thread that survives through SR.detach.
# However, we should still delete lock files on slaves as it is the
# only place to do so.
self._cleanup(self.isMaster)
def forget_vdi(self, uuid):
if not self.legacyMode:
LVMMetadataHandler(self.mdpath).deleteVdiFromMetadata(uuid)
super(LVHDSR, self).forget_vdi(uuid)
def scan(self, uuid):
activated = True
try:
lvname = ''
util.SMlog("LVHDSR.scan for %s" % self.uuid)
if not self.isMaster:
util.SMlog('sr_scan blocked for non-master')
raise xs_errors.XenError('LVMMaster')
if self._refresh_size():
self._expand_size()
self.lvmCache.refresh()
cbt_vdis = self.lvmCache.getTagged(CBTLOG_TAG)
self._loadvdis()
stats = lvutil._getVGstats(self.vgname)
self.physical_size = stats['physical_size']
self.physical_utilisation = stats['physical_utilisation']
# Now check if there are any VDIs in the metadata, which are not in
# XAPI
if self.mdexists:
vdiToSnaps = {}
# get VDIs from XAPI
vdis = self.session.xenapi.SR.get_VDIs(self.sr_ref)
vdi_uuids = set([])
for vdi in vdis:
vdi_uuids.add(self.session.xenapi.VDI.get_uuid(vdi))
Dict = LVMMetadataHandler(self.mdpath, False).getMetadata()[1]
for vdi in list(Dict.keys()):
vdi_uuid = Dict[vdi][UUID_TAG]
if bool(int(Dict[vdi][IS_A_SNAPSHOT_TAG])):
if Dict[vdi][SNAPSHOT_OF_TAG] in vdiToSnaps:
vdiToSnaps[Dict[vdi][SNAPSHOT_OF_TAG]].append(vdi_uuid)
else:
vdiToSnaps[Dict[vdi][SNAPSHOT_OF_TAG]] = [vdi_uuid]
if vdi_uuid not in vdi_uuids:
util.SMlog("Introduce VDI %s as it is present in " \
"metadata and not in XAPI." % vdi_uuid)
sm_config = {}
sm_config['vdi_type'] = Dict[vdi][VDI_TYPE_TAG]
lvname = "%s%s" % \
(lvhdutil.LV_PREFIX[sm_config['vdi_type']], vdi_uuid)
self.lvmCache.activateNoRefcount(lvname)
activated = True
lvPath = os.path.join(self.path, lvname)
if Dict[vdi][VDI_TYPE_TAG] == vhdutil.VDI_TYPE_RAW:
size = self.lvmCache.getSize( \
lvhdutil.LV_PREFIX[vhdutil.VDI_TYPE_RAW] + \
vdi_uuid)
utilisation = \
util.roundup(lvutil.LVM_SIZE_INCREMENT,
int(size))
else:
parent = \
vhdutil._getVHDParentNoCheck(lvPath)
if parent is not None:
sm_config['vhd-parent'] = parent[len( \
lvhdutil.LV_PREFIX[vhdutil.VDI_TYPE_VHD]):]
size = vhdutil.getSizeVirt(lvPath)
if self.provision == "thin":
utilisation = \
util.roundup(lvutil.LVM_SIZE_INCREMENT,
vhdutil.calcOverheadEmpty(lvhdutil.MSIZE))
else:
utilisation = lvhdutil.calcSizeVHDLV(int(size))
vdi_ref = self.session.xenapi.VDI.db_introduce(
vdi_uuid,
Dict[vdi][NAME_LABEL_TAG],
Dict[vdi][NAME_DESCRIPTION_TAG],
self.sr_ref,
Dict[vdi][TYPE_TAG],
False,
bool(int(Dict[vdi][READ_ONLY_TAG])),
{},
vdi_uuid,
{},
sm_config)
self.session.xenapi.VDI.set_managed(vdi_ref,
bool(int(Dict[vdi][MANAGED_TAG])))
self.session.xenapi.VDI.set_virtual_size(vdi_ref,
str(size))
self.session.xenapi.VDI.set_physical_utilisation( \
vdi_ref, str(utilisation))
self.session.xenapi.VDI.set_is_a_snapshot( \
vdi_ref, bool(int(Dict[vdi][IS_A_SNAPSHOT_TAG])))
if bool(int(Dict[vdi][IS_A_SNAPSHOT_TAG])):
self.session.xenapi.VDI.set_snapshot_time( \
vdi_ref, DateTime(Dict[vdi][SNAPSHOT_TIME_TAG]))
if Dict[vdi][TYPE_TAG] == 'metadata':
self.session.xenapi.VDI.set_metadata_of_pool( \
vdi_ref, Dict[vdi][METADATA_OF_POOL_TAG])
# Update CBT status of disks either just added
# or already in XAPI
cbt_logname = "%s.%s" % (vdi_uuid, CBTLOG_TAG)
if cbt_logname in cbt_vdis:
vdi_ref = self.session.xenapi.VDI.get_by_uuid(vdi_uuid)
self.session.xenapi.VDI.set_cbt_enabled(vdi_ref, True)
# For existing VDIs, update local state too
# Scan in base class SR updates existing VDIs
# again based on local states
if vdi_uuid in self.vdis:
self.vdis[vdi_uuid].cbt_enabled = True
cbt_vdis.remove(cbt_logname)
# Now set the snapshot statuses correctly in XAPI
for srcvdi in vdiToSnaps.keys():
try:
srcref = self.session.xenapi.VDI.get_by_uuid(srcvdi)
except:
# the source VDI no longer exists, continue
continue
for snapvdi in vdiToSnaps[srcvdi]:
try:
# this might fail in cases where its already set
snapref = \
self.session.xenapi.VDI.get_by_uuid(snapvdi)
self.session.xenapi.VDI.set_snapshot_of(snapref, srcref)
except Exception as e:
util.SMlog("Setting snapshot failed. " \
"Error: %s" % str(e))
if cbt_vdis:
# If we have items remaining in this list,
# they are cbt_metadata VDI that XAPI doesn't know about
# Add them to self.vdis and they'll get added to the DB
for cbt_vdi in cbt_vdis:
cbt_uuid = cbt_vdi.split(".")[0]
new_vdi = self.vdi(cbt_uuid)
new_vdi.ty = "cbt_metadata"
new_vdi.cbt_enabled = True
self.vdis[cbt_uuid] = new_vdi
super(LVHDSR, self).scan(uuid)
self._kickGC()
finally:
if lvname != '' and activated:
self.lvmCache.deactivateNoRefcount(lvname)
def update(self, uuid):
if not lvutil._checkVG(self.vgname):
return
self._updateStats(uuid, 0)
if self.legacyMode:
return
# synch name_label in metadata with XAPI
update_map = {}
update_map = {METADATA_UPDATE_OBJECT_TYPE_TAG: \
METADATA_OBJECT_TYPE_SR,
NAME_LABEL_TAG: util.to_plain_string( \
self.session.xenapi.SR.get_name_label(self.sr_ref)),
NAME_DESCRIPTION_TAG: util.to_plain_string( \
self.session.xenapi.SR.get_name_description(self.sr_ref))
}
LVMMetadataHandler(self.mdpath).updateMetadata(update_map)
def _updateStats(self, uuid, virtAllocDelta):
valloc = int(self.session.xenapi.SR.get_virtual_allocation(self.sr_ref))
self.virtual_allocation = valloc + virtAllocDelta
util.SMlog("Setting virtual_allocation of SR %s to %d" %
(uuid, self.virtual_allocation))
stats = lvutil._getVGstats(self.vgname)
self.physical_size = stats['physical_size']
self.physical_utilisation = stats['physical_utilisation']
self._db_update()
@deviceCheck
def probe(self):
return lvutil.srlist_toxml(
lvutil.scan_srlist(lvhdutil.VG_PREFIX, self.dconf['device']),
lvhdutil.VG_PREFIX,
('metadata' in self.srcmd.params['sr_sm_config'] and \
self.srcmd.params['sr_sm_config']['metadata'] == 'true'))
def vdi(self, uuid):
return LVHDVDI(self, uuid)
def _loadvdis(self):
self.virtual_allocation = 0
self.vdiInfo = lvhdutil.getVDIInfo(self.lvmCache)
self.allVDIs = {}
for uuid, info in self.vdiInfo.items():
if uuid.startswith(cleanup.SR.TMP_RENAME_PREFIX):
continue
if info.scanError:
raise xs_errors.XenError('VDIUnavailable', \
opterr='Error scanning VDI %s' % uuid)
self.vdis[uuid] = self.allVDIs[uuid] = self.vdi(uuid)
if not self.vdis[uuid].hidden:
self.virtual_allocation += self.vdis[uuid].utilisation
for uuid, vdi in self.vdis.items():
if vdi.parent:
if vdi.parent in self.vdis:
self.vdis[vdi.parent].read_only = True
if vdi.parent in geneology:
geneology[vdi.parent].append(uuid)
else:
geneology[vdi.parent] = [uuid]
# Now remove all hidden leaf nodes to avoid introducing records that
# will be GC'ed
for uuid in list(self.vdis.keys()):
if uuid not in geneology and self.vdis[uuid].hidden:
util.SMlog("Scan found hidden leaf (%s), ignoring" % uuid)
del self.vdis[uuid]
def _ensureSpaceAvailable(self, amount_needed):
space_available = lvutil._getVGstats(self.vgname)['freespace']
if (space_available < amount_needed):
util.SMlog("Not enough space! free space: %d, need: %d" % \
(space_available, amount_needed))
raise xs_errors.XenError('SRNoSpace')
def _handleInterruptedCloneOps(self):
entries = self.journaler.getAll(LVHDVDI.JRN_CLONE)
for uuid, val in entries.items():
util.fistpoint.activate("LVHDRT_clone_vdi_before_undo_clone", self.uuid)
self._handleInterruptedCloneOp(uuid, val)
util.fistpoint.activate("LVHDRT_clone_vdi_after_undo_clone", self.uuid)
self.journaler.remove(LVHDVDI.JRN_CLONE, uuid)
def _handleInterruptedCoalesceLeaf(self):
entries = self.journaler.getAll(cleanup.VDI.JRN_LEAF)
if len(entries) > 0:
util.SMlog("*** INTERRUPTED COALESCE-LEAF OP DETECTED ***")
cleanup.gc_force(self.session, self.uuid)
self.lvmCache.refresh()
def _handleInterruptedCloneOp(self, origUuid, jval, forceUndo=False):
"""Either roll back or finalize the interrupted snapshot/clone
operation. Rolling back is unsafe if the leaf VHDs have already been
in use and written to. However, it is always safe to roll back while
we're still in the context of the failed snapshot operation since the
VBD is paused for the duration of the operation"""
util.SMlog("*** INTERRUPTED CLONE OP: for %s (%s)" % (origUuid, jval))
lvs = lvhdutil.getLVInfo(self.lvmCache)
baseUuid, clonUuid = jval.split("_")
# is there a "base copy" VDI?
if not lvs.get(baseUuid):
# no base copy: make sure the original is there
if lvs.get(origUuid):
util.SMlog("*** INTERRUPTED CLONE OP: nothing to do")
return
raise util.SMException("base copy %s not present, " \
"but no original %s found" % (baseUuid, origUuid))
if forceUndo:
util.SMlog("Explicit revert")
self._undoCloneOp(lvs, origUuid, baseUuid, clonUuid)
return
if not lvs.get(origUuid) or (clonUuid and not lvs.get(clonUuid)):
util.SMlog("One or both leaves missing => revert")
self._undoCloneOp(lvs, origUuid, baseUuid, clonUuid)
return
vdis = lvhdutil.getVDIInfo(self.lvmCache)
if vdis[origUuid].scanError or (clonUuid and vdis[clonUuid].scanError):
util.SMlog("One or both leaves invalid => revert")
self._undoCloneOp(lvs, origUuid, baseUuid, clonUuid)
return
orig = vdis[origUuid]
base = vdis[baseUuid]
self.lvActivator.activate(baseUuid, base.lvName, False)
self.lvActivator.activate(origUuid, orig.lvName, False)
if orig.parentUuid != baseUuid:
parent = vdis[orig.parentUuid]
self.lvActivator.activate(parent.uuid, parent.lvName, False)
origPath = os.path.join(self.path, orig.lvName)
if not vhdutil.check(origPath):
util.SMlog("Orig VHD invalid => revert")
self._undoCloneOp(lvs, origUuid, baseUuid, clonUuid)
return
if clonUuid:
clon = vdis[clonUuid]
clonPath = os.path.join(self.path, clon.lvName)
self.lvActivator.activate(clonUuid, clon.lvName, False)
if not vhdutil.check(clonPath):
util.SMlog("Clon VHD invalid => revert")
self._undoCloneOp(lvs, origUuid, baseUuid, clonUuid)
return
util.SMlog("Snapshot appears valid, will not roll back")
self._completeCloneOp(vdis, origUuid, baseUuid, clonUuid)
def _undoCloneOp(self, lvs, origUuid, baseUuid, clonUuid):
base = lvs[baseUuid]
basePath = os.path.join(self.path, base.name)
# make the parent RW
if base.readonly:
self.lvmCache.setReadonly(base.name, False)
ns = lvhdutil.NS_PREFIX_LVM + self.uuid
origRefcountBinary = RefCounter.check(origUuid, ns)[1]
origRefcountNormal = 0
# un-hide the parent
if base.vdiType == vhdutil.VDI_TYPE_VHD:
self.lvActivator.activate(baseUuid, base.name, False)
origRefcountNormal = 1
vhdInfo = vhdutil.getVHDInfo(basePath, lvhdutil.extractUuid, False)
if base.vdiType == vhdutil.VDI_TYPE_VHD and vhdInfo.hidden:
vhdutil.setHidden(basePath, False)
elif base.vdiType == vhdutil.VDI_TYPE_RAW and base.hidden:
self.lvmCache.setHidden(base.name, False)
# remove the child nodes
if clonUuid and lvs.get(clonUuid):
if lvs[clonUuid].vdiType != vhdutil.VDI_TYPE_VHD:
raise util.SMException("clone %s not VHD" % clonUuid)
self.lvmCache.remove(lvs[clonUuid].name)
if self.lvActivator.get(clonUuid, False):
self.lvActivator.remove(clonUuid, False)
if lvs.get(origUuid):
self.lvmCache.remove(lvs[origUuid].name)
# inflate the parent to fully-allocated size
if base.vdiType == vhdutil.VDI_TYPE_VHD:
fullSize = lvhdutil.calcSizeVHDLV(vhdInfo.sizeVirt)
lvhdutil.inflate(self.journaler, self.uuid, baseUuid, fullSize)
# rename back
origLV = lvhdutil.LV_PREFIX[base.vdiType] + origUuid
self.lvmCache.rename(base.name, origLV)
RefCounter.reset(baseUuid, ns)
if self.lvActivator.get(baseUuid, False):
self.lvActivator.replace(baseUuid, origUuid, origLV, False)