storage_backend_logical.c 25.4 KB
Newer Older
1
/*
2
 * storage_backend_logical.c: storage backend for logical volume handling
3
 *
4
 * Copyright (C) 2007-2009, 2011, 2013 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright (C) 2007-2008 Daniel P. Berrange
 *
 * This library 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; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
20 21 22 23 24 25 26 27 28 29 30 31 32 33
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

#include <sys/wait.h>
#include <sys/stat.h>
#include <stdio.h>
#include <regex.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

34
#include "virerror.h"
35 36
#include "storage_backend_logical.h"
#include "storage_conf.h"
37
#include "vircommand.h"
38
#include "viralloc.h"
39
#include "virlog.h"
E
Eric Blake 已提交
40
#include "virfile.h"
41
#include "virstring.h"
42

43 44
#define VIR_FROM_THIS VIR_FROM_STORAGE

45 46 47 48
#define PV_BLANK_SECTOR_SIZE 512


static int
49
virStorageBackendLogicalSetActive(virStoragePoolObjPtr pool,
50 51
                                  int on)
{
52 53 54 55 56 57 58 59 60 61
    int ret;
    virCommandPtr cmd =
        virCommandNewArgList(VGCHANGE,
                             on ? "-aly" : "-aln",
                             pool->def->source.name,
                             NULL);

    ret = virCommandRun(cmd, NULL);
    virCommandFree(cmd);
    return ret;
62 63 64
}


65 66
#define VIR_STORAGE_VOL_LOGICAL_SEGTYPE_STRIPED "striped"

67
static int
68
virStorageBackendLogicalMakeVol(virStoragePoolObjPtr pool,
69 70 71 72
                                char **const groups,
                                void *data)
{
    virStorageVolDefPtr vol = NULL;
73
    bool is_new_vol = false;
74
    unsigned long long offset, size, length;
75 76 77 78 79
    const char *regex_unit = "(\\S+)\\((\\S+)\\)";
    char *regex = NULL;
    regex_t *reg = NULL;
    regmatch_t *vars = NULL;
    char *p = NULL;
80 81
    size_t i;
    int err, nextents, nvars, ret = -1;
O
Osier Yang 已提交
82 83 84 85 86
    const char *attrs = groups[9];

    /* Skip inactive volume */
    if (attrs[4] != 'a')
        return 0;
87 88 89 90 91 92 93 94 95 96 97 98 99 100

    /* See if we're only looking for a specific volume */
    if (data != NULL) {
        vol = data;
        if (STRNEQ(vol->name, groups[0]))
            return 0;
    }

    /* Or filling in more data on an existing volume */
    if (vol == NULL)
        vol = virStorageVolDefFindByName(pool, groups[0]);

    /* Or a completely new volume */
    if (vol == NULL) {
101
        if (VIR_ALLOC(vol) < 0)
102 103
            return -1;

104
        is_new_vol = true;
105 106
        vol->type = VIR_STORAGE_VOL_BLOCK;

107
        if (VIR_STRDUP(vol->name, groups[0]) < 0)
108
            goto cleanup;
109

110
        if (VIR_REALLOC_N(pool->volumes.objs,
111
                          pool->volumes.count + 1))
112
            goto cleanup;
113 114 115
    }

    if (vol->target.path == NULL) {
116
        if (virAsprintf(&vol->target.path, "%s/%s",
117
                        pool->def->target.path, vol->name) < 0)
118
            goto cleanup;
119 120
    }

121 122 123 124 125 126 127 128
    /* Skips the backingStore of lv created with "--virtualsize",
     * its original device "/dev/$vgname/$lvname_vorigin" is
     * just for lvm internal use, one should never use it.
     *
     * (lvs outputs "[$lvname_vorigin] for field "origin" if the
     *  lv is created with "--virtualsize").
     */
    if (groups[1] && !STREQ(groups[1], "") && (groups[1][0] != '[')) {
129
        if (virAsprintf(&vol->backingStore.path, "%s/%s",
130
                        pool->def->target.path, groups[1]) < 0)
131
            goto cleanup;
132 133

        vol->backingStore.format = VIR_STORAGE_POOL_LOGICAL_LVM2;
134 135
    }

