storage_backend_iscsi.c 16.8 KB
Newer Older
1 2 3
/*
 * storage_backend_iscsi.c: storage backend for iSCSI handling
 *
J
Jim Meyering 已提交
4
 * Copyright (C) 2007-2008, 2010 Red Hat, Inc.
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
 * 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
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

#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>
#include <dirent.h>
D
David Allan 已提交
36
#include <sys/stat.h>
37

38
#include "virterror_internal.h"
39
#include "storage_backend_scsi.h"
40 41
#include "storage_backend_iscsi.h"
#include "util.h"
42
#include "memory.h"
D
David Allan 已提交
43
#include "logging.h"
44

45 46
#define VIR_FROM_THIS VIR_FROM_STORAGE

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
static int
virStorageBackendISCSITargetIP(virConnectPtr conn,
                               const char *hostname,
                               char *ipaddr,
                               size_t ipaddrlen)
{
    struct addrinfo hints;
    struct addrinfo *result = NULL;
    int ret;

    memset(&hints, 0, sizeof hints);
    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) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              _("host lookup failed %s"),
                              gai_strerror(ret));
        return -1;
    }

    if (result == NULL) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              _("no IP address for target %s"),
                              hostname);
        return -1;
    }

    if (getnameinfo(result->ai_addr, result->ai_addrlen,
                    ipaddr, ipaddrlen, NULL, 0,
                    NI_NUMERICHOST) < 0) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              _("cannot format ip addr for %s"),
                              hostname);
        freeaddrinfo(result);
        return -1;
    }

    freeaddrinfo(result);
    return 0;
}

static int
93
virStorageBackendISCSIExtractSession(virConnectPtr conn ATTRIBUTE_UNUSED,
94 95 96 97 98 99 100 101
                                     virStoragePoolObjPtr pool,
                                     char **const groups,
                                     void *data)
{
    char **session = data;

    if (STREQ(groups[1], pool->def->source.devices[0].path)) {
        if ((*session = strdup(groups[0])) == NULL) {
102
            virReportOOMError();
103 104 105 106 107 108 109 110 111
            return -1;
        }
    }

    return 0;
}

static char *
virStorageBackendISCSISession(virConnectPtr conn,
112 113
                              virStoragePoolObjPtr pool,
                              int probe)
114 115
{
    /*
116
     * # iscsiadm --mode session
117 118 119 120 121 122 123 124 125 126 127
     * 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,
    };
128
    const char *const prog[] = {
129
        ISCSIADM, "--mode", "session", NULL
130 131 132
    };
    char *session = NULL;

133 134 135 136
    /* 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.
     */
137 138 139 140 141 142
    if (virStorageBackendRunProgRegex(conn, pool,
                                      prog,
                                      1,
                                      regexes,
                                      vars,
                                      virStorageBackendISCSIExtractSession,
143 144
                                      &session,
                                      NULL) < 0)
145 146
        return NULL;

147 148
    if (session == NULL &&
        !probe) {
149
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
150
                              "%s", _("cannot find session"));
151 152 153 154 155 156
        return NULL;
    }

    return session;
}

D
David Allan 已提交
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

#define LINE_SIZE 4096

static int
virStorageBackendIQNFound(virConnectPtr conn,
                          virStoragePoolObjPtr pool,
                          char **ifacename)
{
    int ret = IQN_MISSING, fd = -1;
    char ebuf[64];
    FILE *fp = NULL;
    pid_t child = 0;
    char *line = NULL, *newline = NULL, *iqn = NULL, *token = NULL,
        *saveptr = NULL;
    const char *const prog[] = {
        ISCSIADM, "--mode", "iface", NULL
    };

    if (VIR_ALLOC_N(line, LINE_SIZE) != 0) {
        ret = IQN_ERROR;
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              _("Could not allocate memory for output of '%s'"),
                              prog[0]);
        goto out;
    }

    memset(line, 0, LINE_SIZE);

