storage_backend_iscsi.c 27.2 KB
Newer Older
1 2 3
/*
 * storage_backend_iscsi.c: storage backend for iSCSI handling
 *
E
Eric Blake 已提交
4
 * Copyright (C) 2007-2008, 2010-2012 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
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

26
#include <dirent.h>
27 28 29 30 31 32
#include <sys/wait.h>
#include <string.h>
#include <stdio.h>
#include <regex.h>
#include <fcntl.h>
#include <unistd.h>
D
David Allan 已提交
33
#include <sys/stat.h>
34

35 36
#include "datatypes.h"
#include "driver.h"
37
#include "virerror.h"
38
#include "storage_backend_scsi.h"
39
#include "storage_backend_iscsi.h"
40
#include "viralloc.h"
41
#include "virlog.h"
E
Eric Blake 已提交
42
#include "virfile.h"
43
#include "vircommand.h"
44
#include "virobject.h"
45
#include "virrandom.h"
46
#include "virstring.h"
47
#include "viruuid.h"
48

49 50
#define VIR_FROM_THIS VIR_FROM_STORAGE

51 52
#define ISCSI_DEFAULT_TARGET_PORT 3260

53 54 55
static char *
virStorageBackendISCSIPortal(virStoragePoolSourcePtr source)
{
56
    char *portal = NULL;
57

58
    if (source->nhost != 1) {
59 60
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Expected exactly 1 host for the storage pool"));
61 62 63
        return NULL;
    }

64 65
    if (source->hosts[0].port == 0)
        source->hosts[0].port = ISCSI_DEFAULT_TARGET_PORT;
66

67 68 69 70
    if (strchr(source->hosts[0].name, ':')) {
        ignore_value(virAsprintf(&portal, "[%s]:%d,1",
                                 source->hosts[0].name,
                                 source->hosts[0].port));
71
    } else {
72 73 74
        ignore_value(virAsprintf(&portal, "%s:%d,1",
                                 source->hosts[0].name,
                                 source->hosts[0].port));
75 76 77 78 79 80
    }

    return portal;
}


81
static int
82
virStorageBackendISCSIExtractSession(virStoragePoolObjPtr pool,
83 84 85 86 87
                                     char **const groups,
                                     void *data)
{
    char **session = data;

88 89
    if (STREQ(groups[1], pool->def->source.devices[0].path))
        return VIR_STRDUP(*session, groups[0]);
90 91 92 93
    return 0;
}

static char *
94
virStorageBackendISCSISession(virStoragePoolObjPtr pool,
95
                              int probe)
96 97
{
    /*
98
     * # iscsiadm --mode session
99 100 101 102 103 104 105 106 107 108 109 110 111
     * tcp: [1] 192.168.122.170:3260,1 demo-tgt-b
     * tcp: [2] 192.168.122.170:3260,1 demo-tgt-a
     *
     * Pull out 2nd and 4th fields
     */
    const char *regexes[] = {
        "^tcp:\\s+\\[(\\S+)\\]\\s+\\S+\\s+(\\S+)\\s*$"
    };
    int vars[] = {
        2,
    };
    char *session = NULL;

112 113
    virCommandPtr cmd = virCommandNewArgList(ISCSIADM, "--mode", "session", NULL);

114 115 116 117
    /* Note that we ignore the exitstatus.  Older versions of iscsiadm tools
     * returned an exit status of > 0, even if they succeeded.  We will just
     * rely on whether session got filled in properly.
     */
118
    if (virStorageBackendRunProgRegex(pool,
119
                                      cmd,
120 121 122 123
                                      1,
                                      regexes,
                                      vars,
                                      virStorageBackendISCSIExtractSession,
124
                                      &session, NULL) < 0)
125
        goto cleanup;
126

127 128
    if (session == NULL &&
        !probe) {
129 130
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot find session"));
131
        goto cleanup;
132 133
    }

134 135
cleanup:
    virCommandFree(cmd);
136 137 138
    return session;
}

D
David Allan 已提交
139 140 141 142

#define LINE_SIZE 4096

