summaryrefslogtreecommitdiffstats
path: root/src/VBox/ValidationKit/tests/storage/storagecfg.py
blob: e97f57b0ca1f55a9b54515c54d21d83985048f2e (plain)
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
# -*- coding: utf-8 -*-
# $Id: storagecfg.py $

"""
VirtualBox Validation Kit - Storage test configuration API.
"""

__copyright__ = \
"""
Copyright (C) 2016-2019 Oracle Corporation

This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free software;
you can redistribute it and/or modify it under the terms of the GNU
General Public License (GPL) as published by the Free Software
Foundation, in version 2 as it comes in the "COPYING" file of the
VirtualBox OSE distribution. VirtualBox OSE is distributed in the
hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.

The contents of this file may alternatively be used under the terms
of the Common Development and Distribution License Version 1.0
(CDDL) only, as it comes in the "COPYING.CDDL" file of the
VirtualBox OSE distribution, in which case the provisions of the
CDDL are applicable instead of those of the GPL.

You may elect to license modified versions of this file under the
terms and conditions of either the GPL or the CDDL or both.
"""
__version__ = "$Revision: 127855 $"

# Standard Python imports.
import os;
import re;

# Validation Kit imports.
from common import utils;


class StorageDisk(object):
    """
    Class representing a disk for testing.
    """

    def __init__(self, sPath, fRamDisk = False):
        self.sPath    = sPath;
        self.fUsed    = False;
        self.fRamDisk = fRamDisk;

    def getPath(self):
        """
        Return the disk path.
        """
        return self.sPath;

    def isUsed(self):
        """
        Returns whether the disk is currently in use.
        """
        return self.fUsed;

    def isRamDisk(self):
        """
        Returns whether the disk objecthas a RAM backing.
        """
        return self.fRamDisk;

    def setUsed(self, fUsed):
        """
        Sets the used flag for the disk.
        """
        if fUsed:
            if self.fUsed:
                return False;

            self.fUsed = True;
        else:
            self.fUsed = fUsed;

        return True;

class StorageConfigOs(object):
    """
    Base class for a single hosts OS storage configuration.
    """

    def _getDisksMatchingRegExpWithPath(self, sPath, sRegExp):
        """
        Adds new disks to the config matching the given regular expression.
        """

        lstDisks = [];
        oRegExp = re.compile(sRegExp);
        asFiles = os.listdir(sPath);
        for sFile in asFiles:
            if oRegExp.match(os.path.basename(sFile)) and os.path.exists(sPath + '/' + sFile):
                lstDisks.append(StorageDisk(sPath + '/' + sFile));

        return lstDisks;

