storage_backend_iscsi.c 24.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 33 34 35
#include <sys/socket.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <stdio.h>
#include <regex.h>
#include <fcntl.h>
#include <unistd.h>
D
David Allan 已提交
36
#include <sys/stat.h>
37

38
#include "virerror.h"
39
#include "storage_backend_scsi.h"
40
#include "storage_backend_iscsi.h"
41
#include "virutil.h"
42
#include "viralloc.h"
43
#include "virlog.h"
E
Eric Blake 已提交
44
#include "virfile.h"
45
#include "vircommand.h"
46
#include "virrandom.h"
47

48 49
#define VIR_FROM_THIS VIR_FROM_STORAGE

50
static int
51
virStorageBackendISCSITargetIP(const char *hostname,
52 53 54 55 56 57 58
                               char *ipaddr,
                               size_t ipaddrlen)
{
    struct addrinfo hints;
    struct addrinfo *result = NULL;
    int ret;

59
    memset(&hints, 0, sizeof(hints));
60 61 62 63 64 65 66
    hints.ai_flags = AI_ADDRCONFIG;
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = 0;

    ret = getaddrinfo(hostname, NULL, &hints, &result);
    if (ret != 0) {
67 68 69
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("host lookup failed %s"),
                       gai_strerror(ret));
70 71 72 73
        return -1;
    }

    if (result == NULL) {
74 75 76
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("no IP address for target %s"),
                       hostname);
77 78 79 80 81 82
        return -1;
    }

    if (getnameinfo(result->ai_addr, result->ai_addrlen,
                    ipaddr, ipaddrlen, NULL, 0,
                    NI_NUMERICHOST) < 0) {
83 84 85
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot format ip addr for %s"),
                       hostname);
86 87 88 89 90 91 92 93
        freeaddrinfo(result);
        return -1;
    }

    freeaddrinfo(result);
    return 0;
}

94 95 96 97 98 99
static char *
virStorageBackendISCSIPortal(virStoragePoolSourcePtr source)
{
    char ipaddr[NI_MAXHOST];
    char *portal;

100
    if (source->nhost != 1) {
101 102
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Expected exactly 1 host for the storage pool"));
103 104 105 106
        return NULL;
    }

    if (virStorageBackendISCSITargetIP(source->hosts[0].name,
107 108 109 110
                                       ipaddr, sizeof(ipaddr)) < 0)
        return NULL;

    if (virAsprintf(&portal, "%s:%d,1", ipaddr,
111 112
                    source->hosts[0].port ?
                    source->hosts[0].port : 3260) < 0) {
113 114 115 116 117 118 119 120
        virReportOOMError();
        return NULL;
    }

    return portal;
}


121
static int
122
virStorageBackendISCSIExtractSession(virStoragePoolObjPtr pool,
123 124 125 126 127 128 129
                                     char **const groups,
                                     void *data)
{
    char **session = data;

    if (STREQ(groups[1], pool->def->source.devices[0].path)) {
        if ((*session = strdup(groups[0])) == NULL) {
130
            virReportOOMError();
131 132 133 134 135 136 137 138
            return -1;
        }
    }

    return 0;
}

static char *
139
virStorageBackendISCSISession(virStoragePoolObjPtr pool,
140
                              int probe)
141 142
{
    /*
143
     * # iscsiadm --mode session
144 145 146 147 148 149 150 151 152 153 154 155 156
     * 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;

157 158
    virCommandPtr cmd = virCommandNewArgList(ISCSIADM, "--mode", "session", NULL);

159 160 161 162
    /* 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.
     */
163
    if (virStorageBackendRunProgRegex(pool,
164
                                      cmd,
165 166 167 168
                                      1,
                                      regexes,
                                      vars,
                                      virStorageBackendISCSIExtractSession,
169
                                      &session, NULL) < 0)
170
        goto cleanup;
171

172 173
    if (session == NULL &&
        !probe) {
174 175
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot find session"));
176
        goto cleanup;
177 178
    }

179 180
cleanup:
    virCommandFree(cmd);
181 182 183
    return session;
}

D
David Allan 已提交
184 185 186 187

#define LINE_SIZE 4096