static int
143
virStorageBackendIQNFound(const char *initiatoriqn,
D
David Allan 已提交
144 145 146 147 148
                          char **ifacename)
{
    int ret = IQN_MISSING, fd = -1;
    char ebuf[64];
    FILE *fp = NULL;
E
Eric Blake 已提交
149
    char *line = NULL, *newline = NULL, *iqn = NULL, *token = NULL;
150 151
    virCommandPtr cmd = virCommandNewArgList(ISCSIADM,
                                             "--mode", "iface", NULL);
D
David Allan 已提交
152 153 154

    if (VIR_ALLOC_N(line, LINE_SIZE) != 0) {
        ret = IQN_ERROR;
155 156 157
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not allocate memory for output of '%s'"),
                       ISCSIADM);
D
David Allan 已提交
158 159 160 161 162
        goto out;
    }

    memset(line, 0, LINE_SIZE);

163 164
    virCommandSetOutputFD(cmd, &fd);
    if (virCommandRunAsync(cmd, NULL) < 0) {
D
David Allan 已提交
165 166 167 168
        ret = IQN_ERROR;
        goto out;
    }

169
    if ((fp = VIR_FDOPEN(fd, "r")) == NULL) {
170 171 172 173
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to open stream for file descriptor "
                         "when reading output from '%s': '%s'"),
                       ISCSIADM, virStrerror(errno, ebuf, sizeof(ebuf)));
D
David Allan 已提交
174 175 176 177 178 179 180 181
        ret = IQN_ERROR;
        goto out;
    }

    while (fgets(line, LINE_SIZE, fp) != NULL) {
        newline = strrchr(line, '\n');
        if (newline == NULL) {
            ret = IQN_ERROR;
182 183 184 185
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unexpected line > %d characters "
                             "when parsing output of '%s'"),
                           LINE_SIZE, ISCSIADM);
D
David Allan 已提交
186 187 188 189 190 191 192 193 194 195
            goto out;
        }
        *newline = '\0';

        iqn = strrchr(line, ',');
        if (iqn == NULL) {
            continue;
        }
        iqn++;

196
        if (STREQ(iqn, initiatoriqn)) {
E
Eric Blake 已提交
197 198 199
            token = strchr(line, ' ');
            if (!token) {
                ret = IQN_ERROR;
200 201 202
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Missing space when parsing output "
                                 "of '%s'"), ISCSIADM);
E
Eric Blake 已提交
203 204
                goto out;
            }
205
            if (VIR_STRNDUP(*ifacename, line, token - line) < 0) {
D
David Allan 已提交
206 207 208 209 210 211 212 213 214
                ret = IQN_ERROR;
                goto out;
            }
            VIR_DEBUG("Found interface '%s' with IQN '%s'", *ifacename, iqn);
            ret = IQN_FOUND;
            break;
        }
    }

215 216 217
    if (virCommandWait(cmd, NULL) < 0)
        ret = IQN_ERROR;

D
David Allan 已提交
218 219
out:
    if (ret == IQN_MISSING) {
220
        VIR_DEBUG("Could not find interface with IQN '%s'", iqn);
D
David Allan 已提交
221 222 223
    }

    VIR_FREE(line);
224 225
    VIR_FORCE_FCLOSE(fp);
    VIR_FORCE_CLOSE(fd);
226
    virCommandFree(cmd);
D
David Allan 已提交
227 228 229 230 231 232

    return ret;
}


static int
233
virStorageBackendCreateIfaceIQN(const char *initiatoriqn,
234
                                char **ifacename)
D
David Allan 已提交
235 236
{
    int ret = -1, exitstatus = -1;
237 238
    char *temp_ifacename;
    virCommandPtr cmd = NULL;
D
David Allan 已提交
239

240 241
    if (virAsprintf(&temp_ifacename,
                    "libvirt-iface-%08llx",
242
                    (unsigned long long)virRandomBits(30)) < 0)
243
        return -1;
D
David Allan 已提交
244 245

    VIR_DEBUG("Attempting to create interface '%s' with IQN '%s'",
246
              temp_ifacename, initiatoriqn);
D
David Allan 已提交
247

248 249 250 251 252
    cmd = virCommandNewArgList(ISCSIADM,
                               "--mode", "iface",
                               "--interface", temp_ifacename,
                               "--op", "new",
                               NULL);
D
David Allan 已提交
253 254 255 256
    /* Note that we ignore the exitstatus.  Older versions of iscsiadm
     * tools returned an exit status of > 0, even if they succeeded.
     * We will just rely on whether the interface got created
     * properly. */
257
    if (virCommandRun(cmd, &exitstatus) < 0) {
258 259 260
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to run command '%s' to create new iscsi interface"),
                       ISCSIADM);
261
        goto cleanup;
D
David Allan 已提交
262
    }
