lock_driver_sanlock.c 27.4 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
/*
 * lock_driver_sanlock.c: A lock driver for Sanlock
 *
 * Copyright (C) 2010-2011 Red Hat, Inc.
 *
 * 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
 *
 */

#include <config.h>

#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
31 32
#include <sys/stat.h>
#include <fcntl.h>
33 34 35

#include <sanlock.h>
#include <sanlock_resource.h>
36 37
#include <sanlock_direct.h>
#include <sanlock_admin.h>
38 39 40 41 42 43 44

#include "lock_driver.h"
#include "logging.h"
#include "virterror_internal.h"
#include "memory.h"
#include "util.h"
#include "files.h"
45 46 47 48
#include "md5.h"
#include "conf.h"

#include "configmake.h"
49 50 51 52 53 54 55

#define VIR_FROM_THIS VIR_FROM_LOCKING

#define virLockError(code, ...)                                     \
    virReportErrorHelper(VIR_FROM_THIS, code, __FILE__,             \
                         __FUNCTION__, __LINE__, __VA_ARGS__)

56

57 58
#define VIR_LOCK_MANAGER_SANLOCK_AUTO_DISK_LOCKSPACE "__LIBVIRT__DISKS__"

59 60 61
typedef struct _virLockManagerSanlockDriver virLockManagerSanlockDriver;
typedef virLockManagerSanlockDriver *virLockManagerSanlockDriverPtr;

62 63 64
typedef struct _virLockManagerSanlockPrivate virLockManagerSanlockPrivate;
typedef virLockManagerSanlockPrivate *virLockManagerSanlockPrivatePtr;

65 66
struct _virLockManagerSanlockDriver {
    bool requireLeaseForDisks;
67 68 69
    int hostID;
    bool autoDiskLease;
    char *autoDiskLeasePath;
70 71 72 73
};

static virLockManagerSanlockDriver *driver = NULL;

74 75 76 77 78 79 80 81 82 83 84 85 86 87
struct _virLockManagerSanlockPrivate {
    char vm_name[SANLK_NAME_LEN];
    char vm_uuid[VIR_UUID_BUFLEN];
    unsigned int vm_id;
    unsigned int vm_pid;
    unsigned int flags;
    bool hasRWDisks;
    int res_count;
    struct sanlk_resource *res_args[SANLK_MAX_RESOURCES];
};

/*
 * sanlock plugin for the libvirt virLockManager API
 */
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
static int virLockManagerSanlockLoadConfig(const char *configFile)
{
    virConfPtr conf;
    virConfValuePtr p;

    if (access(configFile, R_OK) == -1) {
        if (errno != ENOENT) {
            virReportSystemError(errno,
                                 _("Unable to access config file %s"),
                                 configFile);
            return -1;
        }
        return 0;
    }

    if (!(conf = virConfReadFile(configFile, 0)))
        return -1;

#define CHECK_TYPE(name,typ) if (p && p->type != (typ)) {               \
        virLockError(VIR_ERR_INTERNAL_ERROR,                            \
                     "%s: %s: expected type " #typ,                     \
                     configFile, (name));                               \
        virConfFree(conf);                                              \
        return -1;                                                      \
    }

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
    p = virConfGetValue(conf, "auto_disk_leases");
    CHECK_TYPE("auto_disk_leases", VIR_CONF_LONG);
    if (p) driver->autoDiskLease = p->l;

    p = virConfGetValue(conf, "disk_lease_dir");
    CHECK_TYPE("disk_lease_dir", VIR_CONF_STRING);
    if (p && p->str) {
        VIR_FREE(driver->autoDiskLeasePath);
        if (!(driver->autoDiskLeasePath = strdup(p->str))) {
            virReportOOMError();
            virConfFree(conf);
            return -1;
        }
    }

    p = virConfGetValue(conf, "host_id");
    CHECK_TYPE("host_id", VIR_CONF_LONG);
    if (p) driver->hostID = p->l;

133 134 135 136
    p = virConfGetValue(conf, "require_lease_for_disks");
    CHECK_TYPE("require_lease_for_disks", VIR_CONF_LONG);
    if (p)
        driver->requireLeaseForDisks = p->l;
137 138
    else
        driver->requireLeaseForDisks = !driver->autoDiskLease;