185
    if (virExec(prog, NULL, NULL, &child, -1, &fd, NULL, VIR_EXEC_NONE) < 0) {
D
David Allan 已提交
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
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              _("Failed to run '%s' when looking for existing interface with IQN '%s'"),
                              prog[0], pool->def->source.initiator.iqn);

        ret = IQN_ERROR;
        goto out;
    }

    if ((fp = fdopen(fd, "r")) == NULL) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              _("Failed to open stream for file descriptor "
                                "when reading output from '%s': '%s'"),
                              prog[0], virStrerror(errno, ebuf, sizeof ebuf));
        ret = IQN_ERROR;
        goto out;
    }

    while (fgets(line, LINE_SIZE, fp) != NULL) {
        newline = strrchr(line, '\n');
        if (newline == NULL) {
            ret = IQN_ERROR;
            virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                                  _("Unexpected line > %d characters "
                                    "when parsing output of '%s'"),
                                  LINE_SIZE, prog[0]);
            goto out;
        }
        *newline = '\0';

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

        if (STREQ(iqn, pool->def->source.initiator.iqn)) {
            token = strtok_r(line, " ", &saveptr);
            *ifacename = strdup(token);
            if (*ifacename == NULL) {
                ret = IQN_ERROR;
226
                virReportOOMError();
D
David Allan 已提交
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
                goto out;
            }
            VIR_DEBUG("Found interface '%s' with IQN '%s'", *ifacename, iqn);
            ret = IQN_FOUND;
            break;
        }
    }

out:
    if (ret == IQN_MISSING) {
        VIR_DEBUG("Could not find interface witn IQN '%s'", iqn);
    }

    VIR_FREE(line);
    if (fp != NULL) {
        fclose(fp);
    } else {
        if (fd != -1) {
            close(fd);
        }
    }

    return ret;
}


static int
virStorageBackendCreateIfaceIQN(virConnectPtr conn,
                             virStoragePoolObjPtr pool,
                             char **ifacename)
{
    int ret = -1, exitstatus = -1;
    char temp_ifacename[32];

    if (virRandomInitialize(time(NULL) ^ getpid()) == -1) {
J
Jim Meyering 已提交
262
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR, "%s",
D
David Allan 已提交
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
                              _("Failed to initialize random generator "
                                "when creating iscsi interface"));
        goto out;
    }

    snprintf(temp_ifacename, sizeof(temp_ifacename), "libvirt-iface-%08x", virRandom(1024 * 1024 * 1024));

    const char *const cmdargv1[] = {
        ISCSIADM, "--mode", "iface", "--interface",
        &temp_ifacename[0], "--op", "new", NULL
    };

    VIR_DEBUG("Attempting to create interface '%s' with IQN '%s'",
              &temp_ifacename[0], pool->def->source.initiator.iqn);

    /* 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. */
282
    if (virRun(cmdargv1, &exitstatus) < 0) {
D
David Allan 已提交
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              _("Failed to run command '%s' to create new iscsi interface"),
                              cmdargv1[0]);
        goto out;
    }

    const char *const cmdargv2[] = {
        ISCSIADM, "--mode", "iface", "--interface", &temp_ifacename[0],
        "--op", "update", "--name", "iface.initiatorname", "--value",
        pool->def->source.initiator.iqn, NULL
    };

    /* 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. */
298
    if (virRun(cmdargv2, &exitstatus) < 0) {
D
David Allan 已提交
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
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              _("Failed to run command '%s' to update iscsi interface with IQN '%s'"),
                              cmdargv1[0], pool->def->source.initiator.iqn);
        goto out;
    }

    /* Check again to make sure the interface was created. */
    if (virStorageBackendIQNFound(conn, pool, ifacename) != IQN_FOUND) {
        VIR_DEBUG("Failed to find interface '%s' with IQN '%s' "
                  "after attempting to create it",
                  &temp_ifacename[0], pool->def->source.initiator.iqn);
        goto out;
    } else {
        VIR_DEBUG("Interface '%s' with IQN '%s' was created successfully",
                  *ifacename, pool->def->source.initiator.iqn);
    }

    ret = 0;

out:
    if (ret != 0)
        VIR_FREE(*ifacename);
    return ret;
}