263
    virCommandFree(cmd);
D
David Allan 已提交
264

265 266 267 268 269 270 271 272
    cmd = virCommandNewArgList(ISCSIADM,
                               "--mode", "iface",
                               "--interface", temp_ifacename,
                               "--op", "update",
                               "--name", "iface.initiatorname",
                               "--value",
                               initiatoriqn,
                               NULL);
D
David Allan 已提交
273 274 275
    /* Note that we ignore the exitstatus.  Older versions of iscsiadm tools
     * returned an exit status of > 0, even if they succeeded.  We will just
     * rely on whether iface file got updated properly. */
276
    if (virCommandRun(cmd, &exitstatus) < 0) {
277 278 279
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to run command '%s' to update iscsi interface with IQN '%s'"),
                       ISCSIADM, initiatoriqn);
280
        goto cleanup;
D
David Allan 已提交
281 282 283
    }

    /* Check again to make sure the interface was created. */
284
    if (virStorageBackendIQNFound(initiatoriqn, ifacename) != IQN_FOUND) {
D
David Allan 已提交
285 286
        VIR_DEBUG("Failed to find interface '%s' with IQN '%s' "
                  "after attempting to create it",
287
                  &temp_ifacename[0], initiatoriqn);
288
        goto cleanup;
D
David Allan 已提交
289 290
    } else {
        VIR_DEBUG("Interface '%s' with IQN '%s' was created successfully",
291
                  *ifacename, initiatoriqn);
D
David Allan 已提交
292 293 294 295
    }

    ret = 0;

296 297 298
cleanup:
    virCommandFree(cmd);
    VIR_FREE(temp_ifacename);
D
David Allan 已提交
299 300 301 302 303 304
    if (ret != 0)
        VIR_FREE(*ifacename);
    return ret;
}


305

D
David Allan 已提交
306
static int
307 308 309 310
virStorageBackendISCSIConnection(const char *portal,
                                 const char *initiatoriqn,
                                 const char *target,
                                 const char **extraargv)