static int
188
virStorageBackendIQNFound(const char *initiatoriqn,
D
David Allan 已提交
189 190 191 192 193
                          char **ifacename)
{
    int ret = IQN_MISSING, fd = -1;
    char ebuf[64];
    FILE *fp = NULL;
E
Eric Blake 已提交
194
    char *line = NULL, *newline = NULL, *iqn = NULL, *token = NULL;
195 196
    virCommandPtr cmd = virCommandNewArgList(ISCSIADM,
                                             "--mode", "iface", NULL);
D
David Allan 已提交
197 198 199

    if (VIR_ALLOC_N(line, LINE_SIZE) != 0) {
        ret = IQN_ERROR;
200 201 202
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not allocate memory for output of '%s'"),
                       ISCSIADM);
D
David Allan 已提交
203 204 205 206 207
        goto out;
    }

    memset(line, 0, LINE_SIZE);

208 209
    virCommandSetOutputFD(cmd, &fd);
    if (virCommandRunAsync(cmd, NULL) < 0) {
D
David Allan 已提交
210 211 212 213
        ret = IQN_ERROR;
        goto out;
    }

214
    if ((fp = VIR_FDOPEN(fd, "r")) == NULL) {
215 216 217 218
        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 已提交
219 220 221 222 223 224 225 226
        ret = IQN_ERROR;
        goto out;
    }

    while (fgets(line, LINE_SIZE, fp) != NULL) {
        newline = strrchr(line, '\n');
        if (newline == NULL) {
            ret = IQN_ERROR;
227 228 229 230
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unexpected line > %d characters "
                             "when parsing output of '%s'"),
                           LINE_SIZE, ISCSIADM);
D
David Allan 已提交
231 232 233 234 235 236 237 238 239 240
            goto out;
        }
        *newline = '\0';

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

241
        if (STREQ(iqn, initiatoriqn)) {
E
Eric Blake 已提交
242 243 244
            token = strchr(line, ' ');
            if (!token) {
                ret = IQN_ERROR;
245 246 247
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Missing space when parsing output "
                                 "of '%s'"), ISCSIADM);
E
Eric Blake 已提交
248 249 250
                goto out;
            }
            *ifacename = strndup(line, token - line);
D
David Allan 已提交
251 252
            if (*ifacename == NULL) {
                ret = IQN_ERROR;
253
                virReportOOMError();
D
David Allan 已提交
254 255 256 257 258 259 260 261
                goto out;
            }
            VIR_DEBUG("Found interface '%s' with IQN '%s'", *ifacename, iqn);
            ret = IQN_FOUND;
            break;
        }
    }

262 263 264
    if (virCommandWait(cmd, NULL) < 0)
        ret = IQN_ERROR;

D
David Allan 已提交
265 266
out:
    if (ret == IQN_MISSING) {
267
        VIR_DEBUG("Could not find interface with IQN '%s'", iqn);
D
David Allan 已提交
268 269 270
    }

    VIR_FREE(line);
271 272
    VIR_FORCE_FCLOSE(fp);
    VIR_FORCE_CLOSE(fd);
273
    virCommandFree(cmd);
D
David Allan 已提交
274 275 276 277 278 279

    return ret;
}


static int
280
virStorageBackendCreateIfaceIQN(const char *initiatoriqn,
281
                                char **ifacename)
D
David Allan 已提交
282 283
{
    int ret = -1, exitstatus = -1;
284 285
    char *temp_ifacename;
    virCommandPtr cmd = NULL;
D
David Allan 已提交
286

287 288 289 290 291 292
    if (virAsprintf(&temp_ifacename,
                    "libvirt-iface-%08llx",
                    (unsigned long long)virRandomBits(30)) < 0) {
        virReportOOMError();
        return -1;
    }
D
David Allan 已提交
293 294

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

297 298 299 300 301
    cmd = virCommandNewArgList(ISCSIADM,
                               "--mode", "iface",
                               "--interface", temp_ifacename,
                               "--op", "new",
                               NULL);
D
David Allan 已提交
302 303 304 305
    /* 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. */
306
    if (virCommandRun(cmd, &exitstatus) < 0) {
307 308 309
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to run command '%s' to create new iscsi interface"),
                       ISCSIADM);
310
        goto cleanup;
D
David Allan 已提交
311
    }
312
    virCommandFree(cmd);
D
David Allan 已提交
313

314 315 316 317 318 319 320 321
    cmd = virCommandNewArgList(ISCSIADM,
                               "--mode", "iface",
                               "--interface", temp_ifacename,
                               "--op", "update",
                               "--name", "iface.initiatorname",
                               "--value",
                               initiatoriqn,
                               NULL);
D
David Allan 已提交
322 323 324
    /* 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. */