136
    if (!vol->key && VIR_STRDUP(vol->key, groups[2]) < 0)
137
        goto cleanup;
138

139
    if (virStorageBackendUpdateVolInfo(vol, 1) < 0)
140 141 142 143 144
        goto cleanup;

    nextents = 1;
    if (STREQ(groups[4], VIR_STORAGE_VOL_LOGICAL_SEGTYPE_STRIPED)) {
        if (virStrToLong_i(groups[5], NULL, 10, &nextents) < 0) {
145 146
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("malformed volume extent stripes value"));
147 148 149
            goto cleanup;
        }
    }
150 151

    /* Finally fill in extents information */
152
    if (VIR_REALLOC_N(vol->source.extents,
153
                      vol->source.nextent + nextents) < 0)
154
        goto cleanup;
155

156
    if (virStrToLong_ull(groups[6], NULL, 10, &length) < 0) {
157 158
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("malformed volume extent length value"));
159 160 161
        goto cleanup;
    }
    if (virStrToLong_ull(groups[7], NULL, 10, &size) < 0) {
162 163
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("malformed volume extent size value"));
164 165
        goto cleanup;
    }
166
    if (virStrToLong_ull(groups[8], NULL, 10, &vol->allocation) < 0) {
167 168
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("malformed volume allocation value"));
169 170
        goto cleanup;
    }
171

E
Eric Blake 已提交
172
    /* Now parse the "devices" field separately */
173 174
    if (VIR_STRDUP(regex, regex_unit) < 0)
        goto cleanup;
175 176

    for (i = 1; i < nextents; i++) {
177
        if (VIR_REALLOC_N(regex, strlen(regex) + strlen(regex_unit) + 2) < 0)
178
            goto cleanup;
E
Eric Blake 已提交
179
        /* "," is the separator of "devices" field */
180 181 182 183
        strcat(regex, ",");
        strncat(regex, regex_unit, strlen(regex_unit));
    }

184
    if (VIR_ALLOC(reg) < 0)
185
        goto cleanup;
186

187 188 189 190
    /* Each extent has a "path:offset" pair, and vars[0] will
     * be the whole matched string.
     */
    nvars = (nextents * 2) + 1;
191
    if (VIR_ALLOC_N(vars, nvars) < 0)
192 193 194 195 196 197
        goto cleanup;

    err = regcomp(reg, regex, REG_EXTENDED);
    if (err != 0) {
        char error[100];
        regerror(err, reg, error, sizeof(error));
198
        regfree(reg);
199 200 201
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to compile regex %s"),
                       error);
202
        goto cleanup;
203
    }
204

205 206 207
    err = regexec(reg, groups[3], nvars, vars, 0);
    regfree(reg);
    if (err != 0) {
208 209
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("malformed volume extent devices value"));
210
        goto cleanup;
211 212
    }

213
    p = groups[3];
214

215 216
    /* vars[0] is skipped */
    for (i = 0; i < nextents; i++) {
217 218
        size_t j;
        int len;
219
        char *offset_str = NULL;
220 221 222 223 224

        j = (i * 2) + 1;
        len = vars[j].rm_eo - vars[j].rm_so;
        p[vars[j].rm_eo] = '\0';

225 226
        if (VIR_STRNDUP(vol->source.extents[vol->source.nextent].path,
                        p + vars[j].rm_so, len) < 0)
227 228 229
            goto cleanup;

        len = vars[j + 1].rm_eo - vars[j + 1].rm_so;
230
        if (VIR_STRNDUP(offset_str, p + vars[j + 1].rm_so, len) < 0)
231 232 233
            goto cleanup;

        if (virStrToLong_ull(offset_str, NULL, 10, &offset) < 0) {
234 235
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("malformed volume extent offset value"));
E
Eric Blake 已提交
236
            VIR_FREE(offset_str);
237 238 239 240 241 242 243 244 245 246
            goto cleanup;
        }

        VIR_FREE(offset_str);

        vol->source.extents[vol->source.nextent].start = offset * size;
        vol->source.extents[vol->source.nextent].end = (offset * size) + length;
        vol->source.nextent++;
    }

