You need to sign in or sign up before continuing.
viriscsi.c 17.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
/*
 * 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");


43 44 45
static int
virISCSIScanTargetsInternal(const char *portal,
                            const char *ifacename,
46
                            bool persist,
47 48 49 50
                            size_t *ntargetsret,
                            char ***targetsret);


51 52 53 54 55 56 57 58 59 60 61 62
struct virISCSISessionData {
    char *session;
    const char *devpath;
};


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

63 64
    if (!data->session &&
        STREQ(groups[1], data->devpath))
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
        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,
    };
91 92
    char *error = NULL;
    int exitstatus = 0;
93

94 95 96
    virCommandPtr cmd = virCommandNewArgList(ISCSIADM, "--mode",
                                             "session", NULL);
    virCommandSetErrorBuffer(cmd, &error);
97 98 99 100 101 102

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

106
    if (cbdata.session == NULL && !probe)
107
        virReportError(VIR_ERR_INTERNAL_ERROR,
108 109
                       _("cannot find iscsiadm session: %s"),
                       NULLSTR(error));
110

111
 cleanup:
112
    VIR_FREE(error);
113 114 115 116 117 118 119 120 121 122 123 124 125 126
    virCommandFree(cmd);
    return cbdata.session;
}



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

static int
virStorageBackendIQNFound(const char *initiatoriqn,
                          char **ifacename)
{
127 128 129 130 131
    int ret = IQN_ERROR;
    char *outbuf = NULL;
    char *line = NULL;
    char *iface = NULL;
    char *iqn = NULL;
132 133 134
    virCommandPtr cmd = virCommandNewArgList(ISCSIADM,
                                             "--mode", "iface", NULL);

135 136
    *ifacename = NULL;

137 138
    virCommandSetOutputBuffer(cmd, &outbuf);
    if (virCommandRun(cmd, NULL) < 0)
139
        goto cleanup;
140

141 142 143 144 145
    /* Example of data we are dealing with:
     * default tcp,<empty>,<empty>,<empty>,<empty>
     * iser iser,<empty>,<empty>,<empty>,<empty>
     * libvirt-iface-253db048 tcp,<empty>,<empty>,<empty>,iqn.2017-03.com.user:client
     */
146

147 148
    line = outbuf;
    while (line && *line) {
149
        char *current = line;
150
        char *newline;
151 152
        char *next;
        size_t i;
153

154 155 156 157 158 159 160
        if (!(newline = strchr(line, '\n')))
            break;

        *newline = '\0';

        VIR_FREE(iface);
        VIR_FREE(iqn);
161

162 163 164 165 166 167
        /* Find the first space, copy everything up to that point into
         * iface and move past it to continue processing */
        if (!(next = strchr(current, ' ')))
            goto error;

        if (VIR_STRNDUP(iface, current, (next - current)) < 0)
168
            goto cleanup;
169 170 171 172 173 174 175 176 177 178

        current = next + 1;

        /* There are five comma separated fields after iface and we only
         * care about the last one, so we need to skip four commas and
         * copy whatever's left into iqn */
        for (i = 0; i < 4; i++) {
            if (!(next = strchr(current, ',')))
                goto error;
            current = next + 1;
179 180
        }

181 182 183
        if (VIR_STRDUP(iqn, current) < 0)
            goto cleanup;

184
        if (STREQ(iqn, initiatoriqn)) {
185
            VIR_STEAL_PTR(*ifacename, iface);
186

187 188 189 190
            VIR_DEBUG("Found interface '%s' with IQN '%s'", *ifacename, iqn);
            break;
        }

191 192
        line = newline + 1;
    }
193 194

    ret = *ifacename ? IQN_FOUND : IQN_MISSING;
195

196
 cleanup:
197
    if (ret == IQN_MISSING)
198 199
        VIR_DEBUG("Could not find interface with IQN '%s'", iqn);

200 201 202
    VIR_FREE(iqn);
    VIR_FREE(iface);
    VIR_FREE(outbuf);
203 204
    virCommandFree(cmd);
    return ret;
205 206 207 208 209 210

 error:
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("malformed output of %s: %s"),
                   ISCSIADM, line);
    goto cleanup;
211 212 213 214 215 216 217 218 219 220 221 222 223
}


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",
224
                    (unsigned long long)virRandomBits(32)) < 0)
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 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
        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;

278
 cleanup:
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
    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:
313
            if (virStorageBackendCreateIfaceIQN(initiatoriqn, &ifacename) != 0)
314
                goto cleanup;
315 316 317 318
            /*
             * 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
319
             * "iscsiadm: No records found". However, we must ensure that
320 321
             * the command is issued over interface name we invented above
             * and that targets are made persistent.
322
             */