325
    if (virCommandRun(cmd, &exitstatus) < 0) {
326 327 328
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to run command '%s' to update iscsi interface with IQN '%s'"),
                       ISCSIADM, initiatoriqn);
329
        goto cleanup;
D
David Allan 已提交
330 331 332
    }

    /* Check again to make sure the interface was created. */
333
    if (virStorageBackendIQNFound(initiatoriqn, ifacename) != IQN_FOUND) {
D
David Allan 已提交
334 335
        VIR_DEBUG("Failed to find interface '%s' with IQN '%s' "
                  "after attempting to create it",
336
                  &temp_ifacename[0], initiatoriqn);
337
        goto cleanup;
D
David Allan 已提交
338 339
    } else {
        VIR_DEBUG("Interface '%s' with IQN '%s' was created successfully",
340
                  *ifacename, initiatoriqn);
D
David Allan 已提交
341 342 343 344
    }

    ret = 0;

345 346 347
cleanup:
    virCommandFree(cmd);
    VIR_FREE(temp_ifacename);
D
David Allan 已提交
348 349 350 351 352 353
    if (ret != 0)
        VIR_FREE(*ifacename);
    return ret;
}


354

D
David Allan 已提交
355
static int
356 357 358 359
virStorageBackendISCSIConnection(const char *portal,
                                 const char *initiatoriqn,
                                 const char *target,
                                 const char **extraargv)
D
David Allan 已提交
360 361
{
    int ret = -1;
362 363 364 365 366 367 368
    const char *const baseargv[] = {
        ISCSIADM,
        "--mode", "node",
        "--portal", portal,
        "--targetname", target,
        NULL
    };
369
    virCommandPtr cmd;
D
David Allan 已提交
370 371
    char *ifacename = NULL;

372 373
    cmd = virCommandNewArgs(baseargv);
    virCommandAddArgSet(cmd, extraargv);
D
David Allan 已提交
374

375 376 377 378 379 380
    if (initiatoriqn) {
        switch (virStorageBackendIQNFound(initiatoriqn, &ifacename)) {
        case IQN_FOUND:
            VIR_DEBUG("ifacename: '%s'", ifacename);
            break;
        case IQN_MISSING:
381 382
            if (virStorageBackendCreateIfaceIQN(initiatoriqn,
                                                &ifacename) != 0) {
383 384 385 386 387 388 389
                goto cleanup;
            }
            break;
        case IQN_ERROR:
        default:
            goto cleanup;
        }
390
        virCommandAddArgList(cmd, "--interface", ifacename, NULL);
D
David Allan 已提交
391
    }
392

393
    if (virCommandRun(cmd, NULL) < 0)
394
        goto cleanup;
D
David Allan 已提交
395 396 397

    ret = 0;

398
cleanup:
399
    virCommandFree(cmd);
D
David Allan 已提交
400 401 402
    VIR_FREE(ifacename);

    return ret;
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
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;
}
441

442
static int
443
virStorageBackendISCSIFindLUs(virStoragePoolObjPtr pool,
444
                              const char *session)
445
{
446
    char *sysfs_path;
447 448
    int retval = 0;
    uint32_t host;
449

450 451 452 453 454
    if (virAsprintf(&sysfs_path,
                    "/sys/class/iscsi_session/session%s/device", session) < 0) {
        virReportOOMError();
        return -1;
    }
455

456
    if (virStorageBackendISCSIGetHostNumber(sysfs_path, &host) < 0) {
457
        virReportSystemError(errno,
458 459
                             _("Failed to get host number for iSCSI session "
                               "with path '%s'"),
460
                             sysfs_path);
461
        retval = -1;
462 463
    }

464
    if (virStorageBackendSCSIFindLUs(pool, host) < 0) {
465
        virReportSystemError(errno,
466 467
                             _("Failed to find LUs on host %u"), host);
        retval = -1;
468 469
    }

470 471
    VIR_FREE(sysfs_path);

472 473
    return retval;
}
474 475

static int
476
virStorageBackendISCSIRescanLUNs(virStoragePoolObjPtr pool ATTRIBUTE_UNUSED,
477 478
                                 const char *session)
{
479 480 481 482 483 484 485 486
    virCommandPtr cmd = virCommandNewArgList(ISCSIADM,
                                             "--mode", "session",
                                             "-r", session,
                                             "-R",
                                             NULL);
    int ret = virCommandRun(cmd, NULL);
    virCommandFree(cmd);
    return ret;
487 488
}

489 490 491 492
struct virStorageBackendISCSITargetList {
    size_t ntargets;
    char **targets;
};
493 494