247 248 249
    if (is_new_vol)
        pool->volumes.objs[pool->volumes.count++] = vol;

250 251 252 253
    ret = 0;

cleanup:
    VIR_FREE(regex);
254
    VIR_FREE(reg);
255 256 257 258
    VIR_FREE(vars);
    if (is_new_vol && (ret == -1))
        virStorageVolDefFree(vol);
    return ret;
259 260 261
}

static int
262
virStorageBackendLogicalFindLVs(virStoragePoolObjPtr pool,
263 264 265
                                virStorageVolDefPtr vol)
{
    /*
O
Osier Yang 已提交
266 267 268 269 270 271 272 273
     * # lvs --separator , --noheadings --units b --unbuffered --nosuffix --options \
     * "lv_name,origin,uuid,devices,seg_size,vg_extent_size,size,lv_attr" VGNAME
     *
     * RootLV,,06UgP5-2rhb-w3Bo-3mdR-WeoL-pytO-SAa2ky,/dev/hda2(0),5234491392,33554432,5234491392,-wi-ao
     * SwapLV,,oHviCK-8Ik0-paqS-V20c-nkhY-Bm1e-zgzU0M,/dev/hda2(156),1040187392,33554432,1040187392,-wi-ao
     * Test2,,3pg3he-mQsA-5Sui-h0i6-HNmc-Cz7W-QSndcR,/dev/hda2(219),1073741824,33554432,1073741824,owi-a-
     * Test3,,UB5hFw-kmlm-LSoX-EI1t-ioVd-h7GL-M0W8Ht,/dev/hda2(251),2181038080,33554432,2181038080,-wi-a-
     * Test3,Test2,UB5hFw-kmlm-LSoX-EI1t-ioVd-h7GL-M0W8Ht,/dev/hda2(187),1040187392,33554432,1040187392,swi-a-
274
     *
O
Osier Yang 已提交
275 276
     * Pull out name, origin, & uuid, device, device extent start #,
     * segment size, extent size, size, attrs
277 278
     *
     * NB can be multiple rows per volume if they have many extents
279
     *
280 281 282 283
     * NB lvs from some distros (e.g. SLES10 SP2) outputs trailing "," on each line
     *
     * NB Encrypted logical volumes can print ':' in their name, so it is
     *    not a suitable separator (rhbz 470693).
284 285
     * NB "devices" field has multiple device paths and "," if the volume is
     *    striped, so "," is not a suitable separator either (rhbz 727474).
286 287
     */
    const char *regexes[] = {
O
Osier Yang 已提交
288
       "^\\s*(\\S+)#(\\S*)#(\\S+)#(\\S+)#(\\S+)#([0-9]+)#(\\S+)#([0-9]+)#([0-9]+)#(\\S+)#?\\s*$"
289 290
    };
    int vars[] = {
O
Osier Yang 已提交
291
        10
292
    };
293 294 295 296 297 298 299 300 301
    int ret = -1;
    virCommandPtr cmd;

    cmd = virCommandNewArgList(LVS,
                               "--separator", "#",
                               "--noheadings",
                               "--units", "b",
                               "--unbuffered",
                               "--nosuffix",
O
Osier Yang 已提交
302 303
                               "--options",
                               "lv_name,origin,uuid,devices,segtype,stripes,seg_size,vg_extent_size,size,lv_attr",
304 305
                               pool->def->source.name,
                               NULL);
306
    if (virStorageBackendRunProgRegex(pool,
307
                                      cmd,
308 309 310 311
                                      1,
                                      regexes,
                                      vars,
                                      virStorageBackendLogicalMakeVol,
312 313
                                      vol, "lvs") < 0)
        goto cleanup;
314

315 316 317 318
    ret = 0;
cleanup:
    virCommandFree(cmd);
    return ret;
319 320 321
}