D
David Allan 已提交
311 312
{
    int ret = -1;
313 314 315 316 317 318 319
    const char *const baseargv[] = {
        ISCSIADM,
        "--mode", "node",
        "--portal", portal,
        "--targetname", target,
        NULL
    };
320
    virCommandPtr cmd;
D
David Allan 已提交
321 322
    char *ifacename = NULL;

323 324
    cmd = virCommandNewArgs(baseargv);
    virCommandAddArgSet(cmd, extraargv);
D
David Allan 已提交
325

326 327 328 329 330 331
    if (initiatoriqn) {
        switch (virStorageBackendIQNFound(initiatoriqn, &ifacename)) {
        case IQN_FOUND:
            VIR_DEBUG("ifacename: '%s'", ifacename);
            break;
        case IQN_MISSING:
332 333
            if (virStorageBackendCreateIfaceIQN(initiatoriqn,
                                                &ifacename) != 0) {
334 335 336 337 338 339 340
                goto cleanup;
            }
            break;
        case IQN_ERROR:
        default:
            goto cleanup;
        }
341
        virCommandAddArgList(cmd, "--interface", ifacename, NULL);
D
David Allan 已提交
342
    }
343

344
    if (virCommandRun(cmd, NULL) < 0)
345
        goto cleanup;
D
David Allan 已提交
346 347 348

    ret = 0;

349
cleanup:
350
    virCommandFree(cmd);
D
David Allan 已提交
351 352 353
    VIR_FREE(ifacename);

    return ret;
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
static int
virStorageBackendISCSIGetHostNumber(const char *sysfs_path,
                                    uint32_t *host)
{
    int retval = 0;
    DIR *sysdir = NULL;
    struct dirent *dirent = NULL;

    VIR_DEBUG("Finding host number from '%s'", sysfs_path);

    virFileWaitForDevices();

    sysdir = opendir(sysfs_path);

    if (sysdir == NULL) {
        virReportSystemError(errno,
                             _("Failed to opendir path '%s'"), sysfs_path);
        retval = -1;
        goto out;
    }

    while ((dirent = readdir(sysdir))) {
        if (STREQLEN(dirent->d_name, "target", strlen("target"))) {
            if (sscanf(dirent->d_name,
                       "target%u:", host) != 1) {
                VIR_DEBUG("Failed to parse target '%s'", dirent->d_name);
                retval = -1;
                break;
            }
        }
    }

    closedir(sysdir);
out:
    return retval;
}
392

393
static int
394
virStorageBackendISCSIFindLUs(virStoragePoolObjPtr pool,
395
                              const char *session)
396
{
397
    char *sysfs_path;
398 399
    int retval = 0;
    uint32_t host;
400

401
    if (virAsprintf(&sysfs_path,
402
                    "/sys/class/iscsi_session/session%s/device", session) < 0)
403
        return -1;
404

405
    if (virStorageBackendISCSIGetHostNumber(sysfs_path, &host) < 0) {
406
        virReportSystemError(errno,
407 408
                             _("Failed to get host number for iSCSI session "
                               "with path '%s'"),
409
                             sysfs_path);
410
        retval = -1;
411 412
    }

413
    if (virStorageBackendSCSIFindLUs(pool, host) < 0) {
414
        virReportSystemError(errno,
415 416
                             _("Failed to find LUs on host %u"), host);
        retval = -1;
417 418
    }

419 420
    VIR_FREE(sysfs_path);

421 422
    return retval;
}
423 424

static int
425
virStorageBackendISCSIRescanLUNs(virStoragePoolObjPtr pool ATTRIBUTE_UNUSED,
426 427
                                 const char *session)
{
428 429 430 431 432 433 434 435
    virCommandPtr cmd = virCommandNewArgList(ISCSIADM,
                                             "--mode", "session",
                                             "-r", session,
                                             "-R",
                                             NULL);
    int ret = virCommandRun(cmd, NULL);
    virCommandFree(cmd);
    return ret;
436 437
}

438 439 440 441
struct virStorageBackendISCSITargetList {
    size_t ntargets;
    char **targets;
};
442 443

static int
444 445 446
virStorageBackendISCSIGetTargets(virStoragePoolObjPtr pool ATTRIBUTE_UNUSED,
                                 char **const groups,
                                 void *data)
447
{
448 449 450
    struct virStorageBackendISCSITargetList *list = data;
    char *target;

451
    if (VIR_STRDUP(target, groups[1]) < 0)
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
        return -1;

    if (VIR_REALLOC_N(list->targets, list->ntargets + 1) < 0) {
        VIR_FREE(target);
        return -1;
    }

    list->targets[list->ntargets] = target;
    list->ntargets++;

    return 0;
}

static int
virStorageBackendISCSITargetAutologin(const char *portal,
                                      const char *initiatoriqn,
                                      const char *target,
                                      bool enable)
{
    const char *extraargv[] = { "--op", "update",
                                "--name", "node.startup",
                                "--value", enable ? "automatic" : "manual",
                                NULL };

    return virStorageBackendISCSIConnection(portal, initiatoriqn, target, extraargv);
}


static int
virStorageBackendISCSIScanTargets(const char *portal,
                                  const char *initiatoriqn,
                                  size_t *ntargetsret,
                                  char ***targetsret)
{
    /**
     *
     * The output of sendtargets is very simple, just two columns,
     * portal then target name
     *
     * 192.168.122.185:3260,1 iqn.2004-04.com:fedora14:iscsi.demo0.bf6d84
     * 192.168.122.185:3260,1 iqn.2004-04.com:fedora14:iscsi.demo1.bf6d84
     * 192.168.122.185:3260,1 iqn.2004-04.com:fedora14:iscsi.demo2.bf6d84
     * 192.168.122.185:3260,1 iqn.2004-04.com:fedora14:iscsi.demo3.bf6d84
     */
    const char *regexes[] = {
        "^\\s*(\\S+)\\s+(\\S+)\\s*$"
498
    };
499 500
    int vars[] = { 2 };
    struct virStorageBackendISCSITargetList list;
501 502 503 504 505 506 507
    size_t i;
    int ret = -1;
    virCommandPtr cmd = virCommandNewArgList(ISCSIADM,
                                             "--mode", "discovery",
                                             "--type", "sendtargets",
                                             "--portal", portal,
                                             NULL);
508 509 510 511

    memset(&list, 0, sizeof(list));

    if (virStorageBackendRunProgRegex(NULL, /* No pool for callback */
512
                                      cmd,
513 514 515 516
                                      1,
                                      regexes,
                                      vars,
                                      virStorageBackendISCSIGetTargets,
517 518
                                      &list, NULL) < 0)
        goto cleanup;
519

520
    for (i = 0; i < list.ntargets; i++) {
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
        /* We have to ignore failure, because we can't undo
         * the results of 'sendtargets', unless we go scrubbing
         * around in the dirt in /var/lib/iscsi.
         */
        if (virStorageBackendISCSITargetAutologin(portal,
                                                  initiatoriqn,
                                                  list.targets[i], false) < 0)
            VIR_WARN("Unable to disable auto-login on iSCSI target %s: %s",
                     portal, list.targets[i]);
    }

    if (ntargetsret && targetsret) {
        *ntargetsret = list.ntargets;
        *targetsret = list.targets;
    } else {
536
        for (i = 0; i < list.ntargets; i++) {
537 538 539 540 541
            VIR_FREE(list.targets[i]);
        }
        VIR_FREE(list.targets);
    }

542 543 544 545
    ret = 0;
cleanup:
    virCommandFree(cmd);
    return ret;
546 547 548
}


549 550 551
static char *
virStorageBackendISCSIFindPoolSources(virConnectPtr conn ATTRIBUTE_UNUSED,
                                      const char *srcSpec,
E
Eric Blake 已提交
552
                                      unsigned int flags)
553 554 555 556 557
{
    virStoragePoolSourcePtr source = NULL;
    size_t ntargets = 0;
    char **targets = NULL;
    char *ret = NULL;
558
    size_t i;
559 560 561 562 563 564 565
    virStoragePoolSourceList list = {
        .type = VIR_STORAGE_POOL_ISCSI,
        .nsources = 0,
        .sources = NULL
    };
    char *portal = NULL;

E
Eric Blake 已提交
566 567
    virCheckFlags(0, NULL);

568 569 570 571 572 573 574
    if (!srcSpec) {
        virReportError(VIR_ERR_INVALID_ARG,
                       "%s", _("hostname and device path "
                               "must be specified for iscsi sources"));
        return NULL;
    }

575 576 577 578
    if (!(source = virStoragePoolDefParseSourceString(srcSpec,
                                                      list.type)))
        return NULL;

579
    if (source->nhost != 1) {
580 581
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Expected exactly 1 host for the storage pool"));
582 583 584
        goto cleanup;
    }

585 586 587 588 589 590 591 592
    if (!(portal = virStorageBackendISCSIPortal(source)))
        goto cleanup;

    if (virStorageBackendISCSIScanTargets(portal,
                                          source->initiator.iqn,
                                          &ntargets, &targets) < 0)
        goto cleanup;

593
    if (VIR_ALLOC_N(list.sources, ntargets) < 0)
594 595
        goto cleanup;

596
    for (i = 0; i < ntargets; i++) {
E
Eric Blake 已提交
597
        if (VIR_ALLOC_N(list.sources[i].devices, 1) < 0 ||
598
            VIR_ALLOC_N(list.sources[i].hosts, 1) < 0)
599
            goto cleanup;
E
Eric Blake 已提交
600 601
        list.sources[i].nhost = 1;
        list.sources[i].hosts[0] = source->hosts[0];
602 603 604 605 606 607
        list.sources[i].initiator = source->initiator;
        list.sources[i].ndevice = 1;
        list.sources[i].devices[0].path = targets[i];
        list.nsources++;
    }

608
    if (!(ret = virStoragePoolSourceListFormat(&list)))
609 610 611 612
        goto cleanup;

cleanup:
    if (list.sources) {
613
        for (i = 0; i < ntargets; i++) {
E
Eric Blake 已提交
614
            VIR_FREE(list.sources[i].hosts);
615
            VIR_FREE(list.sources[i].devices);
E
Eric Blake 已提交
616
        }
617 618
        VIR_FREE(list.sources);
    }
619
    for (i = 0; i < ntargets; i++)
620 621 622 623 624 625 626
        VIR_FREE(targets[i]);
    VIR_FREE(targets);
    VIR_FREE(portal);
    virStoragePoolSourceFree(source);
    return ret;
}

627 628 629 630 631 632 633 634 635 636
static int
virStorageBackendISCSICheckPool(virConnectPtr conn ATTRIBUTE_UNUSED,
                                virStoragePoolObjPtr pool,
                                bool *isActive)
{
    char *session = NULL;
    int ret = -1;

    *isActive = false;

637
    if (pool->def->source.nhost != 1) {
638 639
         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                        _("Expected exactly 1 host for the storage pool"));
640 641 642 643
        return -1;
    }

    if (pool->def->source.hosts[0].name == NULL) {
644 645
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing source host"));
646 647 648 649 650
        return -1;
    }

    if (pool->def->source.ndevice != 1 ||
        pool->def->source.devices[0].path == NULL) {
651 652
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing source device"));
653 654 655 656 657 658 659 660 661 662 663 664
        return -1;
    }

    if ((session = virStorageBackendISCSISession(pool, 1)) != NULL) {
        *isActive = true;
        VIR_FREE(session);
    }
    ret = 0;

    return ret;
}

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
static int
virStorageBackendISCSINodeUpdate(const char *portal,
                                 const char *target,
                                 const char *name,
                                 const char *value)
{
     virCommandPtr cmd = NULL;
     int status;
     int ret = -1;

     cmd = virCommandNewArgList(ISCSIADM,
                                "--mode", "node",
                                "--portal", portal,
                                "--target", target,
                                "--op", "update",
                                "--name", name,
                                "--value", value,
                                NULL);

    if (virCommandRun(cmd, &status) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to update '%s' of node mode for target '%s'"),
                       name, target);
        goto cleanup;
    }

    ret = 0;