static int
495 496 497
virStorageBackendISCSIGetTargets(virStoragePoolObjPtr pool ATTRIBUTE_UNUSED,
                                 char **const groups,
                                 void *data)
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
    struct virStorageBackendISCSITargetList *list = data;
    char *target;

    if (!(target = strdup(groups[1]))) {
        virReportOOMError();
        return -1;
    }

    if (VIR_REALLOC_N(list->targets, list->ntargets + 1) < 0) {
        VIR_FREE(target);
        virReportOOMError();
        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*$"
552
    };
553 554
    int vars[] = { 2 };
    struct virStorageBackendISCSITargetList list;
555 556 557 558 559 560 561
    size_t i;
    int ret = -1;
    virCommandPtr cmd = virCommandNewArgList(ISCSIADM,
                                             "--mode", "discovery",
                                             "--type", "sendtargets",
                                             "--portal", portal,
                                             NULL);
562 563 564 565

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

    if (virStorageBackendRunProgRegex(NULL, /* No pool for callback */
566
                                      cmd,
567 568 569 570
                                      1,
                                      regexes,
                                      vars,
                                      virStorageBackendISCSIGetTargets,
571 572
                                      &list, NULL) < 0)
        goto cleanup;
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595

    for (i = 0 ; i < list.ntargets ; i++) {
        /* 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 {
        for (i = 0 ; i < list.ntargets ; i++) {
            VIR_FREE(list.targets[i]);
        }
        VIR_FREE(list.targets);
    }

596 597 598 599
    ret = 0;
cleanup:
    virCommandFree(cmd);
    return ret;
600 601 602
}


603 604 605
static char *
virStorageBackendISCSIFindPoolSources(virConnectPtr conn ATTRIBUTE_UNUSED,
                                      const char *srcSpec,
E
Eric Blake 已提交
606
                                      unsigned int flags)
607 608 609 610 611 612 613 614 615 616 617 618 619
{
    virStoragePoolSourcePtr source = NULL;
    size_t ntargets = 0;
    char **targets = NULL;
    char *ret = NULL;
    int i;
    virStoragePoolSourceList list = {
        .type = VIR_STORAGE_POOL_ISCSI,
        .nsources = 0,
        .sources = NULL
    };
    char *portal = NULL;

E
Eric Blake 已提交
620 621
    virCheckFlags(0, NULL);

622 623 624 625 626 627 628
    if (!srcSpec) {
        virReportError(VIR_ERR_INVALID_ARG,
                       "%s", _("hostname and device path "
                               "must be specified for iscsi sources"));
        return NULL;
    }

629 630 631 632
    if (!(source = virStoragePoolDefParseSourceString(srcSpec,
                                                      list.type)))
        return NULL;

633
    if (source->nhost != 1) {
634 635
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Expected exactly 1 host for the storage pool"));
636 637 638
        goto cleanup;
    }

639 640 641 642 643 644 645 646 647 648 649 650 651 652
    if (!(portal = virStorageBackendISCSIPortal(source)))
        goto cleanup;

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

    if (VIR_ALLOC_N(list.sources, ntargets) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    for (i = 0 ; i < ntargets ; i++) {
E
Eric Blake 已提交
653 654
        if (VIR_ALLOC_N(list.sources[i].devices, 1) < 0 ||
            VIR_ALLOC_N(list.sources[i].hosts, 1) < 0) {
655 656 657
            virReportOOMError();
            goto cleanup;
        }
E
Eric Blake 已提交
658 659
        list.sources[i].nhost = 1;
        list.sources[i].hosts[0] = source->hosts[0];
660 661 662 663 664 665 666 667 668 669 670 671 672
        list.sources[i].initiator = source->initiator;
        list.sources[i].ndevice = 1;
        list.sources[i].devices[0].path = targets[i];
        list.nsources++;
    }

    if (!(ret = virStoragePoolSourceListFormat(&list))) {
        virReportOOMError();
        goto cleanup;
    }

cleanup:
    if (list.sources) {
E
Eric Blake 已提交
673 674
        for (i = 0 ; i < ntargets ; i++) {
            VIR_FREE(list.sources[i].hosts);
675
            VIR_FREE(list.sources[i].devices);
E
Eric Blake 已提交
676
        }
677 678 679 680 681 682 683 684 685 686
        VIR_FREE(list.sources);
    }
    for (i = 0 ; i < ntargets ; i++)
        VIR_FREE(targets[i]);
    VIR_FREE(targets);
    VIR_FREE(portal);
    virStoragePoolSourceFree(source);
    return ret;
}

687 688 689 690 691 692 693 694 695 696
static int
virStorageBackendISCSICheckPool(virConnectPtr conn ATTRIBUTE_UNUSED,
                                virStoragePoolObjPtr pool,
                                bool *isActive)
{
    char *session = NULL;
    int ret = -1;

    *isActive = false;

697
    if (pool->def->source.nhost != 1) {
698 699
         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                        _("Expected exactly 1 host for the storage pool"));
700 701 702 703
        return -1;
    }

    if (pool->def->source.hosts[0].name == NULL) {
704 705
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing source host"));
706 707 708 709 710
        return -1;
    }

    if (pool->def->source.ndevice != 1 ||
        pool->def->source.devices[0].path == NULL) {
711 712
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing source device"));
713 714 715 716 717 718 719 720 721 722 723 724 725
        return -1;
    }

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

    return ret;
}


726
static int
727
virStorageBackendISCSIStartPool(virConnectPtr conn ATTRIBUTE_UNUSED,
728 729 730
                                virStoragePoolObjPtr pool)
{
    char *portal = NULL;
731 732 733
    char *session = NULL;
    int ret = -1;
    const char *loginargv[] = { "--login", NULL };
734

735
    if (pool->def->source.nhost != 1) {
736 737
         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                        _("Expected exactly 1 host for the storage pool"));
738 739 740 741
        return -1;
    }

    if (pool->def->source.hosts[0].name == NULL) {
742 743
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing source host"));
744 745 746 747 748
        return -1;
    }

    if (pool->def->source.ndevice != 1 ||
        pool->def->source.devices[0].path == NULL) {
749 750
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing source device"));
751 752 753
        return -1;
    }

754
    if ((session = virStorageBackendISCSISession(pool, 1)) == NULL) {
755 756 757 758 759 760
        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 :-(
         */
761 762 763
        if (virStorageBackendISCSIScanTargets(portal,
                                              pool->def->source.initiator.iqn,
                                              NULL, NULL) < 0)
764 765 766 767 768 769 770
            goto cleanup;

        if (virStorageBackendISCSIConnection(portal,
                                             pool->def->source.initiator.iqn,
                                             pool->def->source.devices[0].path,
                                             loginargv) < 0)
            goto cleanup;
771
    }