139 140 141 142 143

    virConfFree(conf);
    return 0;
}

144 145 146 147 148 149 150 151 152 153 154 155 156 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 185 186 187 188 189 190 191 192 193 194 195 196 197 198
static int virLockManagerSanlockSetupLockspace(void)
{
    int fd = -1;
    struct stat st;
    int rv;
    struct sanlk_lockspace ls;
    char *path = NULL;

    if (virAsprintf(&path, "%s/%s",
                    driver->autoDiskLeasePath,
                    VIR_LOCK_MANAGER_SANLOCK_AUTO_DISK_LOCKSPACE) < 0) {
        virReportOOMError();
        goto error;
    }

    memcpy(ls.name, VIR_LOCK_MANAGER_SANLOCK_AUTO_DISK_LOCKSPACE, SANLK_NAME_LEN);
    ls.host_id = 0; /* Doesn't matter for initialization */
    ls.flags = 0;
    if (!virStrcpy(ls.host_id_disk.path, path, SANLK_NAME_LEN)) {
        virLockError(VIR_ERR_INTERNAL_ERROR,
                     _("Lockspace path '%s' exceeded %d characters"),
                     path, SANLK_NAME_LEN);
        goto error;
    }
    ls.host_id_disk.offset = 0;

    /* Stage 1: Ensure the lockspace file exists on disk, has
     * space allocated for it and is initialized with lease
     */
    if (stat(path, &st) < 0) {
        VIR_DEBUG("Lockspace %s does not yet exist", path);
        if ((fd = open(path, O_WRONLY|O_CREAT|O_EXCL, 0600)) < 0) {
            if (errno != EEXIST) {
                virReportSystemError(errno,
                                     _("Unable to create lockspace %s"),
                                     path);
                goto error;
            }
            VIR_DEBUG("Someone else just created lockspace %s", path);
        } else {
            if ((rv = sanlock_direct_align(&ls.host_id_disk)) < 0) {
                if (rv <= -200)
                    virLockError(VIR_ERR_INTERNAL_ERROR,
                                 _("Unable to query sector size %s: error %d"),
                                 path, rv);
                else
                    virReportSystemError(-rv,
                                         _("Unable to query sector size %s"),
                                         path);
                goto error_unlink;
            }

            /*
             * Pre allocate enough data for 1 block of leases at preferred alignment
             */
E
Eric Blake 已提交
199
            if (safezero(fd, 0, rv) < 0) {
200 201 202 203 204 205 206 207 208 209 210 211
                virReportSystemError(errno,
                                     _("Unable to allocate lockspace %s"),
                                     path);
                goto error_unlink;
            }

            if (VIR_CLOSE(fd) < 0) {
                virReportSystemError(errno,
                                     _("Unable to save lockspace %s"),
                                     path);
                goto error_unlink;
            }
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 263
            if ((rv = sanlock_direct_init(&ls, NULL, 0, 0, 0)) < 0) {
                if (rv <= -200)
                    virLockError(VIR_ERR_INTERNAL_ERROR,
                                 _("Unable to initialize lockspace %s: error %d"),
                                 path, rv);
                else
                    virReportSystemError(-rv,
                                         _("Unable to initialize lockspace %s"),
                                         path);
                goto error_unlink;
            }
            VIR_DEBUG("Lockspace %s has been initialized", path);
        }
    }

    ls.host_id = driver->hostID;
    /* Stage 2: Try to register the lockspace with the daemon.
     * If the lockspace is already registered, we should get EEXIST back
     * in which case we can just carry on with life
     */
    if ((rv = sanlock_add_lockspace(&ls, 0)) < 0) {
        if (-rv != EEXIST) {
            if (rv <= -200)
                virLockError(VIR_ERR_INTERNAL_ERROR,
                             _("Unable to add lockspace %s: error %d"),
                             path, rv);
            else
                virReportSystemError(-rv,
                                     _("Unable to add lockspace %s"),
                                     path);
            return -1;
        } else {
            VIR_DEBUG("Lockspace %s is already registered", path);
        }
    } else {
        VIR_DEBUG("Lockspace %s has been registered", path);
    }

    return 0;

error_unlink:
    if (path)
        unlink(path);
error:
    VIR_FORCE_CLOSE(fd);
    VIR_FREE(path);
    return -1;
}


