Coverage for drivers/EXT4SR.py : 0%

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#!/usr/bin/python3
2#
3# Original work copyright (C) Citrix Systems Inc.
4# Modified work copyright (C) Vates SAS and XCP-ng community
5#
6# This program is free software; you can redistribute it and/or modify
7# it under the terms of the GNU Lesser General Public License as published
8# by the Free Software Foundation; version 2.1 only.
9#
10# This program is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13# GNU Lesser General Public License for more details.
14#
15# You should have received a copy of the GNU Lesser General Public License
16# along with this program; if not, write to the Free Software Foundation, Inc.,
17# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18#
19# EXT4SR: Based on local-file storage repository, mounts ext4 partition
21import SR
22from SR import deviceCheck
23import SRCommand
24import FileSR
25import util
26import lvutil
27import scsiutil
29import os
30import xs_errors
31import vhdutil
32from lock import Lock
33from constants import EXT_PREFIX
35CAPABILITIES = ["SR_PROBE", "SR_UPDATE", "SR_SUPPORTS_LOCAL_CACHING", \
36 "VDI_CREATE", "VDI_DELETE", "VDI_ATTACH", "VDI_DETACH", \
37 "VDI_UPDATE", "VDI_CLONE", "VDI_SNAPSHOT", "VDI_RESIZE", "VDI_MIRROR", \
38 "VDI_GENERATE_CONFIG", \
39 "VDI_RESET_ON_BOOT/2", "ATOMIC_PAUSE", "VDI_CONFIG_CBT",
40 "VDI_ACTIVATE", "VDI_DEACTIVATE", "THIN_PROVISIONING", "VDI_READ_CACHING"]
42CONFIGURATION = [['device', 'local device path (required) (e.g. /dev/sda3)']]
44DRIVER_INFO = {
45 'name': 'Local EXT4 VHD',
46 'description': 'SR plugin which represents disks as VHD files stored on a local EXT4 filesystem, created inside an LVM volume',
47 'vendor': 'Vates SAS',
48 'copyright': '(C) 2019 Vates SAS',
49 'driver_version': '1.0',
50 'required_api_version': '1.0',
51 'capabilities': CAPABILITIES,
52 'configuration': CONFIGURATION
53 }
55DRIVER_CONFIG = {"ATTACH_FROM_CONFIG_WITH_TAPDISK": True}
57class EXT4SR(FileSR.FileSR):
58 """EXT4 Local file storage repository"""
60 def handles(srtype):
61 return srtype == 'ext4'
62 handles = staticmethod(handles)
64 def load(self, sr_uuid):
65 self.ops_exclusive = FileSR.OPS_EXCLUSIVE
66 self.lock = Lock(vhdutil.LOCK_TYPE_SR, self.uuid)
67 self.sr_vditype = SR.DEFAULT_TAP
69 self.path = os.path.join(SR.MOUNT_BASE, sr_uuid)
70 self.vgname = EXT_PREFIX + sr_uuid
71 self.remotepath = os.path.join("/dev", self.vgname, sr_uuid)
72 self.attached = self._checkmount()
73 self.driver_config = DRIVER_CONFIG
75 def delete(self, sr_uuid):
76 super(EXT4SR, self).delete(sr_uuid)
78 # Check PVs match VG
79 try:
80 for dev in self.dconf['device'].split(','):
81 cmd = ["pvs", dev]
82 txt = util.pread2(cmd)
83 if txt.find(self.vgname) == -1:
84 raise xs_errors.XenError('VolNotFound', \
85 opterr='volume is %s' % self.vgname)
86 except util.CommandException as inst:
87 raise xs_errors.XenError('PVSfailed', \
88 opterr='error is %d' % inst.code)
90 # Remove LV, VG and pv
91 try:
92 cmd = ["lvremove", "-f", self.remotepath]
93 util.pread2(cmd)
95 cmd = ["vgremove", self.vgname]
96 util.pread2(cmd)
98 for dev in self.dconf['device'].split(','):
99 cmd = ["pvremove", dev]
100 util.pread2(cmd)
101 except util.CommandException as inst:
102 raise xs_errors.XenError('LVMDelete', \
103 opterr='errno is %d' % inst.code)
105 def attach(self, sr_uuid):
106 if not self._checkmount():
107 try:
108 #Activate LV
109 cmd = ['lvchange', '-ay', self.remotepath]
110 util.pread2(cmd)
112 # make a mountpoint:
113 if not os.path.isdir(self.path):
114 os.makedirs(self.path)
115 except util.CommandException as inst:
116 raise xs_errors.XenError('LVMMount', \
117 opterr='Unable to activate LV. Errno is %d' % inst.code)
119 try:
120 util.pread(["fsck", "-a", self.remotepath])
121 except util.CommandException as inst:
122 if inst.code == 1:
123 util.SMlog("FSCK detected and corrected FS errors. Not fatal.")
124 else:
125 raise xs_errors.XenError('LVMMount', \
126 opterr='FSCK failed on %s. Errno is %d' % (self.remotepath, inst.code))
128 try:
129 util.pread(["mount", self.remotepath, self.path])
130 except util.CommandException as inst:
131 raise xs_errors.XenError('LVMMount', \
132 opterr='Failed to mount FS. Errno is %d' % inst.code)
134 self.attached = True
136 #Update SCSIid string
137 scsiutil.add_serial_record(self.session, self.sr_ref, \
138 scsiutil.devlist_to_serialstring(self.dconf['device'].split(',')))
140 # Set the block scheduler
141 for dev in self.dconf['device'].split(','):
142 self.block_setscheduler(dev)
144 def detach(self, sr_uuid):
145 super(EXT4SR, self).detach(sr_uuid)
146 try:
147 # deactivate SR
148 cmd = ["lvchange", "-an", self.remotepath]
149 util.pread2(cmd)
150 except util.CommandException as inst:
151 raise xs_errors.XenError('LVMUnMount', \
152 opterr='lvm -an failed errno is %d' % inst.code)
154 @deviceCheck
155 def probe(self):
156 return lvutil.srlist_toxml(lvutil.scan_srlist(EXT_PREFIX, self.dconf['device']),
157 EXT_PREFIX)
159 @deviceCheck
160 def create(self, sr_uuid, size):
161 # THIS DRIVER IS DEPRECATED. RAISE.
162 raise Exception('The `ext4` SR type is deprecated since XCP-ng 8.1.\n'
163 'Use the main `ext` driver instead. It will create an EXT4 filesystem now, '
164 'not EXT3 anymore as it used to.')
166 if self._checkmount():
167 raise xs_errors.XenError('SRExists')
169 # Check none of the devices already in use by other PBDs
170 if util.test_hostPBD_devs(self.session, sr_uuid, self.dconf['device']):
171 raise xs_errors.XenError('SRInUse')
173 # Check serial number entry in SR records
174 for dev in self.dconf['device'].split(','):
175 if util.test_scsiserial(self.session, dev):
176 raise xs_errors.XenError('SRInUse')
178 if not lvutil._checkVG(self.vgname):
179 lvutil.createVG(self.dconf['device'], self.vgname)
181 if lvutil._checkLV(self.remotepath):
182 raise xs_errors.XenError('SRExists')
184 try:
185 numdevs = len(self.dconf['device'].split(','))
186 cmd = ["lvcreate", "-n", sr_uuid]
187 if numdevs > 1:
188 lowest = -1
189 for dev in self.dconf['device'].split(','):
190 stats = lvutil._getPVstats(dev)
191 if lowest < 0 or stats['freespace'] < lowest:
192 lowest = stats['freespace']
193 size_mb = (lowest // (1024 * 1024)) * numdevs
195 # Add stripe parameter to command
196 cmd += ["-i", str(numdevs), "-I", "2048"]
197 else:
198 stats = lvutil._getVGstats(self.vgname)
199 size_mb = stats['freespace'] // (1024 * 1024)
200 assert(size_mb > 0)
201 cmd += ["-L", str(size_mb), self.vgname]
202 text = util.pread(cmd)
204 cmd = ["lvchange", "-ay", self.remotepath]
205 text = util.pread(cmd)
206 except util.CommandException as inst:
207 raise xs_errors.XenError('LVMCreate', \
208 opterr='lv operation, error %d' % inst.code)
209 except AssertionError:
210 raise xs_errors.XenError('SRNoSpace', \
211 opterr='Insufficient space in VG %s' % self.vgname)
213 try:
214 util.pread2(["mkfs.ext4", "-F", self.remotepath])
215 except util.CommandException as inst:
216 raise xs_errors.XenError('LVMFilesystem', \
217 opterr='mkfs failed error %d' % inst.code)
219 #Update serial number string
220 scsiutil.add_serial_record(self.session, self.sr_ref, \
221 scsiutil.devlist_to_serialstring(self.dconf['device'].split(',')))
223 def vdi(self, uuid, loadLocked=False):
224 if not loadLocked:
225 return EXTFileVDI(self, uuid)
226 return EXTFileVDI(self, uuid)
229class EXTFileVDI(FileSR.FileVDI):
230 def attach(self, sr_uuid, vdi_uuid):
231 if not hasattr(self, 'xenstore_data'):
232 self.xenstore_data = {}
234 self.xenstore_data["storage-type"] = "ext"
236 return super(EXTFileVDI, self).attach(sr_uuid, vdi_uuid)
239if __name__ == '__main__':
240 SRCommand.run(EXT4SR, DRIVER_INFO)
241else:
242 SR.registerSR(EXT4SR)