class StorageConfigOsSolaris(StorageConfigOs):
    """
    Class implementing the Solaris specifics for a storage configuration.
    """

    def __init__(self):
        StorageConfigOs.__init__(self);
        self.idxRamDisk = 0;

    def _getActivePoolsStartingWith(self, oExec, sPoolIdStart):
        """
        Returns a list of pools starting with the given ID or None on failure.
        """
        lstPools = None;
        fRc, sOutput, _ = oExec.execBinary('zpool', ('list', '-H'));
        if fRc:
            lstPools = [];
            asPools = sOutput.splitlines();
            for sPool in asPools:
                if sPool.startswith(sPoolIdStart):
                    # Extract the whole name and add it to the list.
                    asItems = sPool.split('\t');
                    lstPools.append(asItems[0]);
        return lstPools;

    def _getActiveVolumesInPoolStartingWith(self, oExec, sPool, sVolumeIdStart):
        """
        Returns a list of active volumes for the given pool starting with the given
        identifier or None on failure.
        """
        lstVolumes = None;
        fRc, sOutput, _ = oExec.execBinary('zfs', ('list', '-H'));
        if fRc:
            lstVolumes = [];
            asVolumes = sOutput.splitlines();
            for sVolume in asVolumes:
                if sVolume.startswith(sPool + '/' + sVolumeIdStart):
                    # Extract the whole name and add it to the list.
                    asItems = sVolume.split('\t');
                    lstVolumes.append(asItems[0]);
        return lstVolumes;

    def getDisksMatchingRegExp(self, sRegExp):
        """
        Returns a list of disks matching the regular expression.
        """
        return self._getDisksMatchingRegExpWithPath('/dev/dsk', sRegExp);

    def getMntBase(self):
        """
        Returns the mountpoint base for the host.
        """
        return '/pools';

    def createStoragePool(self, oExec, sPool, asDisks, sRaidLvl):
        """
        Creates a new storage pool with the given disks and the given RAID level.
        """
        sZPoolRaid = None;
        if len(asDisks) > 1 and (sRaidLvl == 'raid5' or sRaidLvl is None):
            sZPoolRaid = 'raidz';

        fRc = True;
        if sZPoolRaid is not None:
            fRc = oExec.execBinaryNoStdOut('zpool', ('create', '-f', sPool, sZPoolRaid,) + tuple(asDisks));
        else:
            fRc = oExec.execBinaryNoStdOut('zpool', ('create', '-f', sPool,) + tuple(asDisks));

        return fRc;

    def createVolume(self, oExec, sPool, sVol, sMountPoint, cbVol = None):
        """
        Creates and mounts a filesystem at the given mountpoint using the
        given pool and volume IDs.
        """
        fRc = True;
        if cbVol is not None:
            fRc = oExec.execBinaryNoStdOut('zfs', ('create', '-o', 'mountpoint='+sMountPoint, '-V', cbVol, sPool + '/' + sVol));
        else:
            fRc = oExec.execBinaryNoStdOut('zfs', ('create', '-o', 'mountpoint='+sMountPoint, sPool + '/' + sVol));

        return fRc;

    def destroyVolume(self, oExec, sPool, sVol):
        """
        Destroys the given volume.
        """
        fRc = oExec.execBinaryNoStdOut('zfs', ('destroy', sPool + '/' + sVol));
        return fRc;

    def destroyPool(self, oExec, sPool):
        """
        Destroys the given storage pool.
        """
        fRc = oExec.execBinaryNoStdOut('zpool', ('destroy', sPool));
        return fRc;

    def cleanupPoolsAndVolumes(self, oExec, sPoolIdStart, sVolIdStart):
        """
        Cleans up any pools and volumes starting with the name in the given
        parameters.
        """
        fRc = True;
        lstPools = self._getActivePoolsStartingWith(oExec, sPoolIdStart);
        if lstPools is not None:
            for sPool in lstPools:
                lstVolumes = self._getActiveVolumesInPoolStartingWith(oExec, sPool, sVolIdStart);
                if lstVolumes is not None:
                    # Destroy all the volumes first
                    for sVolume in lstVolumes:
                        fRc2 = oExec.execBinaryNoStdOut('zfs', ('destroy', sVolume));
                        if not fRc2:
                            fRc = fRc2;

                    # Destroy the pool
                    fRc2 = self.destroyPool(oExec, sPool);
                    if not fRc2:
                        fRc = fRc2;
                else:
                    fRc = False;
        else:
            fRc = False;

        return fRc;

    def createRamDisk(self, oExec, cbRamDisk):
        """
        Creates a RAM backed disk with the given size.
        """
        oDisk = None;
        sRamDiskName = 'ramdisk%u' % (self.idxRamDisk,);
        fRc, _ , _ = oExec.execBinary('ramdiskadm', ('-a', sRamDiskName, str(cbRamDisk)));
        if fRc:
            self.idxRamDisk += 1;
            oDisk = StorageDisk('/dev/ramdisk/%s' % (sRamDiskName, ), True);

        return oDisk;

    def destroyRamDisk(self, oExec, oDisk):
        """
        Destroys the given ramdisk object.
        """
        sRamDiskName = os.path.basename(oDisk.getPath());
        return oExec.execBinaryNoStdOut('ramdiskadm', ('-d', sRamDiskName));