static int virLockManagerSanlockDeinit(void);
264 265
static int virLockManagerSanlockInit(unsigned int version,
                                     const char *configFile,
266 267
                                     unsigned int flags)
{
268 269
    VIR_DEBUG("version=%u configFile=%s flags=%x",
              version, NULLSTR(configFile), flags);
270
    virCheckFlags(0, -1);
271 272 273 274 275 276 277 278 279 280

    if (driver)
        return 0;

    if (VIR_ALLOC(driver) < 0) {
        virReportOOMError();
        return -1;
    }

    driver->requireLeaseForDisks = true;
281 282 283 284 285 286 287
    driver->hostID = 0;
    driver->autoDiskLease = false;
    if (!(driver->autoDiskLeasePath = strdup(LOCALSTATEDIR "/lib/libvirt/sanlock"))) {
        VIR_FREE(driver);
        virReportOOMError();
        goto error;
    }
288 289

    if (virLockManagerSanlockLoadConfig(configFile) < 0)
290 291 292 293 294 295 296 297
        goto error;

    if (driver->autoDiskLease && !driver->hostID) {
        virLockError(VIR_ERR_INTERNAL_ERROR,
                     _("Automatic disk lease mode enabled, but no host ID is set"));
        goto error;
    }

298 299 300 301
    if (driver->autoDiskLease) {
        if (virLockManagerSanlockSetupLockspace() < 0)
            goto error;
    }
302

303
    return 0;
304 305 306 307

error:
    virLockManagerSanlockDeinit();
    return -1;
308 309 310 311
}

static int virLockManagerSanlockDeinit(void)
{
312 313 314
    if (!driver)
        return 0;

315 316 317 318
    VIR_FREE(driver->autoDiskLeasePath);
    VIR_FREE(driver);

    return 0;
319 320
}

321

322 323 324 325 326 327 328 329 330 331 332 333
static int virLockManagerSanlockNew(virLockManagerPtr lock,
                                    unsigned int type,
                                    size_t nparams,
                                    virLockManagerParamPtr params,
                                    unsigned int flags)
{
    virLockManagerParamPtr param;
    virLockManagerSanlockPrivatePtr priv;
    int i;

    virCheckFlags(0, -1);

334 335 336 337 338 339
    if (!driver) {
        virLockError(VIR_ERR_INTERNAL_ERROR,
                     _("Sanlock plugin is not initialized"));
        return -1;
    }

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
    if (type != VIR_LOCK_MANAGER_OBJECT_TYPE_DOMAIN) {
        virLockError(VIR_ERR_INTERNAL_ERROR,
                     _("Unsupported object type %d"), type);
        return -1;
    }

    if (VIR_ALLOC(priv) < 0) {
        virReportOOMError();
        return -1;
    }

    priv->flags = flags;

    for (i = 0; i < nparams; i++) {
        param = &params[i];

        if (STREQ(param->key, "uuid")) {
            memcpy(priv->vm_uuid, param->value.uuid, 16);
        } else if (STREQ(param->key, "name")) {
            if (!virStrcpy(priv->vm_name, param->value.str, SANLK_NAME_LEN)) {
                virLockError(VIR_ERR_INTERNAL_ERROR,
                             _("Domain name '%s' exceeded %d characters"),
                             param->value.str, SANLK_NAME_LEN);
                goto error;
            }
        } else if (STREQ(param->key, "pid")) {
            priv->vm_pid = param->value.ui;
        } else if (STREQ(param->key, "id")) {
            priv->vm_id = param->value.ui;
        }
    }

    lock->privateData = priv;
    return 0;

error:
    VIR_FREE(priv);
    return -1;
}

static void virLockManagerSanlockFree(virLockManagerPtr lock)
{
    virLockManagerSanlockPrivatePtr priv = lock->privateData;
    int i;

    if (!priv)
        return;

    for (i = 0; i < priv->res_count; i++)
        VIR_FREE(priv->res_args[i]);
    VIR_FREE(priv);
    lock->privateData = NULL;
}

394 395 396 397 398 399 400

static const char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7',
                            '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

static int virLockManagerSanlockDiskLeaseName(const char *path,
                                              char *str,
                                              size_t strbuflen)
