viriscsi.c 14.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
/*
 * viriscsi.c: helper APIs for managing iSCSI
 *
 * Copyright (C) 2007-2014 Red Hat, Inc.
 * 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, see
 * <http://www.gnu.org/licenses/>.
 *
 */

#include <config.h>

#include <regex.h>
#include <stdio.h>

#include "viriscsi.h"

#include "viralloc.h"
#include "vircommand.h"
#include "virerror.h"
#include "virfile.h"
#include "virlog.h"
#include "virrandom.h"
#include "virstring.h"

#define VIR_FROM_THIS VIR_FROM_NONE

VIR_LOG_INIT("util.iscsi");


struct virISCSISessionData {
    char *session;
    const char *devpath;
};


static int
virISCSIExtractSession(char **const groups,
                       void *opaque)
{
    struct virISCSISessionData *data = opaque;

    if (STREQ(groups[1], data->devpath))
        return VIR_STRDUP(data->session, groups[0]);
    return 0;
}


char *
virISCSIGetSession(const char *devpath,
                   bool probe)
{
    /*
     * # iscsiadm --mode session
     * 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+).*$"
    };
    int vars[] = {
        2,
    };
    struct virISCSISessionData cbdata = {
        .session = NULL,
        .devpath = devpath,
    };

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

    if (virCommandRunRegex(cmd,
                           1,
                           regexes,
                           vars,
                           virISCSIExtractSession,
                           &cbdata, NULL) < 0)
        goto cleanup;

    if (cbdata.session == NULL && !probe) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot find session"));
        goto cleanup;
    }

99
 cleanup:
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
    virCommandFree(cmd);
    return cbdata.session;
}



#define LINE_SIZE 4096
#define IQN_FOUND 1
#define IQN_MISSING 0
#define IQN_ERROR -1

static int
virStorageBackendIQNFound(const char *initiatoriqn,
                          char **ifacename)
{
    int ret = IQN_MISSING, fd = -1;
    char ebuf[64];
    FILE *fp = NULL;
    char *line = NULL, *newline = NULL, *iqn = NULL, *token = NULL;
    virCommandPtr cmd = virCommandNewArgList(ISCSIADM,
                                             "--mode", "iface", NULL);

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

    memset(line, 0, LINE_SIZE);

    virCommandSetOutputFD(cmd, &fd);
    if (virCommandRunAsync(cmd, NULL) < 0) {
        ret = IQN_ERROR;
        goto out;
    }

    if ((fp = VIR_FDOPEN(fd, "r")) == NULL) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to open stream for file descriptor "
                         "when reading output from '%s': '%s'"),
                       ISCSIADM, 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;
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unexpected line > %d characters "
                             "when parsing output of '%s'"),
                           LINE_SIZE, ISCSIADM);
            goto out;
        }
        *newline = '\0';

        iqn = strrchr(line, ',');
160
        if (iqn == NULL)
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
            continue;
        iqn++;

        if (STREQ(iqn, initiatoriqn)) {
            token = strchr(line, ' ');
            if (!token) {
                ret = IQN_ERROR;
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Missing space when parsing output "
                                 "of '%s'"), ISCSIADM);
                goto out;
            }
            if (VIR_STRNDUP(*ifacename, line, token - line) < 0) {
                ret = IQN_ERROR;
                goto out;
            }
            VIR_DEBUG("Found interface '%s' with IQN '%s'", *ifacename, iqn);
            ret = IQN_FOUND;
            break;
        }
    }

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

186
 out:
187
    if (ret == IQN_MISSING)
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
        VIR_DEBUG("Could not find interface with IQN '%s'", iqn);

    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
    VIR_FORCE_CLOSE(fd);
    virCommandFree(cmd);

    return ret;
}


static int
virStorageBackendCreateIfaceIQN(const char *initiatoriqn,
                                char **ifacename)
{
    int ret = -1, exitstatus = -1;
    char *temp_ifacename;
    virCommandPtr cmd = NULL;

    if (virAsprintf(&temp_ifacename,
                    "libvirt-iface-%08llx",
                    (unsigned long long)virRandomBits(30)) < 0)
        return -1;

    VIR_DEBUG("Attempting to create interface '%s' with IQN '%s'",
              temp_ifacename, initiatoriqn);

    cmd = virCommandNewArgList(ISCSIADM,
                               "--mode", "iface",
                               "--interface", temp_ifacename,
                               "--op", "new",
                               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 the interface got created
     * properly. */
    if (virCommandRun(cmd, &exitstatus) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to run command '%s' to create new iscsi interface"),
                       ISCSIADM);
        goto cleanup;
    }
    virCommandFree(cmd);

    cmd = virCommandNewArgList(ISCSIADM,
                               "--mode", "iface",
                               "--interface", temp_ifacename,
                               "--op", "update",
                               "--name", "iface.initiatorname",
                               "--value",
                               initiatoriqn,
                               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. */
    if (virCommandRun(cmd, &exitstatus) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to run command '%s' to update iscsi interface with IQN '%s'"),
                       ISCSIADM, initiatoriqn);
        goto cleanup;
    }

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

    ret = 0;