class StorageConfigOsLinux(StorageConfigOs):
    """
    Class implementing the Linux specifics for a storage configuration.
    """

    def __init__(self):
        StorageConfigOs.__init__(self);
        self.dSimplePools = { }; # Simple storage pools which don't use lvm (just one partition)
        self.dMounts      = { }; # Pool/Volume to mountpoint mapping.

    def _getDmRaidLevelFromLvl(self, sRaidLvl):
        """
        Converts our raid level indicators to something mdadm can understand.
        """
        if sRaidLvl == 'raid5':
            return '5';
        elif sRaidLvl == 'raid1':
            return 'mirror';
        elif sRaidLvl == 'raid0' or sRaidLvl is None:
            return 'stripe';

        return 'stripe';

    def getDisksMatchingRegExp(self, sRegExp):
        """
        Returns a list of disks matching the regular expression.
        """
        return self._getDisksMatchingRegExpWithPath('/dev/', sRegExp);

    def getMntBase(self):
        """
        Returns the mountpoint base for the host.
        """
        return '/mnt';

    def createStoragePool(self, oExec, sPool, asDisks, sRaidLvl):
        """
        Creates a new storage pool with the given disks and the given RAID level.
        """
        fRc = True;
        if len(asDisks) == 1 and sRaidLvl is None:
            # Doesn't require LVM, put into the simple pools dictionary so we can
            # use it when creating a volume later.
            self.dSimplePools[sPool] = asDisks[0];
        else:
            # If a RAID is required use dm-raid first to create one.
            asLvmPvDisks = asDisks;
            fRc = oExec.execBinaryNoStdOut('mdadm', ('--create', '/dev/md0', '--assume-clean',
                                                     '--level=' + self._getDmRaidLevelFromLvl(sRaidLvl),
                                                     '--raid-devices=' + str(len(asDisks))) + tuple(asDisks));
            if fRc:
                # /dev/md0 is the only block device to use for our volume group.
                asLvmPvDisks = [ '/dev/md0' ];

            # Create a physical volume on every disk first.
            for sLvmPvDisk in asLvmPvDisks:
                fRc = oExec.execBinaryNoStdOut('pvcreate', (sLvmPvDisk, ));
                if not fRc:
                    break;

            if fRc:
                # Create volume group with all physical volumes included
                fRc = oExec.execBinaryNoStdOut('vgcreate', (sPool, ) + tuple(asLvmPvDisks));
        return fRc;

    def createVolume(self, oExec, sPool, sVol, sMountPoint, cbVol = None):
        """
        Creates and mounts a filesystem at the given mountpoint using the
        given pool and volume IDs.
        """
        fRc = True;
        sBlkDev = None;
        if sPool in self.dSimplePools:
            sDiskPath = self.dSimplePools.get(sPool);
            if sDiskPath.find('zram') != -1:
                sBlkDev = sDiskPath;
            else:
                # Create a partition with the requested size
                sFdiskScript = ';\n'; # Single partition filling everything
                if cbVol is not None:
                    sFdiskScript = ',' + str(cbVol // 512) + '\n'; # Get number of sectors
                fRc = oExec.execBinaryNoStdOut('sfdisk', ('--no-reread', '--wipe', 'always', '-q', '-f', sDiskPath), \
                                               sFdiskScript);
                if fRc:
                    if sDiskPath.find('nvme') != -1:
                        sBlkDev = sDiskPath + 'p1';
                    else:
                        sBlkDev = sDiskPath + '1';
        else:
            if cbVol is None:
                fRc = oExec.execBinaryNoStdOut('lvcreate', ('-l', '100%FREE', '-n', sVol, sPool));
            else:
                fRc = oExec.execBinaryNoStdOut('lvcreate', ('-L', str(cbVol), '-n', sVol, sPool));
            if fRc:
                sBlkDev = '/dev/mapper' + sPool + '-' + sVol;

        if fRc is True and sBlkDev is not None:
            # Create a filesystem and mount it
            fRc = oExec.execBinaryNoStdOut('mkfs.ext4', ('-F', '-F', sBlkDev,));
            fRc = fRc and oExec.mkDir(sMountPoint);
            fRc = fRc and oExec.execBinaryNoStdOut('mount', (sBlkDev, sMountPoint));
            if fRc:
                self.dMounts[sPool + '/' + sVol] = sMountPoint;
        return fRc;

    def destroyVolume(self, oExec, sPool, sVol):
        """
        Destroys the given volume.
        """
        # Unmount first
        sMountPoint = self.dMounts[sPool + '/' + sVol];
        fRc = oExec.execBinaryNoStdOut('umount', (sMountPoint,));
        self.dMounts.pop(sPool + '/' + sVol);
        oExec.rmDir(sMountPoint);
        if sPool in self.dSimplePools:
            # Wipe partition table
            sDiskPath = self.dSimplePools.get(sPool);
            if sDiskPath.find('zram') == -1:
                fRc = oExec.execBinaryNoStdOut('sfdisk', ('--no-reread', '--wipe', 'always', '-q', '-f', '--delete', \
                                               sDiskPath));
        else:
            fRc = oExec.execBinaryNoStdOut('lvremove', (sPool + '/' + sVol,));
        return fRc;

    def destroyPool(self, oExec, sPool):
        """
        Destroys the given storage pool.
        """
        fRc = True;
        if sPool in self.dSimplePools:
            self.dSimplePools.pop(sPool);
        else:
            fRc = oExec.execBinaryNoStdOut('vgremove', (sPool,));
        return fRc;

    def cleanupPoolsAndVolumes(self, oExec, sPoolIdStart, sVolIdStart):
        """
        Cleans up any pools and volumes starting with the name in the given
        parameters.
        """
        # @todo: Needs implementation, for LVM based configs a similar approach can be used
        #        as for Solaris.
        _ = oExec;
        _ = sPoolIdStart;
        _ = sVolIdStart;
        return True;

    def createRamDisk(self, oExec, cbRamDisk):
        """
        Creates a RAM backed disk with the given size.
        """
        # Make sure the ZRAM module is loaded.
        oDisk = None;
        fRc = oExec.execBinaryNoStdOut('modprobe', ('zram',));
        if fRc:
            fRc, sOut, _ = oExec.execBinary('zramctl', ('--raw', '-f', '-s', str(cbRamDisk)));
            if fRc:
                oDisk = StorageDisk(sOut.rstrip(), True);

        return oDisk;

    def destroyRamDisk(self, oExec, oDisk):
        """
        Destroys the given ramdisk object.
        """
        return oExec.execBinaryNoStdOut('zramctl', ('-r', oDisk.getPath()));

class StorageCfg(object):
    """
    Storage configuration helper class taking care of the different host OS.
    """

    def __init__(self, oExec, sTargetOs, oDiskCfg):
        self.oExec    = oExec;
        self.lstDisks = [ ]; # List of disks present in the system.
        self.dPools   = { }; # Dictionary of storage pools.
        self.dVols    = { }; # Dictionary of volumes.
        self.iPoolId  = 0;
        self.iVolId   = 0;

        fRc = True;
        oStorOs = None;
        if sTargetOs == 'solaris':
            oStorOs = StorageConfigOsSolaris();
        elif sTargetOs == 'linux':
            oStorOs = StorageConfigOsLinux(); # pylint: disable=R0204
        else:
            fRc = False;

        if fRc:
            self.oStorOs = oStorOs;
            if utils.isString(oDiskCfg):
                self.lstDisks = oStorOs.getDisksMatchingRegExp(oDiskCfg);
            else:
                # Assume a list of of disks and add.
                for sDisk in oDiskCfg:
                    self.lstDisks.append(StorageDisk(sDisk));

    def __del__(self):
        self.cleanup();

    def cleanup(self):
        """
        Cleans up any created storage configs.
        """

        # Destroy all volumes first.
        for sMountPoint in self.dVols.keys(): # pylint: disable=C0201
            self.destroyVolume(sMountPoint);

        # Destroy all pools.
        for sPool in self.dPools.keys(): # pylint: disable=C0201
            self.destroyStoragePool(sPool);

        self.dVols.clear();
        self.dPools.clear();
        self.iPoolId = 0;
        self.iVolId  = 0;

    def getRawDisk(self):
        """
        Returns a raw disk device from the list of free devices for use.
        """
        for oDisk in self.lstDisks:
            if oDisk.isUsed() is False:
                oDisk.setUsed(True);
                return oDisk.getPath();

        return None;

    def getUnusedDiskCount(self):
        """
        Returns the number of unused disks.
        """

        cDisksUnused = 0;
        for oDisk in self.lstDisks:
            if not oDisk.isUsed():
                cDisksUnused += 1;

        return cDisksUnused;

    def createStoragePool(self, cDisks = 0, sRaidLvl = None,
                          cbPool = None, fRamDisk = False):
        """
        Create a new storage pool
        """
        lstDisks = [ ];
        fRc = True;
        sPool = None;

        if fRamDisk:
            oDisk = self.oStorOs.createRamDisk(self.oExec, cbPool);
            if oDisk is not None:
                lstDisks.append(oDisk);
                cDisks = 1;
        else:
            if cDisks == 0:
                cDisks = self.getUnusedDiskCount();

            for oDisk in self.lstDisks:
                if not oDisk.isUsed():
                    oDisk.setUsed(True);
                    lstDisks.append(oDisk);
                    if len(lstDisks) == cDisks:
                        break;

        # Enough drives to satisfy the request?
        if len(lstDisks) == cDisks:
            # Create a list of all device paths
            lstDiskPaths = [ ];
            for oDisk in lstDisks:
                lstDiskPaths.append(oDisk.getPath());

            # Find a name for the pool
            sPool = 'pool' + str(self.iPoolId);
            self.iPoolId += 1;

            fRc = self.oStorOs.createStoragePool(self.oExec, sPool, lstDiskPaths, sRaidLvl);
            if fRc:
                self.dPools[sPool] = lstDisks;
            else:
                self.iPoolId -= 1;
        else:
            fRc = False;

        # Cleanup in case of error.
        if not fRc:
            for oDisk in lstDisks:
                oDisk.setUsed(False);
                if oDisk.isRamDisk():
                    self.oStorOs.destroyRamDisk(self.oExec, oDisk);

        return fRc, sPool;

    def destroyStoragePool(self, sPool):
        """
        Destroys the storage pool with the given ID.
        """

        lstDisks = self.dPools.get(sPool);
        if lstDisks is not None:
            fRc = self.oStorOs.destroyPool(self.oExec, sPool);
            if fRc:
                # Mark disks as unused
                self.dPools.pop(sPool);
                for oDisk in lstDisks:
                    oDisk.setUsed(False);
                    if oDisk.isRamDisk():
                        self.oStorOs.destroyRamDisk(self.oExec, oDisk);
        else:
            fRc = False;

        return fRc;

    def createVolume(self, sPool, cbVol = None):
        """
        Creates a new volume from the given pool returning the mountpoint.
        """

        fRc = True;
        sMountPoint = None;
        if sPool in self.dPools:
            sVol = 'vol' + str(self.iVolId);
            sMountPoint = self.oStorOs.getMntBase() + '/' + sVol;
            self.iVolId += 1;
            fRc = self.oStorOs.createVolume(self.oExec, sPool, sVol, sMountPoint, cbVol);
            if fRc:
                self.dVols[sMountPoint] = (sVol, sPool);
            else:
                self.iVolId -= 1;
        else:
            fRc = False;

        return fRc, sMountPoint;

    def destroyVolume(self, sMountPoint):
        """
        Destroy the volume at the given mount point.
        """

        sVol, sPool = self.dVols.get(sMountPoint);
        fRc = True;
        if sVol is not None:
            fRc = self.oStorOs.destroyVolume(self.oExec, sPool, sVol);
            if fRc:
                self.dVols.pop(sMountPoint);
        else:
            fRc = False;

        return fRc;

    def mkDirOnVolume(self, sMountPoint, sDir, fMode = 0o700):
        """
        Creates a new directory on the volume pointed to by the given mount point.
        """
        return self.oExec.mkDir(sMountPoint + '/' + sDir, fMode);

    def cleanupLeftovers(self):
        """
        Tries to cleanup any leftover pools and volumes from a failed previous run.
        """
        return self.oStorOs.cleanupPoolsAndVolumes(self.oExec, 'pool', 'vol');