401
{
402
    unsigned char buf[MD5_DIGEST_SIZE];
403 404
    int i;

405
    if (strbuflen < ((MD5_DIGEST_SIZE * 2) + 1)) {
406
        virLockError(VIR_ERR_INTERNAL_ERROR,
407
                     _("String length too small to store md5 checksum"));
408 409 410
        return -1;
    }

411 412 413
    if (!(md5_buffer(path, strlen(path), buf))) {
        virLockError(VIR_ERR_INTERNAL_ERROR,
                     _("Unable to compute md5 checksum"));
414 415
        return -1;
    }
416 417 418 419

    for (i = 0 ; i < MD5_DIGEST_SIZE ; i++) {
        str[i*2] = hex[(buf[i] >> 4) & 0xf];
        str[(i*2)+1] = hex[buf[i] & 0xf];
420
    }
421 422 423 424 425 426 427 428 429 430 431 432 433
    str[(MD5_DIGEST_SIZE*2)+1] = '\0';
    return 0;
}

static int virLockManagerSanlockAddLease(virLockManagerPtr lock,
                                         const char *name,
                                         size_t nparams,
                                         virLockManagerParamPtr params)
{
    virLockManagerSanlockPrivatePtr priv = lock->privateData;
    int ret = -1;
    struct sanlk_resource *res = NULL;
    int i;
434 435 436

    if (VIR_ALLOC_VAR(res, struct sanlk_disk, 1) < 0) {
        virReportOOMError();
437
        goto cleanup;
438 439 440 441 442 443 444
    }

    res->num_disks = 1;
    if (!virStrcpy(res->name, name, SANLK_NAME_LEN)) {
        virLockError(VIR_ERR_INTERNAL_ERROR,
                     _("Resource name '%s' exceeds %d characters"),
                     name, SANLK_NAME_LEN);
445
        goto cleanup;
446 447 448 449 450 451 452 453
    }

    for (i = 0; i < nparams; i++) {
        if (STREQ(params[i].key, "path")) {
            if (!virStrcpy(res->disks[0].path, params[i].value.str, SANLK_PATH_LEN)) {
                virLockError(VIR_ERR_INTERNAL_ERROR,
                             _("Lease path '%s' exceeds %d characters"),
                             params[i].value.str, SANLK_PATH_LEN);
454
                goto cleanup;
455 456 457 458 459 460 461 462
            }
        } else if (STREQ(params[i].key, "offset")) {
            res->disks[0].offset = params[i].value.ul;
        } else if (STREQ(params[i].key, "lockspace")) {
            if (!virStrcpy(res->lockspace_name, params[i].value.str, SANLK_NAME_LEN)) {
                virLockError(VIR_ERR_INTERNAL_ERROR,
                             _("Resource lockspace '%s' exceeds %d characters"),
                             params[i].value.str, SANLK_NAME_LEN);
463
                goto cleanup;
464 465 466 467 468 469
            }
        }
    }

    priv->res_args[priv->res_count] = res;
    priv->res_count++;
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 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 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572

    ret = 0;

cleanup:
    if (ret == -1)
        VIR_FREE(res);
    return ret;
}