static int
322
virStorageBackendLogicalRefreshPoolFunc(virStoragePoolObjPtr pool ATTRIBUTE_UNUSED,
323 324 325 326 327 328 329 330 331 332 333 334 335
                                        char **const groups,
                                        void *data ATTRIBUTE_UNUSED)
{
    if (virStrToLong_ull(groups[0], NULL, 10, &pool->def->capacity) < 0)
        return -1;
    if (virStrToLong_ull(groups[1], NULL, 10, &pool->def->available) < 0)
        return -1;
    pool->def->allocation = pool->def->capacity - pool->def->available;

    return 0;
}


336
static int
337
virStorageBackendLogicalFindPoolSourcesFunc(virStoragePoolObjPtr pool ATTRIBUTE_UNUSED,
338 339 340
                                            char **const groups,
                                            void *data)
{
341 342 343
    virStoragePoolSourceListPtr sourceList = data;
    char *pvname = NULL;
    char *vgname = NULL;
344
    size_t i;
345 346 347
    virStoragePoolSourceDevicePtr dev;
    virStoragePoolSource *thisSource;

348 349 350
    if (VIR_STRDUP(pvname, groups[0]) < 0 ||
        VIR_STRDUP(vgname, groups[1]) < 0)
        goto error;
351 352

    thisSource = NULL;
353
    for (i = 0; i < sourceList->nsources; i++) {
354 355 356 357 358
        if (STREQ(sourceList->sources[i].name, vgname)) {
            thisSource = &sourceList->sources[i];
            break;
        }
    }
359

360
    if (thisSource == NULL) {
361
        if (!(thisSource = virStoragePoolSourceListNewSource(sourceList)))
362
            goto error;
363 364

        thisSource->name = vgname;
365
    }
366 367
    else
        VIR_FREE(vgname);
368

369
    if (VIR_REALLOC_N(thisSource->devices, thisSource->ndevice + 1) != 0)
370
        goto error;
371

372 373
    dev = &thisSource->devices[thisSource->ndevice];
    thisSource->ndevice++;
374
    thisSource->format = VIR_STORAGE_POOL_LOGICAL_LVM2;
375 376 377

    memset(dev, 0, sizeof(*dev));
    dev->path = pvname;
378 379

    return 0;
380

381
error:
382 383 384 385
    VIR_FREE(pvname);
    VIR_FREE(vgname);

    return -1;
386 387 388
}

static char *
389
virStorageBackendLogicalFindPoolSources(virConnectPtr conn ATTRIBUTE_UNUSED,
390
                                        const char *srcSpec ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
391
                                        unsigned int flags)