cleanup:
    virCommandFree(cmd);
    return ret;
}
696

697
static int
698 699 700 701 702 703 704 705
virStorageBackendISCSISetAuth(const char *portal,
                              virConnectPtr conn,
                              virStoragePoolDefPtr def)
{
    virSecretPtr secret = NULL;
    unsigned char *secret_value = NULL;
    virStoragePoolAuthChap chap;
    int ret = -1;
706
    char uuidStr[VIR_UUID_STRING_BUFLEN];
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

    if (def->source.authType == VIR_STORAGE_POOL_AUTH_NONE)
        return 0;

    if (def->source.authType != VIR_STORAGE_POOL_AUTH_CHAP) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("iscsi pool only supports 'chap' auth type"));
        return -1;
    }

    if (!conn) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("iscsi 'chap' authentication not supported "
                         "for autostarted pools"));
        return -1;
    }

    chap = def->source.auth.chap;
    if (chap.secret.uuidUsable)
        secret = virSecretLookupByUUID(conn, chap.secret.uuid);
    else
        secret = virSecretLookupByUsage(conn, VIR_SECRET_USAGE_TYPE_ISCSI,
                                        chap.secret.usage);

    if (secret) {
        size_t secret_size;
        secret_value =
            conn->secretDriver->secretGetValue(secret, &secret_size, 0,
                                               VIR_SECRET_GET_VALUE_INTERNAL_CALL);
        if (!secret_value) {
737
            if (chap.secret.uuidUsable) {
738
                virUUIDFormat(chap.secret.uuid, uuidStr);
739 740 741
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("could not get the value of the secret "
                                 "for username %s using uuid '%s'"),
742
                                 chap.username, uuidStr);
743 744 745 746 747 748
            } else {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("could not get the value of the secret "
                                 "for username %s using usage value '%s'"),
                                 chap.username, chap.secret.usage);
            }