static int virLockManagerSanlockAddDisk(virLockManagerPtr lock,
                                        const char *name,
                                        size_t nparams,
                                        virLockManagerParamPtr params ATTRIBUTE_UNUSED)
{
    virLockManagerSanlockPrivatePtr priv = lock->privateData;
    int ret = -1;
    struct sanlk_resource *res = NULL;
    char *path = NULL;

    if (nparams) {
        virLockError(VIR_ERR_INTERNAL_ERROR,
                     _("Unexpected lock parameters for disk resource"));
        return -1;
    }

    if (VIR_ALLOC_VAR(res, struct sanlk_disk, 1) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    res->num_disks = 1;
    if (virLockManagerSanlockDiskLeaseName(name, res->name, SANLK_NAME_LEN) < 0)
        goto cleanup;

    if (virAsprintf(&path, "%s/%s",
                    driver->autoDiskLeasePath, res->name) < 0) {
        virReportOOMError();
        goto cleanup;
    }
    if (!virStrcpy(res->disks[0].path, path, SANLK_PATH_LEN)) {
        virLockError(VIR_ERR_INTERNAL_ERROR,
                     _("Lease path '%s' exceeds %d characters"),
                     path, SANLK_PATH_LEN);
        goto cleanup;
    }

    if (!virStrcpy(res->lockspace_name,
                   VIR_LOCK_MANAGER_SANLOCK_AUTO_DISK_LOCKSPACE,
                   SANLK_NAME_LEN)) {
        virLockError(VIR_ERR_INTERNAL_ERROR,
                     _("Resource lockspace '%s' exceeds %d characters"),
                     VIR_LOCK_MANAGER_SANLOCK_AUTO_DISK_LOCKSPACE, SANLK_NAME_LEN);
        goto cleanup;
    }

    priv->res_args[priv->res_count] = res;
    priv->res_count++;

    ret = 0;

cleanup:
    if (ret == -1)
        VIR_FREE(res);
    VIR_FREE(path);
    return ret;
}


static int virLockManagerSanlockCreateLease(struct sanlk_resource *res)
{
    int fd = -1;
    struct stat st;
    int rv;

    if (stat(res->disks[0].path, &st) < 0) {
        VIR_DEBUG("Lockspace %s does not yet exist", res->disks[0].path);
        if ((fd = open(res->disks[0].path, O_WRONLY|O_CREAT|O_EXCL, 0600)) < 0) {
            if (errno != EEXIST) {
                virReportSystemError(errno,
                                     _("Unable to create lockspace %s"),
                                     res->disks[0].path);
                return -1;
            }
            VIR_DEBUG("Someone else just created lockspace %s", res->disks[0].path);
        } else {
            if ((rv = sanlock_direct_align(&res->disks[0])) < 0) {
                if (rv <= -200)
                    virLockError(VIR_ERR_INTERNAL_ERROR,
                                 _("Unable to query sector size %s: error %d"),
                                 res->disks[0].path, rv);
                else
                    virReportSystemError(-rv,
                                         _("Unable to query sector size %s"),
                                         res->disks[0].path);
                goto error_unlink;
            }

            /*
             * Pre allocate enough data for 1 block of leases at preferred alignment
             */
E
Eric Blake 已提交
573
            if (safezero(fd, 0, rv) < 0) {
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
                virReportSystemError(errno,
                                     _("Unable to allocate lease %s"),
                                     res->disks[0].path);
                goto error_unlink;
            }

            if (VIR_CLOSE(fd) < 0) {
                virReportSystemError(errno,
                                     _("Unable to save lease %s"),
                                     res->disks[0].path);
                goto error_unlink;
            }

            if ((rv = sanlock_direct_init(NULL, res, 0, 0, 0)) < 0) {
                if (rv <= -200)
                    virLockError(VIR_ERR_INTERNAL_ERROR,
                                 _("Unable to initialize lease %s: error %d"),
                                 res->disks[0].path, rv);
                else
                    virReportSystemError(-rv,
                                         _("Unable to initialize lease %s"),
                                         res->disks[0].path);
                goto error_unlink;
            }
            VIR_DEBUG("Lease %s has been initialized", res->disks[0].path);
        }
    }

602 603
    return 0;

604 605 606
error_unlink:
    unlink(res->disks[0].path);
    VIR_FORCE_CLOSE(fd);
607 608 609
    return -1;
}

610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636

static int virLockManagerSanlockAddResource(virLockManagerPtr lock,
                                            unsigned int type,
                                            const char *name,
                                            size_t nparams,
                                            virLockManagerParamPtr params,
                                            unsigned int flags)
{
    virLockManagerSanlockPrivatePtr priv = lock->privateData;

    virCheckFlags(VIR_LOCK_MANAGER_RESOURCE_READONLY |
                  VIR_LOCK_MANAGER_RESOURCE_SHARED, -1);

    if (priv->res_count == SANLK_MAX_RESOURCES) {
        virLockError(VIR_ERR_INTERNAL_ERROR,
                     _("Too many resources %d for object"),
                     SANLK_MAX_RESOURCES);
        return -1;
    }

    if (flags & VIR_LOCK_MANAGER_RESOURCE_READONLY) {
        virLockError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                     _("Readonly leases are not supported"));
        return -1;
    }
    if (flags & VIR_LOCK_MANAGER_RESOURCE_SHARED) {
        virLockError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
E
Eric Blake 已提交
637
                     _("Shareable leases are not supported"));
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
        return -1;
    }

    switch (type) {
    case VIR_LOCK_MANAGER_RESOURCE_TYPE_DISK:
        if (driver->autoDiskLease) {
            if (virLockManagerSanlockAddDisk(lock, name, nparams, params) < 0)
                return -1;

            if (virLockManagerSanlockCreateLease(priv->res_args[priv->res_count-1]) < 0)
                return -1;
        } else {
            if (!(flags & (VIR_LOCK_MANAGER_RESOURCE_SHARED |
                           VIR_LOCK_MANAGER_RESOURCE_READONLY)))
                priv->hasRWDisks = true;
            /* Ignore disk resources without error */
        }
        break;

    case VIR_LOCK_MANAGER_RESOURCE_TYPE_LEASE:
        if (virLockManagerSanlockAddLease(lock, name, nparams, params) < 0)
            return -1;
        break;

    default:
        /* Ignore other resources, without error */
        break;
    }

    return 0;
}