392 393
{
    /*
394 395 396
     * # pvs --noheadings -o pv_name,vg_name
     *   /dev/sdb
     *   /dev/sdc VolGroup00
397 398
     */
    const char *regexes[] = {
399
        "^\\s*(\\S+)\\s+(\\S+)\\s*$"
400 401
    };
    int vars[] = {
402
        2
403
    };
404
    virCommandPtr cmd;
405
    char *retval = NULL;
406
    virStoragePoolSourceList sourceList;
407
    size_t i;
408

E
Eric Blake 已提交
409 410
    virCheckFlags(0, NULL);

411 412 413 414 415
    /*
     * NOTE: ignoring errors here; this is just to "touch" any logical volumes
     * that might be hanging around, so if this fails for some reason, the
     * worst that happens is that scanning doesn't pick everything up
     */
416 417
    cmd = virCommandNew(VGSCAN);
    if (virCommandRun(cmd, NULL) < 0)
418
        VIR_WARN("Failure when running vgscan to refresh physical volumes");
419
    virCommandFree(cmd);
420

421
    memset(&sourceList, 0, sizeof(sourceList));
422 423
    sourceList.type = VIR_STORAGE_POOL_LOGICAL;

424 425 426 427 428 429 430 431
    cmd = virCommandNewArgList(PVS,
                               "--noheadings",
                               "-o", "pv_name,vg_name",
                               NULL);
    if (virStorageBackendRunProgRegex(NULL, cmd, 1, regexes, vars,
                                      virStorageBackendLogicalFindPoolSourcesFunc,
                                      &sourceList, "pvs") < 0) {
        virCommandFree(cmd);
432
        return NULL;
433 434
    }
    virCommandFree(cmd);
435

436
    retval = virStoragePoolSourceListFormat(&sourceList);
437
    if (retval == NULL) {
438 439
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to get source from sourceList"));
440 441 442 443
        goto cleanup;
    }

 cleanup:
444
    for (i = 0; i < sourceList.nsources; i++)
445
        virStoragePoolSourceClear(&sourceList.sources[i]);
446
    VIR_FREE(sourceList.sources);
447 448 449 450 451

    return retval;
}


452 453 454 455 456 457 458 459
static int
virStorageBackendLogicalCheckPool(virConnectPtr conn ATTRIBUTE_UNUSED,
                                  virStoragePoolObjPtr pool,
                                  bool *isActive)
{
    char *path;

    *isActive = false;
460
    if (virAsprintf(&path, "/dev/%s", pool->def->source.name) < 0)
461 462 463 464 465 466 467 468 469 470
        return -1;

    if (access(path, F_OK) == 0)
        *isActive = true;

    VIR_FREE(path);

    return 0;
}

471
static int
472
virStorageBackendLogicalStartPool(virConnectPtr conn ATTRIBUTE_UNUSED,
473 474
                                  virStoragePoolObjPtr pool)
{
475
    if (virStorageBackendLogicalSetActive(pool, 1) < 0)
476 477 478 479 480 481 482
        return -1;

    return 0;
}


static int
483
virStorageBackendLogicalBuildPool(virConnectPtr conn ATTRIBUTE_UNUSED,
484
                                  virStoragePoolObjPtr pool,
E
Eric Blake 已提交
485
                                  unsigned int flags)
486
{
487 488
    virCommandPtr vgcmd;
    int fd;
489
    char zeros[PV_BLANK_SECTOR_SIZE];
490 491
    int ret = -1;
    size_t i;
492

E
Eric Blake 已提交
493 494
    virCheckFlags(0, -1);

495 496
    memset(zeros, 0, sizeof(zeros));

497
    vgcmd = virCommandNewArgList(VGCREATE, pool->def->source.name, NULL);
498

499
    for (i = 0; i < pool->def->source.ndevice; i++) {
500
        virCommandPtr pvcmd;
501 502 503 504 505 506
        /*
         * LVM requires that the first sector is blanked if using
         * a whole disk as a PV. So we just blank them out regardless
         * rather than trying to figure out if we're a disk or partition
         */
        if ((fd = open(pool->def->source.devices[i].path, O_WRONLY)) < 0) {
507
            virReportSystemError(errno,
508 509
                                 _("cannot open device '%s'"),
                                 pool->def->source.devices[i].path);
510 511
            goto cleanup;
        }
512
        if (safewrite(fd, zeros, sizeof(zeros)) < 0) {
513
            virReportSystemError(errno,
514 515
                                 _("cannot clear device header of '%s'"),
                                 pool->def->source.devices[i].path);
516 517 518 519 520 521 522
            VIR_FORCE_CLOSE(fd);
            goto cleanup;
        }
        if (fsync(fd) < 0) {
            virReportSystemError(errno,
                                 _("cannot flush header of device'%s'"),
                                 pool->def->source.devices[i].path);
523
            VIR_FORCE_CLOSE(fd);
524 525
            goto cleanup;
        }
526
        if (VIR_CLOSE(fd) < 0) {
527
            virReportSystemError(errno,
528 529
                                 _("cannot close device '%s'"),
                                 pool->def->source.devices[i].path);
530 531 532 533 534 535 536
            goto cleanup;
        }

        /*
         * Initialize the physical volume because vgcreate is not
         * clever enough todo this for us :-(
         */
537 538 539 540 541
        pvcmd = virCommandNewArgList(PVCREATE,
                                     pool->def->source.devices[i].path,
                                     NULL);
        if (virCommandRun(pvcmd, NULL) < 0) {
            virCommandFree(pvcmd);
542
            goto cleanup;
543 544
        }
        virCommandFree(pvcmd);
545

546 547
        virCommandAddArg(vgcmd, pool->def->source.devices[i].path);
    }
548 549

    /* Now create the volume group itself */
550
    if (virCommandRun(vgcmd, NULL) < 0)
551 552
        goto cleanup;

553
    ret = 0;
554

555 556 557
cleanup:
    virCommandFree(vgcmd);
    return ret;
558 559 560 561
}