749 750 751
            goto cleanup;
        }
    } else {
752
        if (chap.secret.uuidUsable) {
753
            virUUIDFormat(chap.secret.uuid, uuidStr);
754 755
            virReportError(VIR_ERR_NO_SECRET,
                           _("no secret matches uuid '%s'"),
756
                           uuidStr);
757 758 759 760 761
        } else {
            virReportError(VIR_ERR_NO_SECRET,
                           _("no secret matches usage value '%s'"),
                           chap.secret.usage);
        }
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
        goto cleanup;
    }

    if (virStorageBackendISCSINodeUpdate(portal,
                                         def->source.devices[0].path,
                                         "node.session.auth.authmethod",
                                         "CHAP") < 0 ||
        virStorageBackendISCSINodeUpdate(portal,
                                         def->source.devices[0].path,
                                         "node.session.auth.username",
                                         chap.username) < 0 ||
        virStorageBackendISCSINodeUpdate(portal,
                                         def->source.devices[0].path,
                                         "node.session.auth.password",
                                         (const char *)secret_value) < 0)
        goto cleanup;

    ret = 0;

cleanup:
    virObjectUnref(secret);
    VIR_FREE(secret_value);
    return ret;
}

static int
virStorageBackendISCSIStartPool(virConnectPtr conn,
789 790 791
                                virStoragePoolObjPtr pool)
{
    char *portal = NULL;
792 793 794
    char *session = NULL;
    int ret = -1;
    const char *loginargv[] = { "--login", NULL };
795

796
    if (pool->def->source.nhost != 1) {
797 798
         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                        _("Expected exactly 1 host for the storage pool"));
799 800 801 802
        return -1;
    }

    if (pool->def->source.hosts[0].name == NULL) {
803 804
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing source host"));
805 806 807 808 809
        return -1;
    }

    if (pool->def->source.ndevice != 1 ||
        pool->def->source.devices[0].path == NULL) {
810 811
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing source device"));
812 813 814
        return -1;
    }