670 671
static int virLockManagerSanlockAcquire(virLockManagerPtr lock,
                                        const char *state,
672 673
                                        unsigned int flags,
                                        int *fd)
674 675 676 677 678 679 680 681 682 683
{
    virLockManagerSanlockPrivatePtr priv = lock->privateData;
    struct sanlk_options *opt;
    struct sanlk_resource **res_args;
    int res_count;
    bool res_free = false;
    int sock = -1;
    int rv;
    int i;

684 685
    virCheckFlags(VIR_LOCK_MANAGER_ACQUIRE_RESTRICT |
                  VIR_LOCK_MANAGER_ACQUIRE_REGISTER_ONLY, -1);
686 687

    if (priv->res_count == 0 &&
688 689
        priv->hasRWDisks &&
        driver->requireLeaseForDisks) {
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 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 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
        virLockError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                     _("Read/write, exclusive access, disks were present, but no leases specified"));
        return -1;
    }

    if (VIR_ALLOC(opt) < 0) {
        virReportOOMError();
        return -1;
    }

    if (!virStrcpy(opt->owner_name, priv->vm_name, SANLK_NAME_LEN)) {
        virLockError(VIR_ERR_INTERNAL_ERROR,
                     _("Domain name '%s' exceeded %d characters"),
                     priv->vm_name, SANLK_NAME_LEN);
        goto error;
    }

    if (state && STRNEQ(state, "") && 0) {
        if ((rv = sanlock_state_to_args((char *)state,
                                        &res_count,
                                        &res_args)) < 0) {
            if (rv <= -200)
                virLockError(VIR_ERR_INTERNAL_ERROR,
                             _("Unable to parse lock state %s: error %d"),
                             state, rv);
            else
                virReportSystemError(-rv,
                                     _("Unable to parse lock state %s"),
                                     state);
            goto error;
        }
        res_free = true;
    } else {
        res_args = priv->res_args;
        res_count = priv->res_count;
    }

    VIR_DEBUG("Register sanlock %d", flags);
    /* We only initialize 'sock' if we are in the real
     * child process and we need it to be inherited
     *
     * If sock==-1, then sanlock auto-open/closes a
     * temporary sock
     */
    if (priv->vm_pid == getpid() &&
        (sock = sanlock_register()) < 0) {
        if (sock <= -200)
            virLockError(VIR_ERR_INTERNAL_ERROR,
                         _("Failed to open socket to sanlock daemon: error %d"),
                         sock);
        else
            virReportSystemError(-sock, "%s",
                                 _("Failed to open socket to sanlock daemon"));
        goto error;
    }

    if (!(flags & VIR_LOCK_MANAGER_ACQUIRE_REGISTER_ONLY)) {
        VIR_DEBUG("Acquiring object %u", priv->res_count);
        if ((rv = sanlock_acquire(sock, priv->vm_pid, 0,
                                  priv->res_count, priv->res_args,
                                  opt)) < 0) {
            if (rv <= -200)
                virLockError(VIR_ERR_INTERNAL_ERROR,
                             _("Failed to acquire lock: error %d"), rv);
            else
                virReportSystemError(-rv, "%s",
                                     _("Failed to acquire lock"));
            goto error;
        }
    }

    VIR_FREE(opt);

    /*
     * We are *intentionally* "leaking" sock file descriptor
     * because we want it to be inherited by QEMU. When the
     * sock FD finally closes upon QEMU exit (or crash) then
     * sanlock will notice EOF and release the lock
     */
    if (sock != -1 &&
        virSetInherit(sock, true) < 0)
        goto error;