263
 cleanup:
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
    virCommandFree(cmd);
    VIR_FREE(temp_ifacename);
    if (ret != 0)
        VIR_FREE(*ifacename);
    return ret;
}


static int
virISCSIConnection(const char *portal,
                   const char *initiatoriqn,
                   const char *target,
                   const char **extraargv)
{
    int ret = -1;
    const char *const baseargv[] = {
        ISCSIADM,
        "--mode", "node",
        "--portal", portal,
        "--targetname", target,
        NULL
    };
    virCommandPtr cmd;
    char *ifacename = NULL;

    cmd = virCommandNewArgs(baseargv);
    virCommandAddArgSet(cmd, extraargv);

    if (initiatoriqn) {
        switch (virStorageBackendIQNFound(initiatoriqn, &ifacename)) {
        case IQN_FOUND:
            VIR_DEBUG("ifacename: '%s'", ifacename);
            break;
        case IQN_MISSING:
298
            if (virStorageBackendCreateIfaceIQN(initiatoriqn, &ifacename) != 0)
299
                goto cleanup;
300 301 302 303 304 305 306 307 308
            /*
             * iscsiadm doesn't let you send commands to the Interface IQN,
             * unless you've first issued a 'sendtargets' command to the
             * portal. Without the sendtargets all that is received is a
             * "iscsiadm: No records found"
             */
            if (virISCSIScanTargets(portal, initiatoriqn, NULL, NULL) < 0)
                goto cleanup;

309 310 311 312 313 314 315 316 317 318 319 320 321
            break;
        case IQN_ERROR:
        default:
            goto cleanup;
        }
        virCommandAddArgList(cmd, "--interface", ifacename, NULL);
    }

    if (virCommandRun(cmd, NULL) < 0)
        goto cleanup;

    ret = 0;

322
 cleanup:
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
    virCommandFree(cmd);
    VIR_FREE(ifacename);

    return ret;
}


int
virISCSIConnectionLogin(const char *portal,
                        const char *initiatoriqn,
                        const char *target)
{
    const char *extraargv[] = { "--login", NULL };
    return virISCSIConnection(portal, initiatoriqn, target, extraargv);
}


int
virISCSIConnectionLogout(const char *portal,
                         const char *initiatoriqn,
                         const char *target)
{
    const char *extraargv[] = { "--logout", NULL };
    return virISCSIConnection(portal, initiatoriqn, target, extraargv);
}


int
virISCSIRescanLUNs(const char *session)
{
    virCommandPtr cmd = virCommandNewArgList(ISCSIADM,
                                             "--mode", "session",
                                             "-r", session,
                                             "-R",
                                             NULL);
    int ret = virCommandRun(cmd, NULL);
    virCommandFree(cmd);
    return ret;
}


struct virISCSITargetList {
    size_t ntargets;
    char **targets;
};


static int
virISCSIGetTargets(char **const groups,
                   void *data)
{
    struct virISCSITargetList *list = data;
    char *target;

    if (VIR_STRDUP(target, groups[1]) < 0)
        return -1;

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

    return 0;
}


static int
virISCSITargetAutologin(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 virISCSIConnection(portal, initiatoriqn, target, extraargv);
}


int
virISCSIScanTargets(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*$"
    };
    int vars[] = { 2 };
    struct virISCSITargetList list;
    size_t i;
    int ret = -1;
    virCommandPtr cmd = virCommandNewArgList(ISCSIADM,
                                             "--mode", "discovery",
                                             "--type", "sendtargets",
                                             "--portal", portal,
                                             NULL);

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

    if (virCommandRunRegex(cmd,
                           1,
                           regexes,
                           vars,
                           virISCSIGetTargets,
                           &list, NULL) < 0)
        goto cleanup;

    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 (virISCSITargetAutologin(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 {
459
        for (i = 0; i < list.ntargets; i++)
460 461 462 463 464
            VIR_FREE(list.targets[i]);
        VIR_FREE(list.targets);
    }

    ret = 0;
465
 cleanup:
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
    virCommandFree(cmd);
    return ret;
}


int
virISCSINodeUpdate(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);

    /* Ignore non-zero status.  */
    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;
499
 cleanup:
500 501 502
    virCommandFree(cmd);
    return ret;
}