772 773 774 775 776
    ret = 0;

cleanup:
    VIR_FREE(session);
    return ret;
777 778 779
}

static int
780
virStorageBackendISCSIRefreshPool(virConnectPtr conn ATTRIBUTE_UNUSED,
781 782 783 784 785 786
                                  virStoragePoolObjPtr pool)
{
    char *session = NULL;

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

787
    if ((session = virStorageBackendISCSISession(pool, 0)) == NULL)
788
        goto cleanup;
789
    if (virStorageBackendISCSIRescanLUNs(pool, session) < 0)
790
        goto cleanup;
791
    if (virStorageBackendISCSIFindLUs(pool, session) < 0)
792
        goto cleanup;
793
    VIR_FREE(session);
794 795 796 797

    return 0;

 cleanup:
798
    VIR_FREE(session);
799 800 801 802 803
    return -1;
}


static int
804
virStorageBackendISCSIStopPool(virConnectPtr conn ATTRIBUTE_UNUSED,
805 806
                               virStoragePoolObjPtr pool)
{
807
    const char *logoutargv[] = { "--logout", NULL };
808
    char *portal;
809
    int ret = -1;
810

811
    if ((portal = virStorageBackendISCSIPortal(&pool->def->source)) == NULL)
812 813
        return -1;

814 815 816 817 818 819
    if (virStorageBackendISCSIConnection(portal,
                                         pool->def->source.initiator.iqn,
                                         pool->def->source.devices[0].path,
                                         logoutargv) < 0)
        goto cleanup;
    ret = 0;
820

821 822 823
cleanup:
    VIR_FREE(portal);
    return ret;
824 825 826
}

virStorageBackend virStorageBackendISCSI = {
827
    .type = VIR_STORAGE_POOL_ISCSI,
828

829
    .checkPool = virStorageBackendISCSICheckPool,
830 831 832
    .startPool = virStorageBackendISCSIStartPool,
    .refreshPool = virStorageBackendISCSIRefreshPool,
    .stopPool = virStorageBackendISCSIStopPool,
833
    .findPoolSources = virStorageBackendISCSIFindPoolSources,
834
};