static int
virStorageBackendISCSIConnectionIQN(virConnectPtr conn,
                                    virStoragePoolObjPtr pool,
                                    const char *portal,
                                    const char *action)
{
    int ret = -1;
    char *ifacename = NULL;

    switch (virStorageBackendIQNFound(conn, pool, &ifacename)) {
    case IQN_FOUND:
        VIR_DEBUG("ifacename: '%s'", ifacename);
        break;
    case IQN_MISSING:
        if (virStorageBackendCreateIfaceIQN(conn, pool, &ifacename) != 0) {
            goto out;
        }
        break;
    case IQN_ERROR:
    default:
        goto out;
    }

    const char *const sendtargets[] = {
        ISCSIADM, "--mode", "discovery", "--type", "sendtargets", "--portal", portal, NULL
    };
351
    if (virRun(sendtargets, NULL) < 0) {
D
David Allan 已提交
352 353 354 355 356 357 358 359 360 361 362 363
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              _("Failed to run %s to get target list"),
                              sendtargets[0]);
        goto out;
    }

    const char *const cmdargv[] = {
        ISCSIADM, "--mode", "node", "--portal", portal,
        "--targetname", pool->def->source.devices[0].path, "--interface",
        ifacename, action, NULL
    };

364
    if (virRun(cmdargv, NULL) < 0) {
D
David Allan 已提交
365 366 367 368 369 370 371 372 373 374 375 376 377 378
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              _("Failed to run command '%s' with action '%s'"),
                              cmdargv[0], action);
        goto out;
    }

    ret = 0;

out:
    VIR_FREE(ifacename);
    return ret;
}


379 380 381 382 383 384
static int
virStorageBackendISCSIConnection(virConnectPtr conn,
                                 virStoragePoolObjPtr pool,
                                 const char *portal,
                                 const char *action)
{
D
David Allan 已提交
385
    int ret = 0;
386

D
David Allan 已提交
387
    if (pool->def->source.initiator.iqn != NULL) {
388

D
David Allan 已提交
389 390 391 392 393 394 395 396 397
        ret = virStorageBackendISCSIConnectionIQN(conn, pool, portal, action);

    } else {

        const char *const cmdargv[] = {
            ISCSIADM, "--mode", "node", "--portal", portal,
            "--targetname", pool->def->source.devices[0].path, action, NULL
        };

398
        if (virRun(cmdargv, NULL) < 0) {
D
David Allan 已提交
399 400 401 402 403 404
            ret = -1;
        }

    }

    return ret;
405 406
}

407

408
static int
409 410 411
virStorageBackendISCSIFindLUs(virConnectPtr conn,
                              virStoragePoolObjPtr pool,
                              const char *session)
412
{
413
    char sysfs_path[PATH_MAX];
414 415
    int retval = 0;
    uint32_t host;
416 417 418 419

    snprintf(sysfs_path, PATH_MAX,
             "/sys/class/iscsi_session/session%s/device", session);

420
    if (virStorageBackendSCSIGetHostNumber(sysfs_path, &host) < 0) {
421
        virReportSystemError(errno,
422 423
                             _("Failed to get host number for iSCSI session "
                               "with path '%s'"),
424
                             sysfs_path);
425
        retval = -1;
426 427
    }

428
    if (virStorageBackendSCSIFindLUs(conn, pool, host) < 0) {
429
        virReportSystemError(errno,
430 431
                             _("Failed to find LUs on host %u"), host);
        retval = -1;
432 433 434 435
    }

    return retval;
}
436 437

static int
438
virStorageBackendISCSIRescanLUNs(virConnectPtr conn ATTRIBUTE_UNUSED,
439 440 441
                                 virStoragePoolObjPtr pool ATTRIBUTE_UNUSED,
                                 const char *session)
{
442
    const char *const cmdargv[] = {
443 444 445
        ISCSIADM, "--mode", "session", "-r", session, "-R", NULL,
    };

446
    if (virRun(cmdargv, NULL) < 0)
447 448 449 450 451 452 453 454 455 456 457
        return -1;

    return 0;
}