815
    if ((session = virStorageBackendISCSISession(pool, 1)) == NULL) {
816 817 818 819 820 821
        if ((portal = virStorageBackendISCSIPortal(&pool->def->source)) == NULL)
            goto cleanup;
        /*
         * iscsiadm doesn't let you login to a target, unless you've
         * first issued a 'sendtargets' command to the portal :-(
         */
822 823 824
        if (virStorageBackendISCSIScanTargets(portal,
                                              pool->def->source.initiator.iqn,
                                              NULL, NULL) < 0)
825 826
            goto cleanup;

827 828 829
        if (virStorageBackendISCSISetAuth(portal, conn, pool->def) < 0)
            goto cleanup;

830 831 832 833 834
        if (virStorageBackendISCSIConnection(portal,
                                             pool->def->source.initiator.iqn,
                                             pool->def->source.devices[0].path,
                                             loginargv) < 0)
            goto cleanup;
835
    }
836 837 838
    ret = 0;

cleanup:
839
    VIR_FREE(portal);
840 841
    VIR_FREE(session);
    return ret;
842 843 844
}

static int
845
virStorageBackendISCSIRefreshPool(virConnectPtr conn ATTRIBUTE_UNUSED,
846 847 848 849 850 851
                                  virStoragePoolObjPtr pool)
{
    char *session = NULL;

    pool->def->allocation = pool->def->capacity = pool->def->available = 0;

852
    if ((session = virStorageBackendISCSISession(pool, 0)) == NULL)
853
        goto cleanup;
854
    if (virStorageBackendISCSIRescanLUNs(pool, session) < 0)
855
        goto cleanup;
856
    if (virStorageBackendISCSIFindLUs(pool, session) < 0)
857
        goto cleanup;
858
    VIR_FREE(session);
859 860 861 862

    return 0;

 cleanup:
863
    VIR_FREE(session);
864 865 866 867 868
    return -1;
}


static int
869
virStorageBackendISCSIStopPool(virConnectPtr conn ATTRIBUTE_UNUSED,
870 871
                               virStoragePoolObjPtr pool)
{
872
    const char *logoutargv[] = { "--logout", NULL };
873
    char *portal;
874
    int ret = -1;
875

876
    if ((portal = virStorageBackendISCSIPortal(&pool->def->source)) == NULL)
877 878
        return -1;

879 880 881 882 883 884
    if (virStorageBackendISCSIConnection(portal,
                                         pool->def->source.initiator.iqn,
                                         pool->def->source.devices[0].path,
                                         logoutargv) < 0)
        goto cleanup;
    ret = 0;
885

886 887 888
cleanup:
    VIR_FREE(portal);
    return ret;
889 890 891
}

virStorageBackend virStorageBackendISCSI = {
892
    .type = VIR_STORAGE_POOL_ISCSI,
893

894
    .checkPool = virStorageBackendISCSICheckPool,
895 896 897
    .startPool = virStorageBackendISCSIStartPool,
    .refreshPool = virStorageBackendISCSIRefreshPool,
    .stopPool = virStorageBackendISCSIStopPool,
898
    .findPoolSources = virStorageBackendISCSIFindPoolSources,
899
};