static int
562
virStorageBackendLogicalRefreshPool(virConnectPtr conn ATTRIBUTE_UNUSED,
563 564 565 566 567 568 569
                                    virStoragePoolObjPtr pool)
{
    /*
     *  # vgs --separator : --noheadings --units b --unbuffered --nosuffix --options "vg_size,vg_free" VGNAME
     *    10603200512:4328521728
     *
     * Pull out size & free
570 571
     *
     * NB vgs from some distros (e.g. SLES10 SP2) outputs trailing ":" on each line
572 573
     */
    const char *regexes[] = {
574
        "^\\s*(\\S+):([0-9]+):?\\s*$"
575 576 577 578
    };
    int vars[] = {
        2
    };
579 580
    virCommandPtr cmd = NULL;
    int ret = -1;
581

582
    virFileWaitForDevices();
583

584
    /* Get list of all logical volumes */
585 586 587 588 589 590 591 592 593 594 595 596
    if (virStorageBackendLogicalFindLVs(pool, NULL) < 0)
        goto cleanup;

    cmd = virCommandNewArgList(VGS,
                               "--separator", ":",
                               "--noheadings",
                               "--units", "b",
                               "--unbuffered",
                               "--nosuffix",
                               "--options", "vg_size,vg_free",
                               pool->def->source.name,
                               NULL);
597 598

    /* Now get basic volgrp metadata */
599
    if (virStorageBackendRunProgRegex(pool,
600
                                      cmd,
601 602 603 604
                                      1,
                                      regexes,
                                      vars,
                                      virStorageBackendLogicalRefreshPoolFunc,
605 606
                                      NULL, "vgs") < 0)
        goto cleanup;
607

608 609 610 611 612 613 614
    ret = 0;

cleanup:
    virCommandFree(cmd);
    if (ret < 0)
        virStoragePoolObjClearVols(pool);
    return ret;
615 616
}

617 618 619 620
/*
 * This is actually relatively safe; if you happen to try to "stop" the
 * pool that your / is on, for instance, you will get failure like:
 * "Can't deactivate volume group "VolGroup00" with 3 open logical volume(s)"
621 622
 */
static int
623
virStorageBackendLogicalStopPool(virConnectPtr conn ATTRIBUTE_UNUSED,
624 625
                                 virStoragePoolObjPtr pool)
{
626
    if (virStorageBackendLogicalSetActive(pool, 0) < 0)
627 628 629 630 631 632
        return -1;

    return 0;
}

static int
633
virStorageBackendLogicalDeletePool(virConnectPtr conn ATTRIBUTE_UNUSED,
634
                                   virStoragePoolObjPtr pool,
E
Eric Blake 已提交
635
                                   unsigned int flags)