773 774 775 776 777 778 779 780 781 782 783 784
    if (flags & VIR_LOCK_MANAGER_ACQUIRE_RESTRICT) {
        if ((rv = sanlock_restrict(sock, SANLK_RESTRICT_ALL)) < 0) {
            if (rv <= -200)
                virLockError(VIR_ERR_INTERNAL_ERROR,
                             _("Failed to restrict process: error %d"), rv);
            else
                virReportSystemError(-rv, "%s",
                                     _("Failed to restrict process"));
            goto error;
        }
    }

785 786 787 788 789 790 791 792 793
    VIR_DEBUG("Acquire completed fd=%d", sock);

    if (res_free) {
        for (i = 0 ; i < res_count ; i++) {
            VIR_FREE(res_args[i]);
        }
        VIR_FREE(res_args);
    }

794 795 796
    if (fd)
        *fd = sock;

797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
    return 0;

error:
    if (res_free) {
        for (i = 0 ; i < res_count ; i++) {
            VIR_FREE(res_args[i]);
        }
        VIR_FREE(res_args);
    }
    VIR_FREE(opt);
    VIR_FORCE_CLOSE(sock);
    return -1;
}


static int virLockManagerSanlockRelease(virLockManagerPtr lock,
                                        char **state,
                                        unsigned int flags)
{
    virLockManagerSanlockPrivatePtr priv = lock->privateData;
    int res_count;
    int rv;

    virCheckFlags(0, -1);

822 823 824 825 826 827 828 829 830 831
    if (state) {
        if ((rv = sanlock_inquire(-1, priv->vm_pid, 0, &res_count, state)) < 0) {
            if (rv <= -200)
                virLockError(VIR_ERR_INTERNAL_ERROR,
                             _("Failed to inquire lock: error %d"), rv);
            else
                virReportSystemError(-rv, "%s",
                                     _("Failed to inquire lock"));
            return -1;
        }
832

833 834 835
        if (STREQ(*state, ""))
            VIR_FREE(*state);
    }
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858

    if ((rv = sanlock_release(-1, priv->vm_pid, SANLK_REL_ALL, 0, NULL)) < 0) {
        if (rv <= -200)
            virLockError(VIR_ERR_INTERNAL_ERROR,
                         _("Failed to release lock: error %d"), rv);
        else
            virReportSystemError(-rv, "%s",
                                 _("Failed to release lock"));
        return -1;
    }

    return 0;
}

static int virLockManagerSanlockInquire(virLockManagerPtr lock,
                                        char **state,
                                        unsigned int flags)
{
    virLockManagerSanlockPrivatePtr priv = lock->privateData;
    int rv, res_count;

    virCheckFlags(0, -1);

859 860 861 862 863
    if (!state) {
        virLockError(VIR_ERR_INVALID_ARG, "state");
        return -1;
    }

864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
    VIR_DEBUG("pid=%d", priv->vm_pid);

    if ((rv = sanlock_inquire(-1, priv->vm_pid, 0, &res_count, state)) < 0) {
        if (rv <= -200)
            virLockError(VIR_ERR_INTERNAL_ERROR,
                         _("Failed to inquire lock: error %d"), rv);
        else
            virReportSystemError(-rv, "%s",
                                 _("Failed to inquire lock"));
        return -1;
    }

    if (STREQ(*state, ""))
        VIR_FREE(*state);

    return 0;
}

virLockDriver virLockDriverImpl =
{
    .version = VIR_LOCK_MANAGER_VERSION,

    .flags = VIR_LOCK_MANAGER_USES_STATE,

    .drvInit = virLockManagerSanlockInit,
    .drvDeinit = virLockManagerSanlockDeinit,

    .drvNew = virLockManagerSanlockNew,
    .drvFree = virLockManagerSanlockFree,

    .drvAddResource = virLockManagerSanlockAddResource,

    .drvAcquire = virLockManagerSanlockAcquire,
    .drvRelease = virLockManagerSanlockRelease,
    .drvInquire = virLockManagerSanlockInquire,
};