323 324
            if (virISCSIScanTargetsInternal(portal, ifacename,
                                            true, NULL, NULL) < 0)
325 326
                goto cleanup;

327 328 329 330 331 332 333 334 335 336 337 338 339
            break;
        case IQN_ERROR:
        default:
            goto cleanup;
        }
        virCommandAddArgList(cmd, "--interface", ifacename, NULL);
    }

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

    ret = 0;

340
 cleanup:
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
    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;
}


407 408 409
static int
virISCSIScanTargetsInternal(const char *portal,
                            const char *ifacename,
410
                            bool persist,
411 412
                            size_t *ntargetsret,
                            char ***targetsret)
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
{
    /**
     *
     * 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);

437 438 439 440 441 442
    if (!persist) {
        virCommandAddArgList(cmd,
                             "--op", "nonpersistent",
                             NULL);
    }

443 444 445 446 447 448
    if (ifacename) {
        virCommandAddArgList(cmd,
                             "--interface", ifacename,
                             NULL);
    }

449 450 451 452 453 454 455
    memset(&list, 0, sizeof(list));

    if (virCommandRunRegex(cmd,
                           1,
                           regexes,
                           vars,
                           virISCSIGetTargets,
456
                           &list, NULL, NULL) < 0)
457 458 459 460 461 462
        goto cleanup;

    if (ntargetsret && targetsret) {
        *ntargetsret = list.ntargets;
        *targetsret = list.targets;
    } else {
463
        for (i = 0; i < list.ntargets; i++)
464 465 466 467 468
            VIR_FREE(list.targets[i]);
        VIR_FREE(list.targets);
    }

    ret = 0;
469
 cleanup:
470 471 472 473
    virCommandFree(cmd);
    return ret;
}

474 475 476 477 478

/**
 * virISCSIScanTargets:
 * @portal: iSCSI portal
 * @initiatoriqn: Initiator IQN
479
 * @persists: whether scanned targets should be saved
480 481 482 483 484 485 486 487
 * @ntargets: number of items in @targetsret array
 * @targets: array of targets
 *
 * For given @portal issue sendtargets command. Optionally,
 * @initiatoriqn can be set to override default configuration.
 * The targets are stored into @targets array and the size of
 * the array is stored into @ntargets.
 *
488 489 490
 * If @persist is true, then targets returned by iSCSI portal are
 * made persistent on the host (their config is saved).
 *
491 492 493 494 495 496
 * Returns: 0 on success,
 *         -1 otherwise (with error reported)
 */
int
virISCSIScanTargets(const char *portal,
                    const char *initiatoriqn,
497
                    bool persist,
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
                    size_t *ntargets,
                    char ***targets)
{
    char *ifacename = NULL;
    int ret = -1;

    if (ntargets)
        *ntargets = 0;
    if (targets)
        *targets = NULL;

    if (initiatoriqn) {
        switch ((virStorageBackendIQNFound(initiatoriqn, &ifacename))) {
        case IQN_FOUND:
            break;

        case IQN_MISSING:
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("no iSCSI interface defined for IQN %s"),
                           initiatoriqn);
            ATTRIBUTE_FALLTHROUGH;
        case IQN_ERROR:
        default:
            return -1;
        }
    }

525 526
    ret = virISCSIScanTargetsInternal(portal, ifacename,
                                      persist, ntargets, targets);
527 528 529 530 531
    VIR_FREE(ifacename);
    return ret;
}


J
John Ferlan 已提交
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
/*
 * virISCSINodeNew:
 * @portal: address for iSCSI target
 * @target: IQN and specific LUN target
 *
 * Usage of nonpersistent discovery in virISCSIScanTargets is useful primarily
 * only when the target IQN is not known; however, since we have the target IQN
 * usage of the "--op new" can be done. This avoids problems if "--op delete"
 * had been used wiping out the static nodes determined by the scanning of
 * all targets.
 *
 * NB: If an iSCSI node record is already created for this portal and
 * target, subsequent "--op new" commands do not return an error.
 *
 * Returns 0 on success, -1 w/ error message on error
 */
int
virISCSINodeNew(const char *portal,
                const char *target)
{
    virCommandPtr cmd = NULL;
    int status;
    int ret = -1;

    cmd = virCommandNewArgList(ISCSIADM,
                               "--mode", "node",
                               "--portal", portal,
                               "--targetname", target,
                               "--op", "new",
                               NULL);

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

    if (status != 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("%s failed new mode for target '%s' with status '%d'"),
                       ISCSIADM, target, status);
        goto cleanup;
    }

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

583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611

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;
612
 cleanup:
613 614 615
    virCommandFree(cmd);
    return ret;
}