636
{
637 638 639
    virCommandPtr cmd = NULL;
    size_t i;
    int ret = -1;
640

E
Eric Blake 已提交
641 642
    virCheckFlags(0, -1);

643
    /* first remove the volume group */
644 645 646 647 648 649
    cmd = virCommandNewArgList(VGREMOVE,
                               "-f", pool->def->source.name,
                               NULL);
    if (virCommandRun(cmd, NULL) < 0)
        goto cleanup;
    virCommandFree(cmd);
650
    cmd = NULL;
651

652
    /* now remove the pv devices and clear them out */
653
    ret = 0;
654
    for (i = 0; i < pool->def->source.ndevice; i++) {
655 656 657 658 659
        cmd = virCommandNewArgList(PVREMOVE,
                                   pool->def->source.devices[i].path,
                                   NULL);
        if (virCommandRun(cmd, NULL) < 0) {
            ret = -1;
660 661
            break;
        }
662 663
        virCommandFree(cmd);
        cmd = NULL;
664
    }
665

666 667 668
cleanup:
    virCommandFree(cmd);
    return ret;
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
}


static int
virStorageBackendLogicalDeleteVol(virConnectPtr conn,
                                  virStoragePoolObjPtr pool,
                                  virStorageVolDefPtr vol,
                                  unsigned int flags);


static int
virStorageBackendLogicalCreateVol(virConnectPtr conn,
                                  virStoragePoolObjPtr pool,
                                  virStorageVolDefPtr vol)
{
684
    int fd = -1;
685
    virCommandPtr cmd = NULL;
686
    virErrorPtr err;
687

688
    if (vol->target.encryption != NULL) {
689 690 691
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       "%s", _("storage pool does not support encrypted "
                               "volumes"));
692 693 694
        return -1;
    }

J
Ján Tomko 已提交
695 696
    vol->type = VIR_STORAGE_VOL_BLOCK;

697 698 699 700
    if (vol->target.path != NULL) {
        /* A target path passed to CreateVol has no meaning */
        VIR_FREE(vol->target.path);
    }
701 702 703

    if (virAsprintf(&vol->target.path, "%s/%s",
                    pool->def->target.path,
704
                    vol->name) == -1)
705 706
        return -1;

707 708 709 710
    cmd = virCommandNewArgList(LVCREATE,
                               "--name", vol->name,
                               NULL);
    virCommandAddArg(cmd, "-L");
711
    if (vol->capacity != vol->allocation) {
712 713
        virCommandAddArgFormat(cmd, "%lluK",
                VIR_DIV_UP(vol->allocation ? vol->allocation : 1, 1024));
714 715
        virCommandAddArg(cmd, "--virtualsize");
    }
716 717
    virCommandAddArgFormat(cmd, "%lluK", VIR_DIV_UP(vol->capacity, 1024));
    if (vol->backingStore.path)
718
        virCommandAddArgList(cmd, "-s", vol->backingStore.path, NULL);
719 720 721 722
    else
        virCommandAddArg(cmd, pool->def->source.name);

    if (virCommandRun(cmd, NULL) < 0)
723
        goto error;
724

725 726 727 728 729
    virCommandFree(cmd);
    cmd = NULL;

    if ((fd = virStorageBackendVolOpen(vol->target.path)) < 0)
        goto error;
730 731 732 733

    /* We can only chown/grp if root */
    if (getuid() == 0) {
        if (fchown(fd, vol->target.perms.uid, vol->target.perms.gid) < 0) {
734
            virReportSystemError(errno,
735 736
                                 _("cannot set file owner '%s'"),
                                 vol->target.path);
737
            goto error;
738 739 740
        }
    }
    if (fchmod(fd, vol->target.perms.mode) < 0) {
741
        virReportSystemError(errno,
742 743
                             _("cannot set file mode '%s'"),
                             vol->target.path);
744
        goto error;
745 746
    }