static int
virStorageBackendISCSILogin(virConnectPtr conn,
                            virStoragePoolObjPtr pool,
                            const char *portal)
{
458 459 460 461 462
    const char *const cmdsendtarget[] = {
        ISCSIADM, "--mode", "discovery", "--type", "sendtargets",
        "--portal", portal, NULL
    };

463
    if (virRun(cmdsendtarget, NULL) < 0)
464 465
        return -1;

466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
    return virStorageBackendISCSIConnection(conn, pool, portal, "--login");
}

static int
virStorageBackendISCSILogout(virConnectPtr conn,
                             virStoragePoolObjPtr pool,
                             const char *portal)
{
    return virStorageBackendISCSIConnection(conn, pool, portal, "--logout");
}

static char *
virStorageBackendISCSIPortal(virConnectPtr conn,
                             virStoragePoolObjPtr pool)
{
    char ipaddr[NI_MAXHOST];
    char *portal;

    if (virStorageBackendISCSITargetIP(conn,
                                       pool->def->source.host.name,
                                       ipaddr, sizeof(ipaddr)) < 0)
        return NULL;

489
    if (VIR_ALLOC_N(portal, strlen(ipaddr) + 1 + 4 + 2 + 1) < 0) {
490
        virReportOOMError();
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
        return NULL;
    }

    strcpy(portal, ipaddr);
    strcat(portal, ":3260,1");

    return portal;
}


static int
virStorageBackendISCSIStartPool(virConnectPtr conn,
                                virStoragePoolObjPtr pool)
{
    char *portal = NULL;
506
    char *session;
507 508 509

    if (pool->def->source.host.name == NULL) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
510
                              "%s", _("missing source host"));
511 512 513 514 515 516
        return -1;
    }

    if (pool->def->source.ndevice != 1 ||
        pool->def->source.devices[0].path == NULL) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
517
                              "%s", _("missing source device"));
518 519 520
        return -1;
    }

521 522 523 524 525 526 527
    if ((session = virStorageBackendISCSISession(conn, pool, 1)) == NULL) {
        if ((portal = virStorageBackendISCSIPortal(conn, pool)) == NULL)
            return -1;
        if (virStorageBackendISCSILogin(conn, pool, portal) < 0) {
            VIR_FREE(portal);
            return -1;
        }
528
        VIR_FREE(portal);
529 530
    } else {
        VIR_FREE(session);
531 532 533 534 535 536 537 538 539 540 541 542
    }
    return 0;
}

static int
virStorageBackendISCSIRefreshPool(virConnectPtr conn,
                                  virStoragePoolObjPtr pool)
{
    char *session = NULL;

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

543
    if ((session = virStorageBackendISCSISession(conn, pool, 0)) == NULL)
544 545 546
        goto cleanup;
    if (virStorageBackendISCSIRescanLUNs(conn, pool, session) < 0)
        goto cleanup;
547
    if (virStorageBackendISCSIFindLUs(conn, pool, session) < 0)
548
        goto cleanup;
549
    VIR_FREE(session);
550 551 552 553

    return 0;

 cleanup:
554
    VIR_FREE(session);
555 556 557 558 559 560 561 562 563 564 565 566 567 568
    return -1;
}


static int
virStorageBackendISCSIStopPool(virConnectPtr conn,
                               virStoragePoolObjPtr pool)
{
    char *portal;

    if ((portal = virStorageBackendISCSIPortal(conn, pool)) == NULL)
        return -1;

    if (virStorageBackendISCSILogout(conn, pool, portal) < 0) {
569
        VIR_FREE(portal);
570 571
        return -1;
    }
572
    VIR_FREE(portal);
573 574 575 576 577

    return 0;
}

virStorageBackend virStorageBackendISCSI = {
578
    .type = VIR_STORAGE_POOL_ISCSI,
579

580 581 582
    .startPool = virStorageBackendISCSIStartPool,
    .refreshPool = virStorageBackendISCSIRefreshPool,
    .stopPool = virStorageBackendISCSIStopPool,
583
};