747
    if (VIR_CLOSE(fd) < 0) {
748
        virReportSystemError(errno,
749 750
                             _("cannot close file '%s'"),
                             vol->target.path);
751
        goto error;
752 753 754
    }

    /* Fill in data about this new vol */
755
    if (virStorageBackendLogicalFindLVs(pool, vol) < 0) {
756
        virReportSystemError(errno,
757 758
                             _("cannot find newly created volume '%s'"),
                             vol->target.path);
759
        goto error;
760 761 762 763
    }

    return 0;

764
 error:
765
    err = virSaveLastError();
766
    VIR_FORCE_CLOSE(fd);
767
    virStorageBackendLogicalDeleteVol(conn, pool, vol, 0);
768
    virCommandFree(cmd);
769
    virSetError(err);
770
    virFreeError(err);
771 772 773
    return -1;
}

774 775
static int
virStorageBackendLogicalBuildVolFrom(virConnectPtr conn,
776
                                     virStoragePoolObjPtr pool,
777 778 779 780 781 782
                                     virStorageVolDefPtr vol,
                                     virStorageVolDefPtr inputvol,
                                     unsigned int flags)
{
    virStorageBackendBuildVolFrom build_func;

783
    build_func = virStorageBackendGetBuildVolFromFunction(vol, inputvol);
784 785 786
    if (!build_func)
        return -1;

787
    return build_func(conn, pool, vol, inputvol, flags);
788 789
}

790
static int
791
virStorageBackendLogicalDeleteVol(virConnectPtr conn ATTRIBUTE_UNUSED,
792 793
                                  virStoragePoolObjPtr pool ATTRIBUTE_UNUSED,
                                  virStorageVolDefPtr vol,
E
Eric Blake 已提交
794
                                  unsigned int flags)
795
{
796
    int ret = -1;
797
    char *volpath = NULL;
798 799 800

    virCommandPtr lvchange_cmd = NULL;
    virCommandPtr lvremove_cmd = NULL;
801

E
Eric Blake 已提交
802 803
    virCheckFlags(0, -1);

804
    if (virAsprintf(&volpath, "%s/%s",
805
                    pool->def->source.name, vol->name) < 0)
806
        goto cleanup;
807

808
    virFileWaitForDevices();
809

810 811
    lvchange_cmd = virCommandNewArgList(LVCHANGE, "-aln", volpath, NULL);
    lvremove_cmd = virCommandNewArgList(LVREMOVE, "-f", volpath, NULL);
812

813 814 815 816 817 818 819 820 821 822 823
    if (virCommandRun(lvremove_cmd, NULL) < 0) {
        if (virCommandRun(lvchange_cmd, NULL) < 0) {
            goto cleanup;
        } else {
            if (virCommandRun(lvremove_cmd, NULL) < 0)
                goto cleanup;
        }
    }

    ret = 0;
cleanup:
824
    VIR_FREE(volpath);
825 826 827 828
    virCommandFree(lvchange_cmd);
    virCommandFree(lvremove_cmd);
    return ret;
}
829 830 831 832

virStorageBackend virStorageBackendLogical = {
    .type = VIR_STORAGE_POOL_LOGICAL,

833
    .findPoolSources = virStorageBackendLogicalFindPoolSources,
834
    .checkPool = virStorageBackendLogicalCheckPool,
835 836 837 838 839
    .startPool = virStorageBackendLogicalStartPool,
    .buildPool = virStorageBackendLogicalBuildPool,
    .refreshPool = virStorageBackendLogicalRefreshPool,
    .stopPool = virStorageBackendLogicalStopPool,
    .deletePool = virStorageBackendLogicalDeletePool,
840 841
    .buildVol = NULL,
    .buildVolFrom = virStorageBackendLogicalBuildVolFrom,
842 843 844
    .createVol = virStorageBackendLogicalCreateVol,
    .deleteVol = virStorageBackendLogicalDeleteVol,
};