vbox_common.c 269.0 KB
Newer Older
T
Taowei 已提交
1
/*
T
Taowei Luo 已提交
2
 * Copyright (C) 2014, Taowei Luo (uaedante@gmail.com)
3
 * Copyright (C) 2010-2016 Red Hat, Inc.
T
Taowei Luo 已提交
4
 * Copyright (C) 2008-2009 Sun Microsystems, Inc.
T
Taowei 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 *
 * 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 <unistd.h>
T
Taowei 已提交
24
#include <fcntl.h>
T
Taowei 已提交
25 26 27

#include "internal.h"
#include "datatypes.h"
28
#include "virdomainobjlist.h"
T
Taowei 已提交
29 30 31
#include "domain_event.h"
#include "virlog.h"
#include "viralloc.h"
32
#include "virhostmem.h"
T
Taowei 已提交
33
#include "virstring.h"
34 35
#include "virfile.h"
#include "virtime.h"
36
#include "virkeycode.h"
37 38
#include "snapshot_conf.h"
#include "vbox_snapshot_conf.h"
39
#include "virfdstream.h"
T
Taowei 已提交
40
#include "configmake.h"
T
Taowei 已提交
41 42 43

#include "vbox_common.h"
#include "vbox_uniformed_api.h"
T
Taowei 已提交
44
#include "vbox_get_driver.h"
T
Taowei 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57 58

/* Common codes for vbox driver. With the definitions in vbox_common.h,
 * it treats vbox structs as a void*. Though vboxUniformedAPI
 * it call vbox functions. This file is a high level implement about
 * the vbox driver.
 */

#define VIR_FROM_THIS VIR_FROM_VBOX

VIR_LOG_INIT("vbox.vbox_common");

/* global vbox API, used for all common codes. */
static vboxUniformedAPI gVBoxAPI;

59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
static virClassPtr vboxDriverClass;
static virMutex vbox_driver_lock = VIR_MUTEX_INITIALIZER;
static vboxDriverPtr vbox_driver;
static vboxDriverPtr vboxDriverObjNew(void);

static virDomainDefParserConfig vboxDomainDefParserConfig = {
    .macPrefix = { 0x08, 0x00, 0x27 },
    .features = VIR_DOMAIN_DEF_FEATURE_NAME_SLASH,
};

static virCapsPtr
vboxCapsInit(void)
{
    virCapsPtr caps;
    virCapsGuestPtr guest;

    if ((caps = virCapabilitiesNew(virArchFromHost(),
                                   false, false)) == NULL)
        goto no_memory;

M
Martin Kletzander 已提交
79
    if (virCapabilitiesInitNUMA(caps) < 0)
80 81
        goto no_memory;

82 83 84
    if (virCapabilitiesInitCaches(caps) < 0)
        goto no_memory;

85 86 87 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 114 115 116 117 118 119 120
    if ((guest = virCapabilitiesAddGuest(caps,
                                         VIR_DOMAIN_OSTYPE_HVM,
                                         caps->host.arch,
                                         NULL,
                                         NULL,
                                         0,
                                         NULL)) == NULL)
        goto no_memory;

    if (virCapabilitiesAddGuestDomain(guest,
                                      VIR_DOMAIN_VIRT_VBOX,
                                      NULL,
                                      NULL,
                                      0,
                                      NULL) == NULL)
        goto no_memory;

    return caps;

 no_memory:
    virObjectUnref(caps);
    return NULL;
}

static void
vboxDriverDispose(void *obj)
{
    vboxDriverPtr driver = obj;

    virObjectUnref(driver->caps);
    virObjectUnref(driver->xmlopt);
}

static int
vboxDriverOnceInit(void)
{
121
    if (!VIR_CLASS_NEW(vboxDriver, virClassForObjectLockable()))
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
        return -1;

    return 0;
}

VIR_ONCE_GLOBAL_INIT(vboxDriver);

static vboxDriverPtr
vboxDriverObjNew(void)
{
    vboxDriverPtr driver;

    if (vboxDriverInitialize() < 0)
        return NULL;

    if (!(driver = virObjectLockableNew(vboxDriverClass)))
        return NULL;

    if (!(driver->caps = vboxCapsInit()) ||
        !(driver->xmlopt = virDomainXMLOptionNew(&vboxDomainDefParserConfig,
142
                                                 NULL, NULL, NULL, NULL)))
143 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 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 263 264 265 266 267 268 269 270 271 272 273
        goto cleanup;

    return driver;

 cleanup:
    virObjectUnref(driver);
    return NULL;
}

static int
vboxExtractVersion(void)
{
    int ret = -1;
    PRUnichar *versionUtf16 = NULL;
    char *vboxVersion = NULL;
    nsresult rc;

    if (vbox_driver->version > 0)
        return 0;

    rc = gVBoxAPI.UIVirtualBox.GetVersion(vbox_driver->vboxObj, &versionUtf16);
    if (NS_FAILED(rc))
        goto failed;

    gVBoxAPI.UPFN.Utf16ToUtf8(vbox_driver->pFuncs, versionUtf16, &vboxVersion);

    if (virParseVersionString(vboxVersion, &vbox_driver->version, false) >= 0)
        ret = 0;

    gVBoxAPI.UPFN.Utf8Free(vbox_driver->pFuncs, vboxVersion);
    gVBoxAPI.UPFN.ComUnallocMem(vbox_driver->pFuncs, versionUtf16);
    vboxVersion = NULL;
    versionUtf16 = NULL;

 failed:
    if (ret != 0)
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not extract VirtualBox version"));

    return ret;
}

static int
vboxSdkInitialize(void)
{
    /* vbox API was already initialized by first connection */
    if (vbox_driver->connectionCount > 0)
        return 0;

    if (gVBoxAPI.UPFN.Initialize(vbox_driver) != 0)
        return -1;

    if (vbox_driver->vboxObj == NULL) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("IVirtualBox object is null"));
        return -1;
    }

    if (vbox_driver->vboxSession == NULL) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("ISession object is null"));
        return -1;
    }

    return 0;
}

static void
vboxSdkUninitialize(void)
{
    /* do not uninitialize, when there are still connection using it */
    if (vbox_driver->connectionCount > 0)
        return;

    gVBoxAPI.UPFN.Uninitialize(vbox_driver);
}

static vboxDriverPtr
vboxGetDriverConnection(void)
{
    virMutexLock(&vbox_driver_lock);

    if (vbox_driver) {
        virObjectRef(vbox_driver);
    } else {
        vbox_driver = vboxDriverObjNew();

        if (!vbox_driver) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Failed to create vbox driver object."));
            return NULL;
        }
    }

    if (vboxSdkInitialize() < 0 || vboxExtractVersion() < 0) {
        gVBoxAPI.UPFN.Uninitialize(vbox_driver);
        /* make sure to clear the pointer when last reference was released */
        if (!virObjectUnref(vbox_driver))
            vbox_driver = NULL;

        virMutexUnlock(&vbox_driver_lock);

        return NULL;
    }

    vbox_driver->connectionCount++;

    virMutexUnlock(&vbox_driver_lock);

    return vbox_driver;
}

static void
vboxDestroyDriverConnection(void)
{
    virMutexLock(&vbox_driver_lock);

    if (!vbox_driver)
        goto cleanup;

    vbox_driver->connectionCount--;

    vboxSdkUninitialize();

    if (!virObjectUnref(vbox_driver))
        vbox_driver = NULL;

 cleanup:
    virMutexUnlock(&vbox_driver_lock);
}

274
static int openSessionForMachine(vboxDriverPtr data, const unsigned char *dom_uuid,
275
                                 vboxIID *iid, IMachine **machine)
T
Taowei 已提交
276 277 278
{
    VBOX_IID_INITIALIZE(iid);
    vboxIIDFromUUID(iid, dom_uuid);
279 280 281 282 283 284

    /* Get machine for the call to VBOX_SESSION_OPEN_EXISTING */
    if (NS_FAILED(gVBoxAPI.UIVirtualBox.GetMachine(data->vboxObj, iid, machine))) {
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
        return -1;
T
Taowei 已提交
285
    }
286

T
Taowei 已提交
287 288 289
    return 0;
}

T
Taowei 已提交
290

T
Taowei 已提交
291 292 293 294 295 296 297 298 299
/**
 * function to generate the name for medium,
 * for e.g: hda, sda, etc
 *
 * @returns     null terminated string with device name or NULL
 *              for failures
 * @param       storageBus      Input storage bus type
 * @param       devicePort      Input port number
 * @param       deviceSlot      Input slot number
300
 * @param       sdCount         Running total of disk devices with "sd" prefix
T
Taowei 已提交
301
 */
302 303 304 305 306
static char *
vboxGenerateMediumName(PRUint32 storageBus,
                       PRInt32 devicePort,
                       PRInt32 deviceSlot,
                       size_t sdCount)
T
Taowei 已提交
307 308
{
    const char *prefix = NULL;
309 310
    char *name = NULL;
    int total = 0;
T
Taowei 已提交
311

D
Dawid Zamirski 已提交
312 313
    switch ((enum StorageBus) storageBus) {
    case StorageBus_IDE:
T
Taowei 已提交
314
        prefix = "hd";
315
        total = devicePort * 2 + deviceSlot;
D
Dawid Zamirski 已提交
316 317 318 319 320

        break;
    case StorageBus_SATA:
    case StorageBus_SCSI:
    case StorageBus_SAS:
T
Taowei 已提交
321
        prefix = "sd";
322
        total = sdCount;
D
Dawid Zamirski 已提交
323 324 325

        break;
    case StorageBus_Floppy:
326
        total = deviceSlot;
T
Taowei 已提交
327
        prefix = "fd";
D
Dawid Zamirski 已提交
328 329 330 331 332

        break;
    case StorageBus_Null:

        return NULL;
T
Taowei 已提交
333 334 335 336 337 338 339
    }

    name = virIndexToDiskName(total, prefix);

    return name;
}

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

static int
vboxSetStorageController(virDomainControllerDefPtr controller,
                         vboxDriverPtr data,
                         IMachine *machine)
{
    PRUnichar *controllerName = NULL;
    PRInt32 vboxModel = StorageControllerType_Null;
    PRInt32 vboxBusType = StorageBus_Null;
    IStorageController *vboxController = NULL;
    nsresult rc = 0;
    char *debugName = NULL;
    int ret = -1;

    /* libvirt controller type => vbox bus type */
    switch ((virDomainControllerType) controller->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_FDC:
        VBOX_UTF8_TO_UTF16(VBOX_CONTROLLER_FLOPPY_NAME, &controllerName);
        vboxBusType = StorageBus_Floppy;

        break;
    case VIR_DOMAIN_CONTROLLER_TYPE_IDE:
        VBOX_UTF8_TO_UTF16(VBOX_CONTROLLER_IDE_NAME, &controllerName);
        vboxBusType = StorageBus_IDE;

        break;
    case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
        VBOX_UTF8_TO_UTF16(VBOX_CONTROLLER_SCSI_NAME, &controllerName);
        vboxBusType = StorageBus_SCSI;

        break;
    case VIR_DOMAIN_CONTROLLER_TYPE_SATA:
        VBOX_UTF8_TO_UTF16(VBOX_CONTROLLER_SATA_NAME, &controllerName);
        vboxBusType = StorageBus_SATA;

        break;
    case VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL:
    case VIR_DOMAIN_CONTROLLER_TYPE_CCID:
    case VIR_DOMAIN_CONTROLLER_TYPE_USB:
    case VIR_DOMAIN_CONTROLLER_TYPE_PCI:
380
    case VIR_DOMAIN_CONTROLLER_TYPE_XENBUS:
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
    case VIR_DOMAIN_CONTROLLER_TYPE_LAST:
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("The vbox driver does not support %s controller type"),
                       virDomainControllerTypeToString(controller->type));
        return -1;
    }

    /* libvirt scsi model => vbox scsi model */
    if (controller->type == VIR_DOMAIN_CONTROLLER_TYPE_SCSI) {
        switch ((virDomainControllerModelSCSI) controller->model) {
        case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC:
        case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_AUTO:
            vboxModel = StorageControllerType_LsiLogic;

            break;
        case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_BUSLOGIC:
            vboxModel = StorageControllerType_BusLogic;

D
Dawid Zamirski 已提交
399 400 401 402 403 404 405
            break;
        case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSISAS1068:
            /* in vbox, lsisas has a dedicated SAS bus type with no model */
            VBOX_UTF16_FREE(controllerName);
            VBOX_UTF8_TO_UTF16(VBOX_CONTROLLER_SAS_NAME, &controllerName);
            vboxBusType = StorageBus_SAS;

406 407 408 409
            break;
        case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VMPVSCSI:
        case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_IBMVSCSI:
        case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_SCSI:
410 411
        case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_TRANSITIONAL:
        case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_NON_TRANSITIONAL:
412 413 414 415 416 417
        case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSISAS1078:
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("The vbox driver does not support %s SCSI "
                             "controller model"),
                           virDomainControllerModelSCSITypeToString(controller->model));
            goto cleanup;
418 419 420 421 422 423
        case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_DEFAULT:
        case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LAST:
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unexpected SCSI controller model %d"),
                           controller->model);
            goto cleanup;
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
        }
    /* libvirt ide model => vbox ide model */
    } else if (controller->type == VIR_DOMAIN_CONTROLLER_TYPE_IDE) {
        switch ((virDomainControllerModelIDE) controller->model) {
        case VIR_DOMAIN_CONTROLLER_MODEL_IDE_PIIX3:
            vboxModel = StorageControllerType_PIIX3;

            break;
        case VIR_DOMAIN_CONTROLLER_MODEL_IDE_PIIX4:
            vboxModel = StorageControllerType_PIIX4;

            break;
        case VIR_DOMAIN_CONTROLLER_MODEL_IDE_ICH6:
            vboxModel = StorageControllerType_ICH6;

            break;
        case VIR_DOMAIN_CONTROLLER_MODEL_IDE_LAST:
441
        case VIR_DOMAIN_CONTROLLER_MODEL_IDE_DEFAULT:
442
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
443 444
                           _("Unexpected IDE controller model %d"),
                           controller->model);
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 499 500 501
            goto cleanup;
        }
    }

    VBOX_UTF16_TO_UTF8(controllerName, &debugName);
    VIR_DEBUG("Adding VBOX storage controller (name: %s, busType: %d)",
               debugName, vboxBusType);

    rc = gVBoxAPI.UIMachine.AddStorageController(machine, controllerName,
                                                 vboxBusType, &vboxController);

    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to add storage controller "
                         "(name: %s, busType: %d), rc=%08x"),
                       debugName, vboxBusType, rc);
        goto cleanup;
    }

    /* only IDE or SCSI controller have model choices */
    if (vboxModel != StorageControllerType_Null) {
        rc = gVBoxAPI.UIStorageController.SetControllerType(vboxController,
                                                            vboxModel);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                            _("Failed to change storage controller model, "
                              "rc=%08x"), rc);
            goto cleanup;
        }
    }

    ret = 0;

 cleanup:
    VBOX_UTF16_FREE(controllerName);
    VBOX_UTF8_FREE(debugName);
    VBOX_RELEASE(vboxController);

    return ret;
}


static int
vboxAttachStorageControllers(virDomainDefPtr def,
                             vboxDriverPtr data,
                             IMachine *machine)
{
    size_t i;
    for (i = 0; i < def->ncontrollers; i++) {
        if (vboxSetStorageController(def->controllers[i], data, machine) < 0)
            return -1;
    }

    return 0;
}


502 503 504 505 506 507 508
static int
vboxConnectURIProbe(char **uri)
{
    return VIR_STRDUP(*uri, geteuid() ? "vbox:///session" : "vbox:///system");
}


T
Taowei 已提交
509 510 511
static virDrvOpenStatus
vboxConnectOpen(virConnectPtr conn,
                virConnectAuthPtr auth ATTRIBUTE_UNUSED,
512
                virConfPtr conf ATTRIBUTE_UNUSED,
T
Taowei 已提交
513
                unsigned int flags)
T
Taowei 已提交
514
{
515
    vboxDriverPtr driver = NULL;
T
Taowei 已提交
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
    uid_t uid = geteuid();

    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

    if (uid != 0) {
        if (STRNEQ(conn->uri->path, "/session")) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown driver path '%s' specified (try vbox:///session)"), conn->uri->path);
            return VIR_DRV_OPEN_ERROR;
        }
    } else { /* root */
        if (STRNEQ(conn->uri->path, "/system") &&
            STRNEQ(conn->uri->path, "/session")) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown driver path '%s' specified (try vbox:///system)"), conn->uri->path);
            return VIR_DRV_OPEN_ERROR;
        }
    }

535
    if (!(driver = vboxGetDriverConnection()))
T
Taowei 已提交
536 537
        return VIR_DRV_OPEN_ERROR;

538
    conn->privateData = virObjectRef(driver);
T
Taowei 已提交
539 540 541 542 543

    VIR_DEBUG("in vboxOpen");

    return VIR_DRV_OPEN_SUCCESS;
}
T
Taowei 已提交
544

T
Taowei 已提交
545
static int vboxConnectClose(virConnectPtr conn)
T
Taowei 已提交
546 547 548
{
    VIR_DEBUG("%s: in vboxClose", conn->driver->name);

549 550
    virObjectUnref(conn->privateData);
    vboxDestroyDriverConnection();
T
Taowei 已提交
551 552 553

    return 0;
}
T
Taowei 已提交
554

T
Taowei 已提交
555
static int
T
Taowei 已提交
556 557
vboxDomainSave(virDomainPtr dom, const char *path ATTRIBUTE_UNUSED)
{
558
    vboxDriverPtr data = dom->conn->privateData;
559
    IConsole *console = NULL;
560
    vboxIID iid;
T
Taowei 已提交
561 562 563 564
    IMachine *machine = NULL;
    IProgress *progress = NULL;
    resultCodeUnion resultCode;
    nsresult rc;
T
Taowei Luo 已提交
565 566 567 568
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
569 570 571 572 573 574 575 576 577

    /* VirtualBox currently doesn't support saving to a file
     * at a location other then the machine folder and thus
     * setting path to ATTRIBUTE_UNUSED for now, will change
     * this behaviour once get the VirtualBox API in right
     * shape to do this
     */

    /* Open a Session for the machine */
578
    if (openSessionForMachine(data, dom->uuid, &iid, &machine) < 0)
T
Taowei 已提交
579 580 581 582 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
        goto cleanup;

    rc = gVBoxAPI.UISession.OpenExisting(data, &iid, machine);
    if (NS_FAILED(rc))
        goto cleanup;

    rc = gVBoxAPI.UISession.GetConsole(data->vboxSession, &console);
    if (NS_FAILED(rc) || !console)
        goto freeSession;

    rc = gVBoxAPI.UIConsole.SaveState(console, &progress);
    if (!progress)
        goto freeSession;

    gVBoxAPI.UIProgress.WaitForCompletion(progress, -1);
    gVBoxAPI.UIProgress.GetResultCode(progress, &resultCode);
    if (RC_SUCCEEDED(resultCode))
        ret = 0;

 freeSession:
    gVBoxAPI.UISession.Close(data->vboxSession);

 cleanup:
    DEBUGIID("UUID of machine being saved:", &iid);
    VBOX_RELEASE(machine);
    VBOX_RELEASE(console);
    VBOX_RELEASE(progress);
    vboxIIDUnalloc(&iid);
    return ret;
}
T
Taowei 已提交
609

T
Taowei 已提交
610
static int vboxConnectGetVersion(virConnectPtr conn, unsigned long *version)
T
Taowei 已提交
611
{
612
    vboxDriverPtr data = conn->privateData;
T
Taowei 已提交
613 614
    VIR_DEBUG("%s: in vboxGetVersion", conn->driver->name);

615
    virObjectLock(data);
T
Taowei 已提交
616
    *version = data->version;
617
    virObjectUnlock(data);
T
Taowei 已提交
618 619 620

    return 0;
}
T
Taowei 已提交
621

T
Taowei 已提交
622
static char *vboxConnectGetHostname(virConnectPtr conn ATTRIBUTE_UNUSED)
T
Taowei 已提交
623 624 625
{
    return virGetHostname();
}
T
Taowei 已提交
626

T
Taowei 已提交
627
static int vboxConnectIsSecure(virConnectPtr conn ATTRIBUTE_UNUSED)
T
Taowei 已提交
628 629 630 631
{
    /* Driver is using local, non-network based transport */
    return 1;
}
T
Taowei 已提交
632

T
Taowei 已提交
633
static int vboxConnectIsEncrypted(virConnectPtr conn ATTRIBUTE_UNUSED)
T
Taowei 已提交
634 635 636 637
{
    /* No encryption is needed, or used on the local transport*/
    return 0;
}
T
Taowei 已提交
638

T
Taowei 已提交
639
static int vboxConnectIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
T
Taowei 已提交
640 641 642
{
    return 1;
}
T
Taowei 已提交
643

T
Taowei 已提交
644
static int
T
Taowei 已提交
645 646
vboxConnectGetMaxVcpus(virConnectPtr conn, const char *type ATTRIBUTE_UNUSED)
{
647
    vboxDriverPtr data = conn->privateData;
T
Taowei 已提交
648
    PRUint32 maxCPUCount = 0;
T
Taowei Luo 已提交
649 650 651 652
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670

    /* VirtualBox Supports only hvm and thus the type passed to it
     * has no meaning, setting it to ATTRIBUTE_UNUSED
     */
    ISystemProperties *systemProperties = NULL;

    gVBoxAPI.UIVirtualBox.GetSystemProperties(data->vboxObj, &systemProperties);
    if (!systemProperties)
        goto cleanup;
    gVBoxAPI.UISystemProperties.GetMaxGuestCPUCount(systemProperties, &maxCPUCount);

    if (maxCPUCount > 0)
        ret = maxCPUCount;

 cleanup:
    VBOX_RELEASE(systemProperties);
    return ret;
}
671

T
Taowei 已提交
672
static char *vboxConnectGetCapabilities(virConnectPtr conn)
673
{
674
    vboxDriverPtr data = conn->privateData;
T
Taowei Luo 已提交
675 676 677 678
    char *ret = NULL;

    if (!data->vboxObj)
        return ret;
679

680
    virObjectLock(data);
681
    ret = virCapabilitiesFormatXML(data->caps);
682
    virObjectUnlock(data);
683 684 685

    return ret;
}
T
Taowei 已提交
686

T
Taowei 已提交
687
static int vboxConnectListDomains(virConnectPtr conn, int *ids, int nids)
T
Taowei 已提交
688
{
689
    vboxDriverPtr data = conn->privateData;
T
Taowei 已提交
690 691 692 693
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
    PRUint32 state;
    nsresult rc;
    size_t i, j;
T
Taowei Luo 已提交
694 695 696 697
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
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

    rc = gVBoxAPI.UArray.vboxArrayGet(&machines, data->vboxObj, ARRAY_GET_MACHINES);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of Domains, rc=%08x"),
                       (unsigned)rc);
        goto cleanup;
    }

    ret = 0;
    for (i = 0, j = 0; (i < machines.count) && (j < nids); ++i) {
        IMachine *machine = machines.items[i];

        if (machine) {
            PRBool isAccessible = PR_FALSE;
            gVBoxAPI.UIMachine.GetAccessible(machine, &isAccessible);
            if (isAccessible) {
                gVBoxAPI.UIMachine.GetState(machine, &state);
                if (gVBoxAPI.machineStateChecker.Online(state)) {
                    ret++;
                    ids[j++] = i + 1;
                }
            }
        }
    }

 cleanup:
    gVBoxAPI.UArray.vboxArrayRelease(&machines);
    return ret;
}
T
Taowei 已提交
728

T
Taowei 已提交
729
static int vboxConnectNumOfDomains(virConnectPtr conn)
T
Taowei 已提交
730
{
731
    vboxDriverPtr data = conn->privateData;
T
Taowei 已提交
732 733 734 735
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
    PRUint32 state;
    nsresult rc;
    size_t i;
T
Taowei Luo 已提交
736 737 738 739
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
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

    rc = gVBoxAPI.UArray.vboxArrayGet(&machines, data->vboxObj, ARRAY_GET_MACHINES);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get number of Domains, rc=%08x"), (unsigned)rc);
        goto cleanup;
    }

    ret = 0;
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];

        if (machine) {
            PRBool isAccessible = PR_FALSE;
            gVBoxAPI.UIMachine.GetAccessible(machine, &isAccessible);
            if (isAccessible) {
                gVBoxAPI.UIMachine.GetState(machine, &state);
                if (gVBoxAPI.machineStateChecker.Online(state))
                    ret++;
            }
        }
    }

 cleanup:
    gVBoxAPI.UArray.vboxArrayRelease(&machines);
    return ret;
}
T
Taowei 已提交
767

T
Taowei 已提交
768
static virDomainPtr vboxDomainLookupByID(virConnectPtr conn, int id)
T
Taowei 已提交
769
{
770
    vboxDriverPtr data = conn->privateData;
T
Taowei 已提交
771 772 773 774
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
    IMachine *machine;
    PRBool isAccessible = PR_FALSE;
    PRUnichar *machineNameUtf16 = NULL;
775
    char *machineNameUtf8 = NULL;
776
    vboxIID iid;
T
Taowei 已提交
777 778 779
    unsigned char uuid[VIR_UUID_BUFLEN];
    PRUint32 state;
    nsresult rc;
T
Taowei Luo 已提交
780 781 782 783
    virDomainPtr ret = NULL;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
784 785 786 787 788 789 790 791 792 793 794 795 796 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 822 823 824 825 826 827 828 829 830 831

    VBOX_IID_INITIALIZE(&iid);
    /* Internal vbox IDs start from 0, the public libvirt ID
     * starts from 1, so refuse id == 0, and adjust the rest*/
    if (id == 0) {
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching id %d"), id);
        return NULL;
    }
    id = id - 1;

    rc = gVBoxAPI.UArray.vboxArrayGet(&machines, data->vboxObj, ARRAY_GET_MACHINES);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of machines, rc=%08x"), (unsigned)rc);
        return NULL;
    }

    if (id >= machines.count)
        goto cleanup;

    machine = machines.items[id];

    if (!machine)
        goto cleanup;

    isAccessible = PR_FALSE;
    gVBoxAPI.UIMachine.GetAccessible(machine, &isAccessible);
    if (!isAccessible)
        goto cleanup;

    gVBoxAPI.UIMachine.GetState(machine, &state);
    if (!gVBoxAPI.machineStateChecker.Online(state))
        goto cleanup;

    gVBoxAPI.UIMachine.GetName(machine, &machineNameUtf16);
    VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);

    gVBoxAPI.UIMachine.GetId(machine, &iid);
    vboxIIDToUUID(&iid, uuid);
    vboxIIDUnalloc(&iid);

    /* get a new domain pointer from virGetDomain, if it fails
     * then no need to assign the id, else assign the id, cause
     * it is -1 by default. rest is taken care by virGetDomain
     * itself, so need not worry.
     */

832
    ret = virGetDomain(conn, machineNameUtf8, uuid, id + 1);
T
Taowei 已提交
833 834 835 836 837 838 839 840 841

    /* Cleanup all the XPCOM allocated stuff here */
    VBOX_UTF8_FREE(machineNameUtf8);
    VBOX_UTF16_FREE(machineNameUtf16);

 cleanup:
    gVBoxAPI.UArray.vboxArrayRelease(&machines);
    return ret;
}
T
Taowei 已提交
842 843 844 845

virDomainPtr vboxDomainLookupByUUID(virConnectPtr conn,
                                    const unsigned char *uuid)
{
846
    vboxDriverPtr data = conn->privateData;
T
Taowei 已提交
847
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
848
    vboxIID iid;
849
    char *machineNameUtf8 = NULL;
T
Taowei 已提交
850 851 852 853 854
    PRUnichar *machineNameUtf16 = NULL;
    unsigned char iid_as_uuid[VIR_UUID_BUFLEN];
    size_t i;
    bool matched = false;
    nsresult rc;
T
Taowei Luo 已提交
855 856 857 858
    virDomainPtr ret = NULL;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886

    VBOX_IID_INITIALIZE(&iid);
    rc = gVBoxAPI.UArray.vboxArrayGet(&machines, data->vboxObj, ARRAY_GET_MACHINES);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of machines, rc=%08x"), (unsigned)rc);
        return NULL;
    }

    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
        PRBool isAccessible = PR_FALSE;

        if (!machine)
            continue;

        gVBoxAPI.UIMachine.GetAccessible(machine, &isAccessible);
        if (!isAccessible)
            continue;

        rc = gVBoxAPI.UIMachine.GetId(machine, &iid);
        if (NS_FAILED(rc))
            continue;
        vboxIIDToUUID(&iid, iid_as_uuid);
        vboxIIDUnalloc(&iid);

        if (memcmp(uuid, iid_as_uuid, VIR_UUID_BUFLEN) == 0) {
            PRUint32 state;
887 888
            int id = -1;

T
Taowei 已提交
889 890 891 892 893 894 895 896

            matched = true;

            gVBoxAPI.UIMachine.GetName(machine, &machineNameUtf16);
            VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);

            gVBoxAPI.UIMachine.GetState(machine, &state);

897 898
            if (gVBoxAPI.machineStateChecker.Online(state))
                id = i + 1;
T
Taowei 已提交
899

900
            ret = virGetDomain(conn, machineNameUtf8, iid_as_uuid, id);
T
Taowei 已提交
901 902 903 904 905 906 907 908 909 910 911 912 913
         }

         if (matched)
             break;
    }

    /* Do the cleanup and take care you dont leak any memory */
    VBOX_UTF8_FREE(machineNameUtf8);
    VBOX_COM_UNALLOC_MEM(machineNameUtf16);
    gVBoxAPI.UArray.vboxArrayRelease(&machines);

    return ret;
}
T
Taowei 已提交
914

T
Taowei 已提交
915
static virDomainPtr
T
Taowei 已提交
916 917
vboxDomainLookupByName(virConnectPtr conn, const char *name)
{
918
    vboxDriverPtr data = conn->privateData;
T
Taowei 已提交
919
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
920
    vboxIID iid;
921
    char *machineNameUtf8 = NULL;
T
Taowei 已提交
922 923 924 925 926
    PRUnichar *machineNameUtf16 = NULL;
    unsigned char uuid[VIR_UUID_BUFLEN];
    size_t i;
    bool matched = false;
    nsresult rc;
T
Taowei Luo 已提交
927 928 929 930
    virDomainPtr ret = NULL;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955

    VBOX_IID_INITIALIZE(&iid);
    rc = gVBoxAPI.UArray.vboxArrayGet(&machines, data->vboxObj, ARRAY_GET_MACHINES);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of machines, rc=%08x"), (unsigned)rc);
        return NULL;
    }

    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
        PRBool isAccessible = PR_FALSE;

        if (!machine)
            continue;

        gVBoxAPI.UIMachine.GetAccessible(machine, &isAccessible);
        if (!isAccessible)
            continue;

        gVBoxAPI.UIMachine.GetName(machine, &machineNameUtf16);
        VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);

        if (STREQ(name, machineNameUtf8)) {
            PRUint32 state;
956
            int id = -1;
T
Taowei 已提交
957 958 959 960 961 962 963 964 965

            matched = true;

            gVBoxAPI.UIMachine.GetId(machine, &iid);
            vboxIIDToUUID(&iid, uuid);
            vboxIIDUnalloc(&iid);

            gVBoxAPI.UIMachine.GetState(machine, &state);

966 967
            if (gVBoxAPI.machineStateChecker.Online(state))
                id = i + 1;
T
Taowei 已提交
968

969
            ret = virGetDomain(conn, machineNameUtf8, uuid, id);
T
Taowei 已提交
970 971 972 973 974 975 976 977 978 979 980 981 982
        }

        VBOX_UTF8_FREE(machineNameUtf8);
        VBOX_COM_UNALLOC_MEM(machineNameUtf16);
        if (matched)
            break;
    }

    gVBoxAPI.UArray.vboxArrayRelease(&machines);

    return ret;
}

T
Taowei 已提交
983
static void
984
vboxSetBootDeviceOrder(virDomainDefPtr def, vboxDriverPtr data,
T
Taowei 已提交
985 986 987
                       IMachine *machine)
{
    ISystemProperties *systemProperties = NULL;
988
    PRUint32 maxBootPosition = 0;
T
Taowei 已提交
989 990
    size_t i = 0;

991
    VIR_DEBUG("def->os.type             %s", virDomainOSTypeToString(def->os.type));
T
Taowei 已提交
992 993 994 995 996 997 998 999 1000 1001 1002 1003
    VIR_DEBUG("def->os.arch             %s", virArchToString(def->os.arch));
    VIR_DEBUG("def->os.machine          %s", def->os.machine);
    VIR_DEBUG("def->os.nBootDevs        %zu", def->os.nBootDevs);
    VIR_DEBUG("def->os.bootDevs[0]      %d", def->os.bootDevs[0]);
    VIR_DEBUG("def->os.bootDevs[1]      %d", def->os.bootDevs[1]);
    VIR_DEBUG("def->os.bootDevs[2]      %d", def->os.bootDevs[2]);
    VIR_DEBUG("def->os.bootDevs[3]      %d", def->os.bootDevs[3]);
    VIR_DEBUG("def->os.init             %s", def->os.init);
    VIR_DEBUG("def->os.kernel           %s", def->os.kernel);
    VIR_DEBUG("def->os.initrd           %s", def->os.initrd);
    VIR_DEBUG("def->os.cmdline          %s", def->os.cmdline);
    VIR_DEBUG("def->os.root             %s", def->os.root);
1004 1005 1006 1007 1008 1009
    if (def->os.loader) {
        VIR_DEBUG("def->os.loader->path     %s", def->os.loader->path);
        VIR_DEBUG("def->os.loader->readonly %d", def->os.loader->readonly);
        VIR_DEBUG("def->os.loader->type     %d", def->os.loader->type);
        VIR_DEBUG("def->os.loader->nvram    %s", def->os.loader->nvram);
    }
T
Taowei 已提交
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
    VIR_DEBUG("def->os.bootloader       %s", def->os.bootloader);
    VIR_DEBUG("def->os.bootloaderArgs   %s", def->os.bootloaderArgs);

    gVBoxAPI.UIVirtualBox.GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        gVBoxAPI.UISystemProperties.GetMaxBootPosition(systemProperties,
                                                       &maxBootPosition);
        VBOX_RELEASE(systemProperties);
    }

    /* Clear the defaults first */
1021
    for (i = 0; i < maxBootPosition; i++)
T
Taowei 已提交
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
        gVBoxAPI.UIMachine.SetBootOrder(machine, i+1, DeviceType_Null);

    for (i = 0; (i < def->os.nBootDevs) && (i < maxBootPosition); i++) {
        PRUint32 device = DeviceType_Null;

        if (def->os.bootDevs[i] == VIR_DOMAIN_BOOT_FLOPPY) {
            device = DeviceType_Floppy;
        } else if (def->os.bootDevs[i] == VIR_DOMAIN_BOOT_CDROM) {
            device = DeviceType_DVD;
        } else if (def->os.bootDevs[i] == VIR_DOMAIN_BOOT_DISK) {
            device = DeviceType_HardDisk;
        } else if (def->os.bootDevs[i] == VIR_DOMAIN_BOOT_NET) {
            device = DeviceType_Network;
        }
        gVBoxAPI.UIMachine.SetBootOrder(machine, i+1, device);
    }
}

1040
static int
1041
vboxAttachDrives(virDomainDefPtr def, vboxDriverPtr data, IMachine *machine)
T
Taowei 已提交
1042 1043
{
    size_t i;
1044
    int type, ret = 0;
1045
    const char *src = NULL;
1046
    nsresult rc = 0;
1047
    virDomainDiskDefPtr disk = NULL;
1048
    virDomainControllerDefPtr cont;
T
Taowei 已提交
1049
    PRUnichar *storageCtlName = NULL;
1050
    char *controllerName = NULL;
1051
    IMedium *medium = NULL;
D
Dawid Zamirski 已提交
1052
    PRUnichar *mediumFileUtf16 = NULL;
1053 1054 1055 1056
    PRUint32 devicePort, deviceSlot, deviceType, accessMode;
    vboxIID mediumUUID;

    VBOX_IID_INITIALIZE(&mediumUUID);
T
Taowei 已提交
1057

1058
    for (i = 0; i < def->ndisks; i++) {
1059 1060 1061 1062 1063 1064 1065
        disk = def->disks[i];
        src = virDomainDiskGetSource(disk);
        type = virDomainDiskGetType(disk);
        deviceType = DeviceType_Null;
        accessMode = AccessMode_ReadOnly;
        devicePort = disk->info.addr.drive.unit;
        deviceSlot = disk->info.addr.drive.bus;
T
Taowei 已提交
1066

1067 1068 1069 1070 1071 1072 1073 1074 1075
        if (type != VIR_STORAGE_TYPE_FILE) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Unsupported storage type %s, the only supported "
                             "type is %s"),
                           virStorageTypeToString(type),
                           virStorageTypeToString(VIR_STORAGE_TYPE_FILE));
            ret = -1;
            goto cleanup;
        }
T
Taowei 已提交
1076

1077 1078 1079 1080 1081
        switch ((virDomainDiskDevice) disk->device) {
        case VIR_DOMAIN_DISK_DEVICE_DISK:
            if (!src) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("Missing disk source file path"));
1082
                ret = -1;
1083
                goto cleanup;
T
Taowei 已提交
1084 1085
            }

1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
            deviceType = DeviceType_HardDisk;
            accessMode = AccessMode_ReadWrite;

            break;

        case VIR_DOMAIN_DISK_DEVICE_CDROM:
            deviceType = DeviceType_DVD;
            accessMode = AccessMode_ReadOnly;

            break;
        case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
            deviceType = DeviceType_Floppy;
            accessMode = AccessMode_ReadWrite;

            break;
        case VIR_DOMAIN_DISK_DEVICE_LUN:
        case VIR_DOMAIN_DISK_DEVICE_LAST:
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("The vbox driver does not support %s disk device"),
                           virDomainDiskDeviceTypeToString(disk->device));
            ret = -1;
            goto cleanup;
        }

        switch ((virDomainDiskBus) disk->bus) {
        case VIR_DOMAIN_DISK_BUS_IDE:
1112
            VBOX_UTF8_TO_UTF16(VBOX_CONTROLLER_IDE_NAME, &storageCtlName);
1113 1114 1115 1116 1117
            devicePort = def->disks[i]->info.addr.drive.bus;
            deviceSlot = def->disks[i]->info.addr.drive.unit;

            break;
        case VIR_DOMAIN_DISK_BUS_SATA:
1118
            VBOX_UTF8_TO_UTF16(VBOX_CONTROLLER_SATA_NAME, &storageCtlName);
1119 1120 1121

            break;
        case VIR_DOMAIN_DISK_BUS_SCSI:
1122
            VBOX_UTF8_TO_UTF16(VBOX_CONTROLLER_SCSI_NAME, &storageCtlName);
1123

1124 1125
            cont = virDomainDeviceFindSCSIController(def, &disk->info);
            if (cont && cont->model == VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSISAS1068) {
D
Dawid Zamirski 已提交
1126 1127 1128 1129
                VBOX_UTF16_FREE(storageCtlName);
                VBOX_UTF8_TO_UTF16(VBOX_CONTROLLER_SAS_NAME, &storageCtlName);
            }

1130 1131
            break;
        case VIR_DOMAIN_DISK_BUS_FDC:
1132
            VBOX_UTF8_TO_UTF16(VBOX_CONTROLLER_FLOPPY_NAME, &storageCtlName);
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
            devicePort = 0;
            deviceSlot = disk->info.addr.drive.unit;

            break;
        case VIR_DOMAIN_DISK_BUS_VIRTIO:
        case VIR_DOMAIN_DISK_BUS_XEN:
        case VIR_DOMAIN_DISK_BUS_USB:
        case VIR_DOMAIN_DISK_BUS_UML:
        case VIR_DOMAIN_DISK_BUS_SD:
        case VIR_DOMAIN_DISK_BUS_LAST:
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("The vbox driver does not support %s bus type"),
                           virDomainDiskBusTypeToString(disk->bus));
            ret = -1;
            goto cleanup;
        }

        /* If disk source is specified, lookup IMedium - removable drives don't
         * have either.
         */
        if (src) {
            VBOX_UTF8_TO_UTF16(src, &mediumFileUtf16);
            VIR_DEBUG("Looking up medium %s, type: %d, mode: %d", src,
                      deviceType, accessMode);

            rc = gVBoxAPI.UIVirtualBox.FindHardDisk(data->vboxObj, mediumFileUtf16,
                                                    deviceType, accessMode, &medium);
T
Taowei 已提交
1160

1161 1162 1163 1164 1165
            /* The following is not needed for vbox 4.2+ but older versions have
             * distinct find and open operations where the former looks in vbox
             * media registry while the latter at storage location. In 4.2+, the
             * OpenMedium call takes care of both cases internally
             */
T
Taowei 已提交
1166 1167 1168 1169 1170 1171 1172 1173 1174
            if (!medium) {
                rc = gVBoxAPI.UIVirtualBox.OpenMedium(data->vboxObj,
                                                      mediumFileUtf16,
                                                      deviceType, accessMode,
                                                      &medium);
            }

            if (!medium) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
1175
                               _("Failed to open the following disk/dvd/floppy "
1176
                                 "to the machine: %s, rc=%08x"), src, rc);
1177
                ret = -1;
1178
                goto cleanup;
T
Taowei 已提交
1179 1180 1181 1182 1183
            }

            rc = gVBoxAPI.UIMedium.GetId(medium, &mediumUUID);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
1184
                               _("Can't get the UUID of the file to be attached "
T
Taowei 已提交
1185
                                 "as harddisk/dvd/floppy: %s, rc=%08x"),
1186
                               src, rc);
1187
                ret = -1;
1188
                goto cleanup;
T
Taowei 已提交
1189
            }
1190
        }
T
Taowei 已提交
1191

1192 1193 1194 1195 1196 1197 1198
        if (disk->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
            if (disk->src->readonly) {
                gVBoxAPI.UIMedium.SetType(medium, MediumType_Immutable);
                VIR_DEBUG("Setting hard disk to immutable");
            } else if (!disk->src->readonly) {
                gVBoxAPI.UIMedium.SetType(medium, MediumType_Normal);
                VIR_DEBUG("Setting hard disk type to normal");
T
Taowei 已提交
1199
            }
1200
        }
T
Taowei 已提交
1201

1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
        VBOX_UTF16_TO_UTF8(storageCtlName, &controllerName);
        VIR_DEBUG("Attaching disk(%zu), controller: %s, port: %d, slot: %d, "
                  "type: %d, medium: %s", i, controllerName, devicePort,
                    deviceSlot, deviceType, medium == NULL ? "empty" : src);
        VBOX_UTF8_FREE(controllerName);

        /* Attach the harddisk/dvd/Floppy to the storage controller,
         * medium == NULL is ok here
         */
        rc = gVBoxAPI.UIMachine.AttachDevice(machine,
                                             storageCtlName,
                                             devicePort,
                                             deviceSlot,
                                             deviceType,
                                             medium);

        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not attach the file as "
                             "harddisk/dvd/floppy: %s, rc=%08x"), src, rc);
            ret = -1;
            goto cleanup;
        } else {
            DEBUGIID("Attached HDD/DVD/Floppy with UUID", &mediumUUID);
        }
T
Taowei 已提交
1227

1228
 cleanup:
1229 1230 1231 1232
        VBOX_MEDIUM_RELEASE(medium);
        vboxIIDUnalloc(&mediumUUID);
        VBOX_UTF16_FREE(mediumFileUtf16);
        VBOX_UTF16_FREE(storageCtlName);
1233

1234 1235
        if (ret < 0)
            break;
T
Taowei 已提交
1236
    }
1237 1238

    return ret;
T
Taowei 已提交
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
}

static void
vboxAttachSound(virDomainDefPtr def, IMachine *machine)
{
    nsresult rc;
    IAudioAdapter *audioAdapter = NULL;

    /* Check if def->nsounds is one as VirtualBox currently supports
     * only one sound card
     */
    if (def->nsounds != 1)
        return;

    gVBoxAPI.UIMachine.GetAudioAdapter(machine, &audioAdapter);
    if (!audioAdapter)
        return;

    rc = gVBoxAPI.UIAudioAdapter.SetEnabled(audioAdapter, 1);
    if (NS_FAILED(rc))
        goto cleanup;

    if (def->sounds[0]->model == VIR_DOMAIN_SOUND_MODEL_SB16) {
        gVBoxAPI.UIAudioAdapter.SetAudioController(audioAdapter,
                                                   AudioControllerType_SB16);
1264
    } else if (def->sounds[0]->model == VIR_DOMAIN_SOUND_MODEL_AC97) {
T
Taowei 已提交
1265 1266 1267 1268 1269 1270 1271 1272
        gVBoxAPI.UIAudioAdapter.SetAudioController(audioAdapter,
                                                   AudioControllerType_AC97);
    }

 cleanup:
    VBOX_RELEASE(audioAdapter);
}

1273
static int
1274
vboxAttachNetwork(virDomainDefPtr def, vboxDriverPtr data, IMachine *machine)
T
Taowei 已提交
1275 1276
{
    ISystemProperties *systemProperties = NULL;
1277 1278
    PRUint32 chipsetType = ChipsetType_Null;
    PRUint32 networkAdapterCount = 0;
T
Taowei 已提交
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
    size_t i = 0;

    if (gVBoxAPI.chipsetType)
        gVBoxAPI.UIMachine.GetChipsetType(machine, &chipsetType);

    gVBoxAPI.UIVirtualBox.GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        gVBoxAPI.UISystemProperties.GetMaxNetworkAdapters(systemProperties, chipsetType,
                                                          &networkAdapterCount);
        VBOX_RELEASE(systemProperties);
    }

    VIR_DEBUG("Number of Network Cards to be connected: %zu", def->nnets);
    VIR_DEBUG("Number of Network Cards available: %d", networkAdapterCount);

    for (i = 0; (i < def->nnets) && (i < networkAdapterCount); i++) {
        INetworkAdapter *adapter = NULL;
1296
        PRUint32 adapterType = NetworkAdapterType_Null;
T
Taowei 已提交
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
        char macaddr[VIR_MAC_STRING_BUFLEN] = {0};
        char macaddrvbox[VIR_MAC_STRING_BUFLEN - 5] = {0};
        PRUnichar *MACAddress = NULL;

        virMacAddrFormat(&def->nets[i]->mac, macaddr);
        snprintf(macaddrvbox, VIR_MAC_STRING_BUFLEN - 5,
                 "%02X%02X%02X%02X%02X%02X",
                 def->nets[i]->mac.addr[0],
                 def->nets[i]->mac.addr[1],
                 def->nets[i]->mac.addr[2],
                 def->nets[i]->mac.addr[3],
                 def->nets[i]->mac.addr[4],
                 def->nets[i]->mac.addr[5]);
        macaddrvbox[VIR_MAC_STRING_BUFLEN - 6] = '\0';

        VIR_DEBUG("NIC(%zu): Type:   %d", i, def->nets[i]->type);
C
Cole Robinson 已提交
1313
        VIR_DEBUG("NIC(%zu): Model:  %s", i, virDomainNetModelTypeToString(def->nets[i]->model));
T
Taowei 已提交
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
        VIR_DEBUG("NIC(%zu): Mac:    %s", i, macaddr);
        VIR_DEBUG("NIC(%zu): ifname: %s", i, def->nets[i]->ifname);
        if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
            VIR_DEBUG("NIC(%zu): name:    %s", i, def->nets[i]->data.network.name);
        } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_INTERNAL) {
            VIR_DEBUG("NIC(%zu): name:   %s", i, def->nets[i]->data.internal.name);
        } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_USER) {
            VIR_DEBUG("NIC(%zu): NAT.", i);
        } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
            VIR_DEBUG("NIC(%zu): brname: %s", i, def->nets[i]->data.bridge.brname);
            VIR_DEBUG("NIC(%zu): script: %s", i, def->nets[i]->script);
1325 1326
            if (def->nets[i]->guestIP.nips == 1) {
                char *ipStr = virSocketAddrFormat(&def->nets[i]->guestIP.ips[0]->address);
1327 1328
                VIR_DEBUG("NIC(%zu): ipaddr: %s", i, ipStr);
                VIR_FREE(ipStr);
1329
            } else if (def->nets[i]->guestIP.nips > 1) {
1330 1331 1332
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("Driver does not support setting multiple IP addresses"));
                return -1;
1333
            }
T
Taowei 已提交
1334 1335 1336 1337 1338 1339 1340 1341
        }

        gVBoxAPI.UIMachine.GetNetworkAdapter(machine, i, &adapter);
        if (!adapter)
            continue;

        gVBoxAPI.UINetworkAdapter.SetEnabled(adapter, 1);

C
Cole Robinson 已提交
1342 1343
        if (def->nets[i]->model) {
            if (def->nets[i]->model == VIR_DOMAIN_NET_MODEL_AM79C970A) {
T
Taowei 已提交
1344
                adapterType = NetworkAdapterType_Am79C970A;
C
Cole Robinson 已提交
1345
            } else if (def->nets[i]->model == VIR_DOMAIN_NET_MODEL_AM79C973) {
T
Taowei 已提交
1346
                adapterType = NetworkAdapterType_Am79C973;
C
Cole Robinson 已提交
1347
            } else if (def->nets[i]->model == VIR_DOMAIN_NET_MODEL_82540EM) {
T
Taowei 已提交
1348
                adapterType = NetworkAdapterType_I82540EM;
C
Cole Robinson 已提交
1349
            } else if (def->nets[i]->model == VIR_DOMAIN_NET_MODEL_82545EM) {
T
Taowei 已提交
1350
                adapterType = NetworkAdapterType_I82545EM;
C
Cole Robinson 已提交
1351
            } else if (def->nets[i]->model == VIR_DOMAIN_NET_MODEL_82543GC) {
T
Taowei 已提交
1352 1353
                adapterType = NetworkAdapterType_I82543GC;
            } else if (gVBoxAPI.APIVersion >= 3000051 &&
C
Cole Robinson 已提交
1354
                       def->nets[i]->model == VIR_DOMAIN_NET_MODEL_VIRTIO) {
T
Taowei 已提交
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
                /* Only vbox 3.1 and later support NetworkAdapterType_Virto */
                adapterType = NetworkAdapterType_Virtio;
            }
        } else {
            adapterType = NetworkAdapterType_Am79C973;
        }

        gVBoxAPI.UINetworkAdapter.SetAdapterType(adapter, adapterType);

        if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
            PRUnichar *hostInterface = NULL;
            /* Bridged Network */

            gVBoxAPI.UINetworkAdapter.AttachToBridgedInterface(adapter);

            if (def->nets[i]->data.bridge.brname) {
                VBOX_UTF8_TO_UTF16(def->nets[i]->data.bridge.brname,
                                   &hostInterface);
                gVBoxAPI.UINetworkAdapter.SetBridgedInterface(adapter, hostInterface);
                VBOX_UTF16_FREE(hostInterface);
            }
        } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_INTERNAL) {
            PRUnichar *internalNetwork = NULL;
            /* Internal Network */

            gVBoxAPI.UINetworkAdapter.AttachToInternalNetwork(adapter);

            if (def->nets[i]->data.internal.name) {
                VBOX_UTF8_TO_UTF16(def->nets[i]->data.internal.name,
                                   &internalNetwork);
                gVBoxAPI.UINetworkAdapter.SetInternalNetwork(adapter, internalNetwork);
                VBOX_UTF16_FREE(internalNetwork);
            }
        } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
            PRUnichar *hostInterface = NULL;
            /* Host Only Networking (currently only vboxnet0 available
             * on *nix and mac, on windows you can create and configure
             * as many as you want)
             */
            gVBoxAPI.UINetworkAdapter.AttachToHostOnlyInterface(adapter);

            if (def->nets[i]->data.network.name) {
                VBOX_UTF8_TO_UTF16(def->nets[i]->data.network.name,
                                   &hostInterface);
                gVBoxAPI.UINetworkAdapter.SetHostOnlyInterface(adapter, hostInterface);
                VBOX_UTF16_FREE(hostInterface);
            }
        } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_USER) {
            /* NAT */
            gVBoxAPI.UINetworkAdapter.AttachToNAT(adapter);
        } else {
            /* else always default to NAT if we don't understand
             * what option is been passed to us
             */
            gVBoxAPI.UINetworkAdapter.AttachToNAT(adapter);
        }

        VBOX_UTF8_TO_UTF16(macaddrvbox, &MACAddress);
        gVBoxAPI.UINetworkAdapter.SetMACAddress(adapter, MACAddress);
        VBOX_UTF16_FREE(MACAddress);
    }
1416
    return 0;
T
Taowei 已提交
1417 1418 1419
}

static void
1420
vboxAttachSerial(virDomainDefPtr def, vboxDriverPtr data, IMachine *machine)
T
Taowei 已提交
1421 1422
{
    ISystemProperties *systemProperties = NULL;
1423
    PRUint32 serialPortCount = 0;
T
Taowei 已提交
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
    size_t i = 0;

    gVBoxAPI.UIVirtualBox.GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        gVBoxAPI.UISystemProperties.GetSerialPortCount(systemProperties,
                                                       &serialPortCount);
        VBOX_RELEASE(systemProperties);
    }

    VIR_DEBUG("Number of Serial Ports to be connected: %zu", def->nserials);
    VIR_DEBUG("Number of Serial Ports available: %d", serialPortCount);

    for (i = 0; (i < def->nserials) && (i < serialPortCount); i++) {
        ISerialPort *serialPort = NULL;
        PRUnichar *pathUtf16 = NULL;

1440
        VIR_DEBUG("SerialPort(%zu): Type: %d", i, def->serials[i]->source->type);
T
Taowei 已提交
1441 1442 1443 1444 1445 1446 1447 1448 1449
        VIR_DEBUG("SerialPort(%zu): target.port: %d", i,
              def->serials[i]->target.port);

        gVBoxAPI.UIMachine.GetSerialPort(machine, i, &serialPort);
        if (!serialPort)
            continue;

        gVBoxAPI.UISerialPort.SetEnabled(serialPort, 1);

1450 1451
        if (def->serials[i]->source->data.file.path) {
            VBOX_UTF8_TO_UTF16(def->serials[i]->source->data.file.path,
T
Taowei 已提交
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
                               &pathUtf16);
            gVBoxAPI.UISerialPort.SetPath(serialPort, pathUtf16);
        }

        /* For now hard code the serial ports to COM1 and COM2,
         * COM1 (Base Addr: 0x3F8 (decimal: 1016), IRQ: 4)
         * COM2 (Base Addr: 0x2F8 (decimal:  760), IRQ: 3)
         * TODO: make this more flexible
         */
        /* TODO: to improve the libvirt XMl handling so
         * that def->serials[i]->target.port shows real port
         * and not always start at 0
         */
        if (def->serials[i]->target.port == 0) {
            gVBoxAPI.UISerialPort.SetIRQ(serialPort, 4);
            gVBoxAPI.UISerialPort.SetIOBase(serialPort, 1016);
            VIR_DEBUG(" serialPort-%zu irq: %d, iobase 0x%x, path: %s",
1469
                  i, 4, 1016, def->serials[i]->source->data.file.path);
T
Taowei 已提交
1470 1471 1472 1473
        } else if (def->serials[i]->target.port == 1) {
            gVBoxAPI.UISerialPort.SetIRQ(serialPort, 3);
            gVBoxAPI.UISerialPort.SetIOBase(serialPort, 760);
            VIR_DEBUG(" serialPort-%zu irq: %d, iobase 0x%x, path: %s",
1474
                  i, 3, 760, def->serials[i]->source->data.file.path);
T
Taowei 已提交
1475 1476
        }

1477
        if (def->serials[i]->source->type == VIR_DOMAIN_CHR_TYPE_DEV) {
T
Taowei 已提交
1478
            gVBoxAPI.UISerialPort.SetHostMode(serialPort, PortMode_HostDevice);
1479
        } else if (def->serials[i]->source->type == VIR_DOMAIN_CHR_TYPE_PIPE) {
T
Taowei 已提交
1480 1481
            gVBoxAPI.UISerialPort.SetHostMode(serialPort, PortMode_HostPipe);
        } else if (gVBoxAPI.APIVersion >= 2002051 &&
1482
                   def->serials[i]->source->type == VIR_DOMAIN_CHR_TYPE_FILE) {
T
Taowei 已提交
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
            /* PortMode RawFile is used for vbox 3.0 or later */
            gVBoxAPI.UISerialPort.SetHostMode(serialPort, PortMode_RawFile);
        } else {
            gVBoxAPI.UISerialPort.SetHostMode(serialPort,
                                              PortMode_Disconnected);
        }

        VBOX_RELEASE(serialPort);
        VBOX_UTF16_FREE(pathUtf16);
    }
}

static void
1496
vboxAttachParallel(virDomainDefPtr def, vboxDriverPtr data, IMachine *machine)
T
Taowei 已提交
1497 1498
{
    ISystemProperties *systemProperties = NULL;
1499
    PRUint32 parallelPortCount = 0;
T
Taowei 已提交
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
    size_t i = 0;

    gVBoxAPI.UIVirtualBox.GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        gVBoxAPI.UISystemProperties.GetParallelPortCount(systemProperties,
                                                         &parallelPortCount);
        VBOX_RELEASE(systemProperties);
    }

    VIR_DEBUG("Number of Parallel Ports to be connected: %zu", def->nparallels);
    VIR_DEBUG("Number of Parallel Ports available: %d", parallelPortCount);
    for (i = 0; (i < def->nparallels) && (i < parallelPortCount); i++) {
        IParallelPort *parallelPort = NULL;
        PRUnichar *pathUtf16 = NULL;

1515
        VIR_DEBUG("ParallelPort(%zu): Type: %d", i, def->parallels[i]->source->type);
T
Taowei 已提交
1516 1517 1518 1519 1520 1521 1522
        VIR_DEBUG("ParallelPort(%zu): target.port: %d", i,
              def->parallels[i]->target.port);

        gVBoxAPI.UIMachine.GetParallelPort(machine, i, &parallelPort);
        if (!parallelPort)
            continue;

1523
        VBOX_UTF8_TO_UTF16(def->parallels[i]->source->data.file.path, &pathUtf16);
T
Taowei 已提交
1524 1525 1526 1527 1528 1529

        /* For now hard code the parallel ports to
         * LPT1 (Base Addr: 0x378 (decimal: 888), IRQ: 7)
         * LPT2 (Base Addr: 0x278 (decimal: 632), IRQ: 5)
         * TODO: make this more flexible
         */
1530 1531 1532 1533
        if ((def->parallels[i]->source->type == VIR_DOMAIN_CHR_TYPE_DEV) ||
            (def->parallels[i]->source->type == VIR_DOMAIN_CHR_TYPE_PTY) ||
            (def->parallels[i]->source->type == VIR_DOMAIN_CHR_TYPE_FILE) ||
            (def->parallels[i]->source->type == VIR_DOMAIN_CHR_TYPE_PIPE)) {
T
Taowei 已提交
1534 1535 1536 1537 1538
            gVBoxAPI.UIParallelPort.SetPath(parallelPort, pathUtf16);
            if (i == 0) {
                gVBoxAPI.UIParallelPort.SetIRQ(parallelPort, 7);
                gVBoxAPI.UIParallelPort.SetIOBase(parallelPort, 888);
                VIR_DEBUG(" parallePort-%zu irq: %d, iobase 0x%x, path: %s",
1539
                      i, 7, 888, def->parallels[i]->source->data.file.path);
T
Taowei 已提交
1540 1541 1542 1543
            } else if (i == 1) {
                gVBoxAPI.UIParallelPort.SetIRQ(parallelPort, 5);
                gVBoxAPI.UIParallelPort.SetIOBase(parallelPort, 632);
                VIR_DEBUG(" parallePort-%zu irq: %d, iobase 0x%x, path: %s",
1544
                      i, 5, 632, def->parallels[i]->source->data.file.path);
T
Taowei 已提交
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
            }
        }

        /* like serial port, parallel port can't be enabled unless
         * correct IRQ and IOBase values are specified.
         */
        gVBoxAPI.UIParallelPort.SetEnabled(parallelPort, 1);

        VBOX_RELEASE(parallelPort);
        VBOX_UTF16_FREE(pathUtf16);
    }
}

static void
vboxAttachVideo(virDomainDefPtr def, IMachine *machine)
{
    if ((def->nvideos == 1) &&
        (def->videos[0]->type == VIR_DOMAIN_VIDEO_TYPE_VBOX)) {
        gVBoxAPI.UIMachine.SetVRAMSize(machine,
                                       VIR_DIV_UP(def->videos[0]->vram, 1024));
        gVBoxAPI.UIMachine.SetMonitorCount(machine, def->videos[0]->heads);
        if (def->videos[0]->accel) {
1567 1568 1569 1570
            if (def->videos[0]->accel->accel3d) {
                gVBoxAPI.UIMachine.SetAccelerate3DEnabled(machine,
                    def->videos[0]->accel->accel3d == VIR_TRISTATE_BOOL_YES);
            }
1571
            if (def->videos[0]->accel->accel2d) {
T
Taowei 已提交
1572
                gVBoxAPI.UIMachine.SetAccelerate2DVideoEnabled(machine,
1573 1574
                    def->videos[0]->accel->accel2d == VIR_TRISTATE_BOOL_YES);
            }
T
Taowei 已提交
1575 1576
        } else {
            gVBoxAPI.UIMachine.SetAccelerate3DEnabled(machine, 0);
1577
            gVBoxAPI.UIMachine.SetAccelerate2DVideoEnabled(machine, 0);
T
Taowei 已提交
1578 1579 1580 1581 1582
        }
    }
}

static void
1583
vboxAttachDisplay(virDomainDefPtr def, vboxDriverPtr data, IMachine *machine)
T
Taowei 已提交
1584
{
1585 1586 1587
    int vrdpPresent = 0;
    int sdlPresent = 0;
    int guiPresent = 0;
T
Taowei 已提交
1588 1589 1590
    char *guiDisplay = NULL;
    char *sdlDisplay = NULL;
    size_t i = 0;
1591
    virDomainGraphicsListenDefPtr glisten;
T
Taowei 已提交
1592 1593

    for (i = 0; i < def->ngraphics; i++) {
1594
        IVRDEServer *VRDEServer = NULL;
T
Taowei 已提交
1595 1596 1597 1598 1599

        if ((def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_RDP) &&
            (vrdpPresent == 0)) {

            vrdpPresent = 1;
1600 1601 1602
            gVBoxAPI.UIMachine.GetVRDEServer(machine, &VRDEServer);
            if (VRDEServer) {
                gVBoxAPI.UIVRDEServer.SetEnabled(VRDEServer, PR_TRUE);
T
Taowei 已提交
1603 1604
                VIR_DEBUG("VRDP Support turned ON.");

1605
                gVBoxAPI.UIVRDEServer.SetPorts(data, VRDEServer, def->graphics[i]);
T
Taowei 已提交
1606 1607

                if (def->graphics[i]->data.rdp.replaceUser) {
1608
                    gVBoxAPI.UIVRDEServer.SetReuseSingleConnection(VRDEServer,
T
Taowei 已提交
1609 1610 1611 1612 1613
                                                                   PR_TRUE);
                    VIR_DEBUG("VRDP set to reuse single connection");
                }

                if (def->graphics[i]->data.rdp.multiUser) {
1614
                    gVBoxAPI.UIVRDEServer.SetAllowMultiConnection(VRDEServer,
T
Taowei 已提交
1615 1616 1617 1618
                                                                  PR_TRUE);
                    VIR_DEBUG("VRDP set to allow multiple connection");
                }

1619 1620
                if ((glisten = virDomainGraphicsGetListen(def->graphics[i], 0)) &&
                    glisten->address) {
T
Taowei 已提交
1621 1622
                    PRUnichar *netAddressUtf16 = NULL;

1623
                    VBOX_UTF8_TO_UTF16(glisten->address, &netAddressUtf16);
1624
                    gVBoxAPI.UIVRDEServer.SetNetAddress(data, VRDEServer,
T
Taowei 已提交
1625 1626
                                                        netAddressUtf16);
                    VIR_DEBUG("VRDP listen address is set to: %s",
1627
                              glisten->address);
T
Taowei 已提交
1628 1629 1630 1631

                    VBOX_UTF16_FREE(netAddressUtf16);
                }

1632
                VBOX_RELEASE(VRDEServer);
T
Taowei 已提交
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
            }
        }

        if ((def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_DESKTOP) &&
            (guiPresent == 0)) {
            guiPresent = 1;
            if (VIR_STRDUP(guiDisplay, def->graphics[i]->data.desktop.display) < 0) {
                /* just don't go to cleanup yet as it is ok to have
                 * guiDisplay as NULL and we check it below if it
                 * exist and then only use it there
                 */
            }
        }

        if ((def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_SDL) &&
            (sdlPresent == 0)) {
            sdlPresent = 1;
            if (VIR_STRDUP(sdlDisplay, def->graphics[i]->data.sdl.display) < 0) {
                /* just don't go to cleanup yet as it is ok to have
                 * sdlDisplay as NULL and we check it below if it
                 * exist and then only use it there
                 */
            }
        }
    }

    if ((vrdpPresent == 1) && (guiPresent == 0) && (sdlPresent == 0)) {
        /* store extradata key that frontend is set to vrdp */
1661
        PRUnichar *keyTypeUtf16 = NULL;
T
Taowei 已提交
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
        PRUnichar *valueTypeUtf16 = NULL;

        VBOX_UTF8_TO_UTF16("FRONTEND/Type", &keyTypeUtf16);
        VBOX_UTF8_TO_UTF16("vrdp", &valueTypeUtf16);

        gVBoxAPI.UIMachine.SetExtraData(machine, keyTypeUtf16, valueTypeUtf16);

        VBOX_UTF16_FREE(keyTypeUtf16);
        VBOX_UTF16_FREE(valueTypeUtf16);

    } else if ((guiPresent == 0) && (sdlPresent == 1)) {
        /* store extradata key that frontend is set to sdl */
1674 1675 1676
        PRUnichar *keyTypeUtf16 = NULL;
        PRUnichar *valueTypeUtf16 = NULL;
        PRUnichar *keyDislpayUtf16 = NULL;
T
Taowei 已提交
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
        PRUnichar *valueDisplayUtf16 = NULL;

        VBOX_UTF8_TO_UTF16("FRONTEND/Type", &keyTypeUtf16);
        VBOX_UTF8_TO_UTF16("sdl", &valueTypeUtf16);

        gVBoxAPI.UIMachine.SetExtraData(machine, keyTypeUtf16, valueTypeUtf16);

        VBOX_UTF16_FREE(keyTypeUtf16);
        VBOX_UTF16_FREE(valueTypeUtf16);

        if (sdlDisplay) {
            VBOX_UTF8_TO_UTF16("FRONTEND/Display", &keyDislpayUtf16);
            VBOX_UTF8_TO_UTF16(sdlDisplay, &valueDisplayUtf16);

            gVBoxAPI.UIMachine.SetExtraData(machine, keyDislpayUtf16,
                                            valueDisplayUtf16);

            VBOX_UTF16_FREE(keyDislpayUtf16);
            VBOX_UTF16_FREE(valueDisplayUtf16);
        }

    } else {
        /* if all are set then default is gui, with vrdp turned on */
1700 1701 1702
        PRUnichar *keyTypeUtf16 = NULL;
        PRUnichar *valueTypeUtf16 = NULL;
        PRUnichar *keyDislpayUtf16 = NULL;
T
Taowei 已提交
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
        PRUnichar *valueDisplayUtf16 = NULL;

        VBOX_UTF8_TO_UTF16("FRONTEND/Type", &keyTypeUtf16);
        VBOX_UTF8_TO_UTF16("gui", &valueTypeUtf16);

        gVBoxAPI.UIMachine.SetExtraData(machine, keyTypeUtf16, valueTypeUtf16);

        VBOX_UTF16_FREE(keyTypeUtf16);
        VBOX_UTF16_FREE(valueTypeUtf16);

        if (guiDisplay) {
            VBOX_UTF8_TO_UTF16("FRONTEND/Display", &keyDislpayUtf16);
            VBOX_UTF8_TO_UTF16(guiDisplay, &valueDisplayUtf16);

            gVBoxAPI.UIMachine.SetExtraData(machine, keyDislpayUtf16,
                                            valueDisplayUtf16);

            VBOX_UTF16_FREE(keyDislpayUtf16);
            VBOX_UTF16_FREE(valueDisplayUtf16);
        }
    }

    VIR_FREE(guiDisplay);
    VIR_FREE(sdlDisplay);
}

static void
1730
vboxAttachUSB(virDomainDefPtr def, vboxDriverPtr data, IMachine *machine)
T
Taowei 已提交
1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
{
    IUSBCommon *USBCommon = NULL;
    size_t i = 0;
    bool isUSB = false;
    nsresult rc;

    if (def->nhostdevs == 0)
        return;

    /* Loop through the devices first and see if you
     * have a USB Device, only if you have one then
     * start the USB controller else just proceed as
     * usual
     */
    for (i = 0; i < def->nhostdevs; i++) {
        if (def->hostdevs[i]->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS)
            continue;

        if (def->hostdevs[i]->source.subsys.type !=
            VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB)
            continue;

        if (!def->hostdevs[i]->source.subsys.u.usb.vendor &&
            !def->hostdevs[i]->source.subsys.u.usb.product)
            continue;

        VIR_DEBUG("USB Device detected, VendorId:0x%x, ProductId:0x%x",
                  def->hostdevs[i]->source.subsys.u.usb.vendor,
                  def->hostdevs[i]->source.subsys.u.usb.product);
        isUSB = true;
        break;
    }

    if (!isUSB)
        return;

    /* First Start the USB Controller and then loop
     * to attach USB Devices to it
     */
    rc = gVBoxAPI.UIMachine.GetUSBCommon(machine, &USBCommon);
    if (NS_FAILED(rc) || !USBCommon)
        return;
    gVBoxAPI.UIUSBCommon.Enable(USBCommon);

    for (i = 0; i < def->nhostdevs; i++) {
1776
        char *filtername = NULL;
T
Taowei 已提交
1777
        PRUnichar *filternameUtf16 = NULL;
1778 1779 1780
        IUSBDeviceFilter *filter = NULL;
        PRUnichar *vendorIdUtf16 = NULL;
        char vendorId[40] = {0};
T
Taowei 已提交
1781
        PRUnichar *productIdUtf16 = NULL;
1782
        char productId[40] = {0};
T
Taowei 已提交
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833

        if (def->hostdevs[i]->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS)
            continue;

        if (def->hostdevs[i]->source.subsys.type !=
            VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB)
            continue;

        /* Zero pad for nice alignment when fewer than 9999
         * devices.
         */
        if (virAsprintf(&filtername, "filter%04zu", i) >= 0) {
            VBOX_UTF8_TO_UTF16(filtername, &filternameUtf16);
            VIR_FREE(filtername);
            gVBoxAPI.UIUSBCommon.CreateDeviceFilter(USBCommon,
                                                    filternameUtf16,
                                                    &filter);
        }
        VBOX_UTF16_FREE(filternameUtf16);

        if (!filter)
            continue;

        if (!def->hostdevs[i]->source.subsys.u.usb.vendor &&
            !def->hostdevs[i]->source.subsys.u.usb.product)
            continue;

        if (def->hostdevs[i]->source.subsys.u.usb.vendor) {
            snprintf(vendorId, sizeof(vendorId), "%x",
                     def->hostdevs[i]->source.subsys.u.usb.vendor);
            VBOX_UTF8_TO_UTF16(vendorId, &vendorIdUtf16);
            gVBoxAPI.UIUSBDeviceFilter.SetVendorId(filter, vendorIdUtf16);
            VBOX_UTF16_FREE(vendorIdUtf16);
        }
        if (def->hostdevs[i]->source.subsys.u.usb.product) {
            snprintf(productId, sizeof(productId), "%x",
                     def->hostdevs[i]->source.subsys.u.usb.product);
            VBOX_UTF8_TO_UTF16(productId, &productIdUtf16);
            gVBoxAPI.UIUSBDeviceFilter.SetProductId(filter,
                                                    productIdUtf16);
            VBOX_UTF16_FREE(productIdUtf16);
        }
        gVBoxAPI.UIUSBDeviceFilter.SetActive(filter, 1);
        gVBoxAPI.UIUSBCommon.InsertDeviceFilter(USBCommon, i, filter);
        VBOX_RELEASE(filter);
    }

    VBOX_RELEASE(USBCommon);
}

static void
1834
vboxAttachSharedFolder(virDomainDefPtr def, vboxDriverPtr data, IMachine *machine)
T
Taowei 已提交
1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848
{
    size_t i;
    PRUnichar *nameUtf16;
    PRUnichar *hostPathUtf16;
    PRBool writable;

    if (def->nfss == 0)
        return;

    for (i = 0; i < def->nfss; i++) {
        if (def->fss[i]->type != VIR_DOMAIN_FS_TYPE_MOUNT)
            continue;

        VBOX_UTF8_TO_UTF16(def->fss[i]->dst, &nameUtf16);
1849
        VBOX_UTF8_TO_UTF16(def->fss[i]->src->path, &hostPathUtf16);
T
Taowei 已提交
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
        writable = !def->fss[i]->readonly;

        gVBoxAPI.UIMachine.CreateSharedFolder(machine, nameUtf16, hostPathUtf16,
                                              writable, PR_FALSE);

        VBOX_UTF16_FREE(nameUtf16);
        VBOX_UTF16_FREE(hostPathUtf16);
    }
}

1860 1861
static virDomainPtr
vboxDomainDefineXMLFlags(virConnectPtr conn, const char *xml, unsigned int flags)
T
Taowei 已提交
1862
{
1863
    vboxDriverPtr data = conn->privateData;
1864 1865
    IMachine *machine = NULL;
    IBIOSSettings *bios = NULL;
1866
    vboxIID mchiid;
1867
    virDomainDefPtr def = NULL;
T
Taowei 已提交
1868 1869
    nsresult rc;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
T
Taowei Luo 已提交
1870
    virDomainPtr ret = NULL;
1871
    unsigned int parse_flags = VIR_DOMAIN_DEF_PARSE_INACTIVE;
1872 1873
    bool machineReady = false;

T
Taowei Luo 已提交
1874

1875 1876 1877
    virCheckFlags(VIR_DOMAIN_DEFINE_VALIDATE, NULL);

    if (flags & VIR_DOMAIN_DEFINE_VALIDATE)
1878
        parse_flags |= VIR_DOMAIN_DEF_PARSE_VALIDATE_SCHEMA;
1879

T
Taowei Luo 已提交
1880 1881
    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
1882 1883

    if (!(def = virDomainDefParseString(xml, data->caps, data->xmlopt,
1884 1885
                                        NULL, parse_flags)))
        return ret;
T
Taowei 已提交
1886

1887
    VBOX_IID_INITIALIZE(&mchiid);
T
Taowei 已提交
1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
    virUUIDFormat(def->uuid, uuidstr);

    rc = gVBoxAPI.UIVirtualBox.CreateMachine(data, def, &machine, uuidstr);

    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not define a domain, rc=%08x"), (unsigned)rc);
        goto cleanup;
    }

    rc = gVBoxAPI.UIMachine.SetMemorySize(machine,
                                          VIR_DIV_UP(def->mem.cur_balloon, 1024));
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not set the memory size of the domain to: %llu Kb, "
                         "rc=%08x"),
                       def->mem.cur_balloon, (unsigned)rc);
    }

1907
    if (virDomainDefHasVcpusOffline(def)) {
T
Taowei 已提交
1908 1909 1910
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("current vcpu count must equal maximum"));
    }
1911
    rc = gVBoxAPI.UIMachine.SetCPUCount(machine, virDomainDefGetVcpusMax(def));
T
Taowei 已提交
1912 1913 1914
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not set the number of virtual CPUs to: %u, rc=%08x"),
1915
                       virDomainDefGetVcpusMax(def), (unsigned)rc);
T
Taowei 已提交
1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967
    }

    rc = gVBoxAPI.UIMachine.SetCPUProperty(machine, CPUPropertyType_PAE,
                                           def->features[VIR_DOMAIN_FEATURE_PAE] ==
                                           VIR_TRISTATE_SWITCH_ON);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not change PAE status to: %s, rc=%08x"),
                       (def->features[VIR_DOMAIN_FEATURE_PAE] == VIR_TRISTATE_SWITCH_ON)
                       ? _("Enabled") : _("Disabled"), (unsigned)rc);
    }

    gVBoxAPI.UIMachine.GetBIOSSettings(machine, &bios);
    if (bios) {
        rc = gVBoxAPI.UIBIOSSettings.SetACPIEnabled(bios,
                                                    def->features[VIR_DOMAIN_FEATURE_ACPI] ==
                                                    VIR_TRISTATE_SWITCH_ON);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("could not change ACPI status to: %s, rc=%08x"),
                           (def->features[VIR_DOMAIN_FEATURE_ACPI] == VIR_TRISTATE_SWITCH_ON)
                           ? _("Enabled") : _("Disabled"), (unsigned)rc);
        }
        rc = gVBoxAPI.UIBIOSSettings.SetIOAPICEnabled(bios,
                                                      def->features[VIR_DOMAIN_FEATURE_APIC] ==
                                                      VIR_TRISTATE_SWITCH_ON);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("could not change APIC status to: %s, rc=%08x"),
                           (def->features[VIR_DOMAIN_FEATURE_APIC] == VIR_TRISTATE_SWITCH_ON)
                           ? _("Enabled") : _("Disabled"), (unsigned)rc);
        }
        VBOX_RELEASE(bios);
    }

    /* Register the machine before attaching other devices to it */
    rc = gVBoxAPI.UIVirtualBox.RegisterMachine(data->vboxObj, machine);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not define a domain, rc=%08x"), (unsigned)rc);
        goto cleanup;
    }

    /* Get the uuid of the machine, currently it is immutable
     * object so open a session to it and get it back, so that
     * you can make changes to the machine setting
     */
    gVBoxAPI.UIMachine.GetId(machine, &mchiid);
    gVBoxAPI.UISession.Open(data, &mchiid, machine);
    gVBoxAPI.UISession.GetMachine(data->vboxSession, &machine);

    vboxSetBootDeviceOrder(def, data, machine);
1968 1969
    if (vboxAttachStorageControllers(def, data, machine) < 0)
        goto cleanup;
1970 1971
    if (vboxAttachDrives(def, data, machine) < 0)
        goto cleanup;
T
Taowei 已提交
1972
    vboxAttachSound(def, machine);
1973 1974
    if (vboxAttachNetwork(def, data, machine) < 0)
        goto cleanup;
T
Taowei 已提交
1975 1976 1977 1978 1979 1980 1981
    vboxAttachSerial(def, data, machine);
    vboxAttachParallel(def, data, machine);
    vboxAttachVideo(def, machine);
    vboxAttachDisplay(def, data, machine);
    vboxAttachUSB(def, data, machine);
    vboxAttachSharedFolder(def, data, machine);

1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996
    machineReady = true;

 cleanup:
    /* if machine wasn't even created, cleanup is trivial */
    if (!machine) {
        vboxIIDUnalloc(&mchiid);
        virDomainDefFree(def);

        return ret;
    }

    /* Save the machine settings made till now, even when jumped here on error,
     * as otherwise unregister won't cleanup properly. For example, it won't
     * close media that were partially attached. The VBOX SDK docs say that
     * unregister implicitly calls saveSettings but evidently it's not so...
T
Taowei 已提交
1997 1998 1999 2000
     */
    rc = gVBoxAPI.UIMachine.SaveSettings(machine);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
2001 2002
                       _("Failed to save VM settings, rc=%08x"), rc);
        machineReady = false;
T
Taowei 已提交
2003 2004 2005 2006
    }

    gVBoxAPI.UISession.Close(data->vboxSession);

2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
    if (machineReady) {
        ret = virGetDomain(conn, def->name, def->uuid, -1);
    } else {
        /* Unregister incompletely configured VM to not leave garbage behind */
        rc = gVBoxAPI.unregisterMachine(data, &mchiid, &machine);

        if (NS_SUCCEEDED(rc))
            gVBoxAPI.deleteConfig(machine);
        else
            VIR_WARN("Could not cleanup partially created VM after failure, "
                     "rc=%08x", rc);
    }
T
Taowei 已提交
2019

2020 2021
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&mchiid);
T
Taowei 已提交
2022 2023 2024 2025 2026
    virDomainDefFree(def);

    return ret;
}

2027 2028 2029 2030 2031 2032
static virDomainPtr
vboxDomainDefineXML(virConnectPtr conn, const char *xml)
{
    return vboxDomainDefineXMLFlags(conn, xml, 0);
}

T
Taowei 已提交
2033
static int vboxDomainUndefineFlags(virDomainPtr dom, unsigned int flags)
T
Taowei 已提交
2034
{
2035
    vboxDriverPtr data = dom->conn->privateData;
2036
    IMachine *machine = NULL;
2037
    vboxIID iid;
T
Taowei 已提交
2038
    nsresult rc;
T
Taowei Luo 已提交
2039 2040 2041 2042
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066

    gVBoxAPI.UIID.vboxIIDInitialize(&iid);
    /* No managed save, so we explicitly reject
     * VIR_DOMAIN_UNDEFINE_MANAGED_SAVE.  No snapshot metadata for
     * VBox, so we can trivially ignore that flag.  */
    virCheckFlags(VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA, -1);
    vboxIIDFromUUID(&iid, dom->uuid);
    rc = gVBoxAPI.unregisterMachine(data, &iid, &machine);

    DEBUGIID("UUID of machine being undefined", &iid);

    if (NS_SUCCEEDED(rc)) {
        gVBoxAPI.deleteConfig(machine);
        ret = 0;
    } else {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not delete the domain, rc=%08x"), (unsigned)rc);
    }

    vboxIIDUnalloc(&iid);
    VBOX_RELEASE(machine);

    return ret;
}
T
Taowei 已提交
2067

T
Taowei 已提交
2068
static int vboxDomainUndefine(virDomainPtr dom)
T
Taowei 已提交
2069 2070 2071 2072
{
    return vboxDomainUndefineFlags(dom, 0);
}

T
Taowei 已提交
2073
static int
2074
vboxStartMachine(virDomainPtr dom, int maxDomID, IMachine *machine, vboxIID *iid)
T
Taowei 已提交
2075
{
2076
    vboxDriverPtr data = dom->conn->privateData;
2077 2078 2079 2080 2081 2082 2083 2084 2085
    int vrdpPresent = 0;
    int sdlPresent = 0;
    int guiPresent = 0;
    char *guiDisplay = NULL;
    char *sdlDisplay = NULL;
    PRUnichar *keyTypeUtf16 = NULL;
    PRUnichar *valueTypeUtf16 = NULL;
    char *valueTypeUtf8 = NULL;
    PRUnichar *keyDislpayUtf16 = NULL;
T
Taowei 已提交
2086
    PRUnichar *valueDisplayUtf16 = NULL;
2087 2088 2089 2090
    char *valueDisplayUtf8 = NULL;
    IProgress *progress = NULL;
    PRUnichar *env = NULL;
    PRUnichar *sessionType = NULL;
T
Taowei 已提交
2091
    nsresult rc;
T
Taowei Luo 已提交
2092 2093 2094 2095
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140

    VBOX_UTF8_TO_UTF16("FRONTEND/Type", &keyTypeUtf16);
    gVBoxAPI.UIMachine.GetExtraData(machine, keyTypeUtf16, &valueTypeUtf16);
    VBOX_UTF16_FREE(keyTypeUtf16);

    if (valueTypeUtf16) {
        VBOX_UTF16_TO_UTF8(valueTypeUtf16, &valueTypeUtf8);
        VBOX_UTF16_FREE(valueTypeUtf16);

        if (STREQ(valueTypeUtf8, "sdl") || STREQ(valueTypeUtf8, "gui")) {

            VBOX_UTF8_TO_UTF16("FRONTEND/Display", &keyDislpayUtf16);
            gVBoxAPI.UIMachine.GetExtraData(machine, keyDislpayUtf16,
                                            &valueDisplayUtf16);
            VBOX_UTF16_FREE(keyDislpayUtf16);

            if (valueDisplayUtf16) {
                VBOX_UTF16_TO_UTF8(valueDisplayUtf16, &valueDisplayUtf8);
                VBOX_UTF16_FREE(valueDisplayUtf16);

                if (strlen(valueDisplayUtf8) <= 0)
                    VBOX_UTF8_FREE(valueDisplayUtf8);
            }

            if (STREQ(valueTypeUtf8, "sdl")) {
                sdlPresent = 1;
                if (VIR_STRDUP(sdlDisplay, valueDisplayUtf8) < 0) {
                    /* just don't go to cleanup yet as it is ok to have
                     * sdlDisplay as NULL and we check it below if it
                     * exist and then only use it there
                     */
                }
            }

            if (STREQ(valueTypeUtf8, "gui")) {
                guiPresent = 1;
                if (VIR_STRDUP(guiDisplay, valueDisplayUtf8) < 0) {
                    /* just don't go to cleanup yet as it is ok to have
                     * guiDisplay as NULL and we check it below if it
                     * exist and then only use it there
                     */
                }
            }
        }

2141
        if (STREQ(valueTypeUtf8, "vrdp"))
T
Taowei 已提交
2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
            vrdpPresent = 1;

        if (!vrdpPresent && !sdlPresent && !guiPresent) {
            /* if nothing is selected it means either the machine xml
             * file is really old or some values are missing so fallback
             */
            guiPresent = 1;
        }

        VBOX_UTF8_FREE(valueTypeUtf8);

    } else {
        guiPresent = 1;
    }
    VBOX_UTF8_FREE(valueDisplayUtf8);

    if (guiPresent) {
        if (guiDisplay) {
            char *displayutf8;
            if (virAsprintf(&displayutf8, "DISPLAY=%s", guiDisplay) >= 0) {
                VBOX_UTF8_TO_UTF16(displayutf8, &env);
                VIR_FREE(displayutf8);
            }
            VIR_FREE(guiDisplay);
        }

        VBOX_UTF8_TO_UTF16("gui", &sessionType);
    }

    if (sdlPresent) {
        if (sdlDisplay) {
            char *displayutf8;
            if (virAsprintf(&displayutf8, "DISPLAY=%s", sdlDisplay) >= 0) {
                VBOX_UTF8_TO_UTF16(displayutf8, &env);
                VIR_FREE(displayutf8);
            }
            VIR_FREE(sdlDisplay);
        }

        VBOX_UTF8_TO_UTF16("sdl", &sessionType);
    }

2184
    if (vrdpPresent)
T
Taowei 已提交
2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225
        VBOX_UTF8_TO_UTF16("vrdp", &sessionType);

    rc = gVBoxAPI.UIMachine.LaunchVMProcess(data, machine, iid,
                                            sessionType, env,
                                            &progress);

    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("OpenRemoteSession/LaunchVMProcess failed, domain can't be started"));
        ret = -1;
    } else {
        PRBool completed = 0;
        resultCodeUnion resultCode;

        gVBoxAPI.UIProgress.WaitForCompletion(progress, -1);
        rc = gVBoxAPI.UIProgress.GetCompleted(progress, &completed);
        if (NS_FAILED(rc)) {
            /* error */
            ret = -1;
        }
        gVBoxAPI.UIProgress.GetResultCode(progress, &resultCode);
        if (RC_FAILED(resultCode)) {
            /* error */
            ret = -1;
        } else {
            /* all ok set the domid */
            dom->id = maxDomID + 1;
            ret = 0;
        }
    }

    VBOX_RELEASE(progress);

    gVBoxAPI.UISession.Close(data->vboxSession);

    VBOX_UTF16_FREE(env);
    VBOX_UTF16_FREE(sessionType);

    return ret;
}

T
Taowei 已提交
2226
static int vboxDomainCreateWithFlags(virDomainPtr dom, unsigned int flags)
T
Taowei 已提交
2227
{
2228
    vboxDriverPtr data = dom->conn->privateData;
T
Taowei 已提交
2229 2230 2231 2232
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
    unsigned char uuid[VIR_UUID_BUFLEN] = {0};
    nsresult rc;
    size_t i = 0;
T
Taowei Luo 已提交
2233 2234 2235 2236
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261

    virCheckFlags(0, -1);

    if (!dom->name) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Error while reading the domain name"));
        goto cleanup;
    }

    rc = gVBoxAPI.UArray.vboxArrayGet(&machines, data->vboxObj, ARRAY_GET_MACHINES);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of machines, rc=%08x"), (unsigned)rc);
        goto cleanup;
    }

    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
        PRBool isAccessible = PR_FALSE;

        if (!machine)
            continue;

        gVBoxAPI.UIMachine.GetAccessible(machine, &isAccessible);
        if (isAccessible) {
2262
            vboxIID iid;
T
Taowei 已提交
2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296

            VBOX_IID_INITIALIZE(&iid);

            rc = gVBoxAPI.UIMachine.GetId(machine, &iid);
            if (NS_FAILED(rc))
                continue;
            vboxIIDToUUID(&iid, uuid);

            if (memcmp(dom->uuid, uuid, VIR_UUID_BUFLEN) == 0) {
                PRUint32 state;
                gVBoxAPI.UIMachine.GetState(machine, &state);

                if (gVBoxAPI.machineStateChecker.NotStart(state)) {
                    ret = vboxStartMachine(dom, i, machine, &iid);
                } else {
                    virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                                   _("machine is not in "
                                     "poweroff|saved|aborted state, so "
                                     "couldn't start it"));
                    ret = -1;
                }
            }
            vboxIIDUnalloc(&iid);
            if (ret != -1)
                break;
        }
    }

    /* Do the cleanup and take care you dont leak any memory */
    gVBoxAPI.UArray.vboxArrayRelease(&machines);

 cleanup:
    return ret;
}
T
Taowei 已提交
2297

T
Taowei 已提交
2298
static int vboxDomainCreate(virDomainPtr dom)
T
Taowei 已提交
2299 2300 2301
{
    return vboxDomainCreateWithFlags(dom, 0);
}
T
Taowei 已提交
2302

T
Taowei 已提交
2303 2304
static virDomainPtr vboxDomainCreateXML(virConnectPtr conn, const char *xml,
                                        unsigned int flags)
T
Taowei 已提交
2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329
{
    /* VirtualBox currently doesn't have support for running
     * virtual machines without actually defining them and thus
     * for time being just define new machine and start it.
     *
     * TODO: After the appropriate API's are added in VirtualBox
     * change this behaviour to the expected one.
     */

    virDomainPtr dom;

    virCheckFlags(0, NULL);

    dom = vboxDomainDefineXML(conn, xml);
    if (dom == NULL)
        return NULL;

    if (vboxDomainCreate(dom) < 0) {
        vboxDomainUndefineFlags(dom, 0);
        virObjectUnref(dom);
        return NULL;
    }

    return dom;
}
T
Taowei 已提交
2330

T
Taowei 已提交
2331
static int vboxDomainIsActive(virDomainPtr dom)
T
Taowei 已提交
2332
{
2333
    vboxDriverPtr data = dom->conn->privateData;
T
Taowei 已提交
2334
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
2335
    vboxIID iid;
2336
    char *machineNameUtf8 = NULL;
T
Taowei 已提交
2337 2338 2339 2340 2341
    PRUnichar *machineNameUtf16 = NULL;
    unsigned char uuid[VIR_UUID_BUFLEN];
    size_t i;
    bool matched = false;
    nsresult rc;
T
Taowei Luo 已提交
2342 2343 2344 2345
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399

    VBOX_IID_INITIALIZE(&iid);
    rc = gVBoxAPI.UArray.vboxArrayGet(&machines, data->vboxObj, ARRAY_GET_MACHINES);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of machines, rc=%08x"), (unsigned)rc);
        return ret;
    }

    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
        PRBool isAccessible = PR_FALSE;

        if (!machine)
            continue;

        gVBoxAPI.UIMachine.GetAccessible(machine, &isAccessible);
        if (!isAccessible)
            continue;

        gVBoxAPI.UIMachine.GetId(machine, &iid);
        if (NS_FAILED(rc))
            continue;
        vboxIIDToUUID(&iid, uuid);
        vboxIIDUnalloc(&iid);

        if (memcmp(dom->uuid, uuid, VIR_UUID_BUFLEN) == 0) {

            PRUint32 state;

            matched = true;

            gVBoxAPI.UIMachine.GetName(machine, &machineNameUtf16);
            VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);

            gVBoxAPI.UIMachine.GetState(machine, &state);

            if (gVBoxAPI.machineStateChecker.Online(state))
                ret = 1;
            else
                ret = 0;
        }

        if (matched)
            break;
    }

    /* Do the cleanup and take care you dont leak any memory */
    VBOX_UTF8_FREE(machineNameUtf8);
    VBOX_COM_UNALLOC_MEM(machineNameUtf16);
    gVBoxAPI.UArray.vboxArrayRelease(&machines);

    return ret;
}
T
Taowei 已提交
2400

T
Taowei 已提交
2401
static int vboxDomainIsPersistent(virDomainPtr dom)
T
Taowei 已提交
2402 2403 2404
{
    /* All domains are persistent.  However, we do want to check for
     * existence. */
2405
    vboxDriverPtr data = dom->conn->privateData;
2406
    vboxIID iid;
T
Taowei 已提交
2407
    IMachine *machine = NULL;
T
Taowei Luo 已提交
2408 2409 2410 2411
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
2412

2413
    if (openSessionForMachine(data, dom->uuid, &iid, &machine) < 0)
T
Taowei 已提交
2414 2415 2416 2417 2418 2419 2420 2421 2422
        goto cleanup;

    ret = 1;

 cleanup:
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}
T
Taowei 已提交
2423

T
Taowei 已提交
2424
static int vboxDomainIsUpdated(virDomainPtr dom)
T
Taowei 已提交
2425 2426 2427
{
    /* VBox domains never have a persistent state that differs from
     * current state.  However, we do want to check for existence.  */
2428
    vboxDriverPtr data = dom->conn->privateData;
2429
    vboxIID iid;
T
Taowei 已提交
2430
    IMachine *machine = NULL;
T
Taowei Luo 已提交
2431 2432 2433 2434
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
2435

2436
    if (openSessionForMachine(data, dom->uuid, &iid, &machine) < 0)
T
Taowei 已提交
2437 2438 2439 2440 2441 2442 2443 2444 2445
        goto cleanup;

    ret = 0;

 cleanup:
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}
T
Taowei 已提交
2446

T
Taowei 已提交
2447
static int vboxDomainSuspend(virDomainPtr dom)
T
Taowei 已提交
2448
{
2449
    vboxDriverPtr data = dom->conn->privateData;
2450
    IMachine *machine = NULL;
2451
    vboxIID iid;
2452 2453
    IConsole *console = NULL;
    PRBool isAccessible = PR_FALSE;
T
Taowei 已提交
2454
    PRUint32 state;
T
Taowei Luo 已提交
2455 2456 2457 2458
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
2459

2460
    if (openSessionForMachine(data, dom->uuid, &iid, &machine) < 0)
T
Taowei 已提交
2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496
        goto cleanup;

    if (!machine)
        goto cleanup;

    gVBoxAPI.UIMachine.GetAccessible(machine, &isAccessible);
    if (!isAccessible)
        goto cleanup;

    gVBoxAPI.UIMachine.GetState(machine, &state);

    if (gVBoxAPI.machineStateChecker.Running(state)) {
        /* set state pause */
        gVBoxAPI.UISession.OpenExisting(data, &iid, machine);
        gVBoxAPI.UISession.GetConsole(data->vboxSession, &console);
        if (console) {
            gVBoxAPI.UIConsole.Pause(console);
            VBOX_RELEASE(console);
            ret = 0;
        } else {
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("error while suspending the domain"));
            goto cleanup;
        }
        gVBoxAPI.UISession.Close(data->vboxSession);
    } else {
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("machine not in running state to suspend it"));
        goto cleanup;
    }

 cleanup:
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}
T
Taowei 已提交
2497

T
Taowei 已提交
2498
static int vboxDomainResume(virDomainPtr dom)
T
Taowei 已提交
2499
{
2500
    vboxDriverPtr data = dom->conn->privateData;
2501
    IMachine *machine = NULL;
2502
    vboxIID iid;
2503
    IConsole *console = NULL;
T
Taowei 已提交
2504 2505
    PRUint32 state;
    PRBool isAccessible = PR_FALSE;
T
Taowei Luo 已提交
2506 2507 2508 2509
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
2510

2511
    if (openSessionForMachine(data, dom->uuid, &iid, &machine) < 0)
T
Taowei 已提交
2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547
        goto cleanup;

    if (!machine)
        goto cleanup;

    gVBoxAPI.UIMachine.GetAccessible(machine, &isAccessible);
    if (!isAccessible)
        goto cleanup;

    gVBoxAPI.UIMachine.GetState(machine, &state);

    if (gVBoxAPI.machineStateChecker.Paused(state)) {
        /* resume the machine here */
        gVBoxAPI.UISession.OpenExisting(data, &iid, machine);
        gVBoxAPI.UISession.GetConsole(data->vboxSession, &console);
        if (console) {
            gVBoxAPI.UIConsole.Resume(console);
            VBOX_RELEASE(console);
            ret = 0;
        } else {
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("error while resuming the domain"));
            goto cleanup;
        }
        gVBoxAPI.UISession.Close(data->vboxSession);
    } else {
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("machine not paused, so can't resume it"));
        goto cleanup;
    }

 cleanup:
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}
T
Taowei 已提交
2548

T
Taowei 已提交
2549
static int vboxDomainShutdownFlags(virDomainPtr dom, unsigned int flags)
T
Taowei 已提交
2550
{
2551
    vboxDriverPtr data = dom->conn->privateData;
2552
    IMachine *machine = NULL;
2553
    vboxIID iid;
2554
    IConsole *console = NULL;
T
Taowei 已提交
2555
    PRUint32 state;
2556
    PRBool isAccessible = PR_FALSE;
T
Taowei Luo 已提交
2557 2558 2559 2560
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
2561 2562 2563

    virCheckFlags(0, -1);

2564
    if (openSessionForMachine(data, dom->uuid, &iid, &machine) < 0)
T
Taowei 已提交
2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599
        goto cleanup;

    if (!machine)
        goto cleanup;

    gVBoxAPI.UIMachine.GetAccessible(machine, &isAccessible);
    if (!isAccessible)
        goto cleanup;

    gVBoxAPI.UIMachine.GetState(machine, &state);

    if (gVBoxAPI.machineStateChecker.Paused(state)) {
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("machine paused, so can't power it down"));
        goto cleanup;
    } else if (gVBoxAPI.machineStateChecker.PoweredOff(state)) {
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("machine already powered down"));
        goto cleanup;
    }

    gVBoxAPI.UISession.OpenExisting(data, &iid, machine);
    gVBoxAPI.UISession.GetConsole(data->vboxSession, &console);
    if (console) {
        gVBoxAPI.UIConsole.PowerButton(console);
        VBOX_RELEASE(console);
        ret = 0;
    }
    gVBoxAPI.UISession.Close(data->vboxSession);

 cleanup:
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}
T
Taowei 已提交
2600

T
Taowei 已提交
2601
static int vboxDomainShutdown(virDomainPtr dom)
T
Taowei 已提交
2602 2603 2604
{
    return vboxDomainShutdownFlags(dom, 0);
}
T
Taowei 已提交
2605

T
Taowei 已提交
2606
static int vboxDomainReboot(virDomainPtr dom, unsigned int flags)
T
Taowei 已提交
2607
{
2608
    vboxDriverPtr data = dom->conn->privateData;
2609
    IMachine *machine = NULL;
2610
    vboxIID iid;
2611
    IConsole *console = NULL;
T
Taowei 已提交
2612
    PRUint32 state;
2613
    PRBool isAccessible = PR_FALSE;
T
Taowei Luo 已提交
2614 2615 2616 2617
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
2618 2619 2620

    virCheckFlags(0, -1);

2621
    if (openSessionForMachine(data, dom->uuid, &iid, &machine) < 0)
T
Taowei 已提交
2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652
        goto cleanup;

    if (!machine)
        goto cleanup;

    gVBoxAPI.UIMachine.GetAccessible(machine, &isAccessible);
    if (!isAccessible)
        goto cleanup;

    gVBoxAPI.UIMachine.GetState(machine, &state);

    if (gVBoxAPI.machineStateChecker.Running(state)) {
        gVBoxAPI.UISession.OpenExisting(data, &iid, machine);
        gVBoxAPI.UISession.GetConsole(data->vboxSession, &console);
        if (console) {
            gVBoxAPI.UIConsole.Reset(console);
            VBOX_RELEASE(console);
            ret = 0;
        }
        gVBoxAPI.UISession.Close(data->vboxSession);
    } else {
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("machine not running, so can't reboot it"));
        goto cleanup;
    }

 cleanup:
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}
T
Taowei 已提交
2653

T
Taowei 已提交
2654
static int vboxDomainDestroyFlags(virDomainPtr dom, unsigned int flags)
T
Taowei 已提交
2655
{
2656
    vboxDriverPtr data = dom->conn->privateData;
2657
    IMachine *machine = NULL;
2658
    vboxIID iid;
2659
    IConsole *console = NULL;
T
Taowei 已提交
2660
    PRUint32 state;
2661
    PRBool isAccessible = PR_FALSE;
T
Taowei Luo 已提交
2662 2663 2664 2665
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
2666 2667 2668

    virCheckFlags(0, -1);

2669
    if (openSessionForMachine(data, dom->uuid, &iid, &machine) < 0)
T
Taowei 已提交
2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701
        goto cleanup;

    if (!machine)
        goto cleanup;

    gVBoxAPI.UIMachine.GetAccessible(machine, &isAccessible);
    if (!isAccessible)
        goto cleanup;

    gVBoxAPI.UIMachine.GetState(machine, &state);

    if (gVBoxAPI.machineStateChecker.PoweredOff(state)) {
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("machine already powered down"));
        goto cleanup;
    }

    gVBoxAPI.UISession.OpenExisting(data, &iid, machine);
    gVBoxAPI.UISession.GetConsole(data->vboxSession, &console);
    if (console) {
        gVBoxAPI.UIConsole.PowerDown(console);
        VBOX_RELEASE(console);
        dom->id = -1;
        ret = 0;
    }
    gVBoxAPI.UISession.Close(data->vboxSession);

 cleanup:
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}
T
Taowei 已提交
2702

T
Taowei 已提交
2703
static int vboxDomainDestroy(virDomainPtr dom)
T
Taowei 已提交
2704 2705 2706
{
    return vboxDomainDestroyFlags(dom, 0);
}
T
Taowei 已提交
2707

T
Taowei 已提交
2708
static char *vboxDomainGetOSType(virDomainPtr dom ATTRIBUTE_UNUSED) {
T
Taowei 已提交
2709 2710 2711 2712 2713 2714 2715 2716 2717 2718
    /* Returning "hvm" always as suggested on list, cause
     * this functions seems to be badly named and it
     * is supposed to pass the ABI name and not the domain
     * operating system driver as I had imagined ;)
     */
    char *osType;

    ignore_value(VIR_STRDUP(osType, "hvm"));
    return osType;
}
T
Taowei 已提交
2719

T
Taowei 已提交
2720
static int vboxDomainSetMemory(virDomainPtr dom, unsigned long memory)
T
Taowei 已提交
2721
{
2722
    vboxDriverPtr data = dom->conn->privateData;
2723
    IMachine *machine = NULL;
2724
    vboxIID iid;
T
Taowei 已提交
2725
    PRUint32 state;
2726
    PRBool isAccessible = PR_FALSE;
T
Taowei 已提交
2727
    nsresult rc;
T
Taowei Luo 已提交
2728 2729 2730 2731
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
2732

2733
    if (openSessionForMachine(data, dom->uuid, &iid, &machine) < 0)
T
Taowei 已提交
2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776
        goto cleanup;

    if (!machine)
        goto cleanup;

    gVBoxAPI.UIMachine.GetAccessible(machine, &isAccessible);
    if (!isAccessible)
        goto cleanup;

    gVBoxAPI.UIMachine.GetState(machine, &state);

    if (!gVBoxAPI.machineStateChecker.PoweredOff(state)) {
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("memory size can't be changed unless domain is powered down"));
        goto cleanup;
    }

    rc = gVBoxAPI.UISession.Open(data, &iid, machine);
    if (NS_FAILED(rc))
        goto cleanup;

    rc = gVBoxAPI.UISession.GetMachine(data->vboxSession, &machine);
    if (NS_SUCCEEDED(rc) && machine) {

        rc = gVBoxAPI.UIMachine.SetMemorySize(machine,
                                              VIR_DIV_UP(memory, 1024));
        if (NS_SUCCEEDED(rc)) {
            gVBoxAPI.UIMachine.SaveSettings(machine);
            ret = 0;
        } else {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("could not set the memory size of the "
                             "domain to: %lu Kb, rc=%08x"),
                           memory, (unsigned)rc);
        }
    }
    gVBoxAPI.UISession.Close(data->vboxSession);

 cleanup:
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}
T
Taowei 已提交
2777

T
Taowei 已提交
2778
static int vboxDomainGetInfo(virDomainPtr dom, virDomainInfoPtr info)
T
Taowei 已提交
2779
{
2780
    vboxDriverPtr data = dom->conn->privateData;
T
Taowei 已提交
2781
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
2782
    char *machineName = NULL;
T
Taowei 已提交
2783 2784 2785
    PRUnichar *machineNameUtf16 = NULL;
    nsresult rc;
    size_t i = 0;
T
Taowei Luo 已提交
2786 2787 2788 2789
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821

    rc = gVBoxAPI.UArray.vboxArrayGet(&machines, data->vboxObj, ARRAY_GET_MACHINES);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of machines, rc=%08x"), (unsigned)rc);
        goto cleanup;
    }

    info->nrVirtCpu = 0;
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
        PRBool isAccessible = PR_FALSE;

        if (!machine)
            continue;

        gVBoxAPI.UIMachine.GetAccessible(machine, &isAccessible);
        if (!isAccessible)
            continue;

        gVBoxAPI.UIMachine.GetName(machine, &machineNameUtf16);
        VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineName);

        if (STREQ(dom->name, machineName)) {
            /* Get the Machine State (also match it with
            * virDomainState). Get the Machine memory and
            * for time being set max_balloon and cur_balloon to same
            * Also since there is no direct way of checking
            * the cputime required (one condition being the
            * VM is remote), return zero for cputime. Get the
            * number of CPU.
            */
2822
            PRUint32 CPUCount = 0;
T
Taowei 已提交
2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859
            PRUint32 memorySize = 0;
            PRUint32 state;
            PRUint32 maxMemorySize = 4 * 1024;
            ISystemProperties *systemProperties = NULL;

            gVBoxAPI.UIVirtualBox.GetSystemProperties(data->vboxObj, &systemProperties);
            if (systemProperties) {
                gVBoxAPI.UISystemProperties.GetMaxGuestRAM(systemProperties, &maxMemorySize);
                VBOX_RELEASE(systemProperties);
                systemProperties = NULL;
            }

            gVBoxAPI.UIMachine.GetCPUCount(machine, &CPUCount);
            gVBoxAPI.UIMachine.GetMemorySize(machine, &memorySize);
            gVBoxAPI.UIMachine.GetState(machine, &state);

            info->cpuTime = 0;
            info->nrVirtCpu = CPUCount;
            info->memory = memorySize * 1024;
            info->maxMem = maxMemorySize * 1024;
            info->state = gVBoxAPI.vboxConvertState(state);

            ret = 0;
        }

        VBOX_UTF8_FREE(machineName);
        VBOX_COM_UNALLOC_MEM(machineNameUtf16);
        if (info->nrVirtCpu)
            break;

    }

    gVBoxAPI.UArray.vboxArrayRelease(&machines);

 cleanup:
    return ret;
}
T
Taowei 已提交
2860

T
Taowei 已提交
2861 2862
static int vboxDomainGetState(virDomainPtr dom, int *state,
                              int *reason, unsigned int flags)
T
Taowei 已提交
2863
{
2864
    vboxDriverPtr data = dom->conn->privateData;
2865
    vboxIID domiid;
T
Taowei 已提交
2866 2867
    IMachine *machine = NULL;
    PRUint32 mstate;
T
Taowei Luo 已提交
2868 2869 2870 2871
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
2872 2873 2874

    virCheckFlags(0, -1);

2875
    if (openSessionForMachine(data, dom->uuid, &domiid, &machine) < 0)
T
Taowei 已提交
2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890
        goto cleanup;

    gVBoxAPI.UIMachine.GetState(machine, &mstate);

    *state = gVBoxAPI.vboxConvertState(mstate);

    if (reason)
        *reason = 0;

    ret = 0;

 cleanup:
    vboxIIDUnalloc(&domiid);
    return ret;
}
T
Taowei 已提交
2891

T
Taowei 已提交
2892 2893
static int vboxDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                                   unsigned int flags)
T
Taowei 已提交
2894
{
2895
    vboxDriverPtr data = dom->conn->privateData;
2896
    IMachine *machine = NULL;
2897
    vboxIID iid;
2898
    PRUint32 CPUCount = nvcpus;
T
Taowei 已提交
2899
    nsresult rc;
T
Taowei Luo 已提交
2900 2901 2902 2903
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
2904 2905 2906 2907 2908 2909

    if (flags != VIR_DOMAIN_AFFECT_LIVE) {
        virReportError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
        return -1;
    }

2910
    if (openSessionForMachine(data, dom->uuid, &iid, &machine) < 0)
T
Taowei 已提交
2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940
        return -1;

    rc = gVBoxAPI.UISession.Open(data, &iid, machine);
    if (NS_SUCCEEDED(rc)) {
        gVBoxAPI.UISession.GetMachine(data->vboxSession, &machine);
        if (machine) {
            rc = gVBoxAPI.UIMachine.SetCPUCount(machine, CPUCount);
            if (NS_SUCCEEDED(rc)) {
                gVBoxAPI.UIMachine.SaveSettings(machine);
                ret = 0;
            } else {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("could not set the number of cpus of the domain "
                                 "to: %u, rc=%08x"),
                               CPUCount, (unsigned)rc);
            }
            VBOX_RELEASE(machine);
        } else {
            virReportError(VIR_ERR_NO_DOMAIN,
                           _("no domain with matching id %d"), dom->id);
        }
    } else {
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("can't open session to the domain with id %d"), dom->id);
    }
    gVBoxAPI.UISession.Close(data->vboxSession);

    vboxIIDUnalloc(&iid);
    return ret;
}
T
Taowei 已提交
2941

T
Taowei 已提交
2942
static int vboxDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus)
T
Taowei 已提交
2943 2944 2945
{
    return vboxDomainSetVcpusFlags(dom, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
}
T
Taowei 已提交
2946

T
Taowei 已提交
2947
static int vboxDomainGetVcpusFlags(virDomainPtr dom, unsigned int flags)
T
Taowei 已提交
2948
{
2949
    vboxDriverPtr data = dom->conn->privateData;
T
Taowei 已提交
2950 2951
    ISystemProperties *systemProperties = NULL;
    PRUint32 maxCPUCount = 0;
T
Taowei Luo 已提交
2952 2953 2954 2955
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977

    if (flags != (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_VCPU_MAXIMUM)) {
        virReportError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
        return -1;
    }

    /* Currently every domain supports the same number of max cpus
     * as that supported by vbox and thus take it directly from
     * the systemproperties.
     */

    gVBoxAPI.UIVirtualBox.GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        gVBoxAPI.UISystemProperties.GetMaxGuestCPUCount(systemProperties, &maxCPUCount);
        VBOX_RELEASE(systemProperties);
    }

    if (maxCPUCount > 0)
        ret = maxCPUCount;

    return ret;
}
T
Taowei 已提交
2978

T
Taowei 已提交
2979
static int vboxDomainGetMaxVcpus(virDomainPtr dom)
T
Taowei 已提交
2980 2981 2982 2983
{
    return vboxDomainGetVcpusFlags(dom, (VIR_DOMAIN_AFFECT_LIVE |
                                         VIR_DOMAIN_VCPU_MAXIMUM));
}
T
Taowei 已提交
2984 2985

static void
2986
vboxHostDeviceGetXMLDesc(vboxDriverPtr data, virDomainDefPtr def, IMachine *machine)
T
Taowei 已提交
2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018
{
    IUSBCommon *USBCommon = NULL;
    PRBool enabled = PR_FALSE;
    vboxArray deviceFilters = VBOX_ARRAY_INITIALIZER;
    size_t i;
    PRUint32 USBFilterCount = 0;

    def->nhostdevs = 0;

    gVBoxAPI.UIMachine.GetUSBCommon(machine, &USBCommon);
    if (!USBCommon)
        return;

    gVBoxAPI.UIUSBCommon.GetEnabled(USBCommon, &enabled);
    if (!enabled)
        goto release_controller;

    gVBoxAPI.UArray.vboxArrayGet(&deviceFilters, USBCommon,
                                 gVBoxAPI.UArray.handleUSBGetDeviceFilters(USBCommon));

    if (deviceFilters.count <= 0)
        goto release_filters;

    /* check if the filters are active and then only
     * alloc mem and set def->nhostdevs
     */

    for (i = 0; i < deviceFilters.count; i++) {
        PRBool active = PR_FALSE;
        IUSBDeviceFilter *deviceFilter = deviceFilters.items[i];

        gVBoxAPI.UIUSBDeviceFilter.GetActive(deviceFilter, &active);
3019
        if (active)
T
Taowei 已提交
3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030
            def->nhostdevs++;
    }

    if (def->nhostdevs == 0)
        goto release_filters;

    /* Alloc mem needed for the filters now */
    if (VIR_ALLOC_N(def->hostdevs, def->nhostdevs) < 0)
        goto release_filters;

    for (i = 0; i < def->nhostdevs; i++) {
J
John Ferlan 已提交
3031
        def->hostdevs[i] = virDomainHostdevDefNew();
T
Taowei 已提交
3032 3033 3034 3035 3036
        if (!def->hostdevs[i])
            goto release_hostdevs;
    }

    for (i = 0; i < deviceFilters.count; i++) {
3037
        PRBool active = PR_FALSE;
T
Taowei 已提交
3038
        IUSBDeviceFilter *deviceFilter = deviceFilters.items[i];
3039 3040 3041 3042 3043 3044 3045
        PRUnichar *vendorIdUtf16 = NULL;
        char *vendorIdUtf8 = NULL;
        unsigned vendorId = 0;
        PRUnichar *productIdUtf16 = NULL;
        char *productIdUtf8 = NULL;
        unsigned productId = 0;
        char *endptr = NULL;
T
Taowei 已提交
3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064

        gVBoxAPI.UIUSBDeviceFilter.GetActive(deviceFilter, &active);
        if (!active)
            continue;

        def->hostdevs[USBFilterCount]->mode =
            VIR_DOMAIN_HOSTDEV_MODE_SUBSYS;
        def->hostdevs[USBFilterCount]->source.subsys.type =
            VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB;

        gVBoxAPI.UIUSBDeviceFilter.GetVendorId(deviceFilter, &vendorIdUtf16);
        gVBoxAPI.UIUSBDeviceFilter.GetProductId(deviceFilter, &productIdUtf16);

        VBOX_UTF16_TO_UTF8(vendorIdUtf16, &vendorIdUtf8);
        VBOX_UTF16_TO_UTF8(productIdUtf16, &productIdUtf8);

        ignore_value(virStrToLong_ui(vendorIdUtf8, &endptr, 16, &vendorId));
        ignore_value(virStrToLong_ui(productIdUtf8, &endptr, 16, &productId));

3065
        def->hostdevs[USBFilterCount]->source.subsys.u.usb.vendor = vendorId;
T
Taowei 已提交
3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090
        def->hostdevs[USBFilterCount]->source.subsys.u.usb.product = productId;

        VBOX_UTF16_FREE(vendorIdUtf16);
        VBOX_UTF8_FREE(vendorIdUtf8);

        VBOX_UTF16_FREE(productIdUtf16);
        VBOX_UTF8_FREE(productIdUtf8);

        USBFilterCount++;
    }

 release_filters:
    gVBoxAPI.UArray.vboxArrayRelease(&deviceFilters);
 release_controller:
    VBOX_RELEASE(USBCommon);
    return;

 release_hostdevs:
    for (i = 0; i < def->nhostdevs; i++)
        virDomainHostdevDefFree(def->hostdevs[i]);
    VIR_FREE(def->hostdevs);

    goto release_filters;
}

3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143

static int
vboxDumpStorageControllers(virDomainDefPtr def, IMachine *machine)
{
    vboxArray storageControllers = VBOX_ARRAY_INITIALIZER;
    IStorageController *controller = NULL;
    PRUint32 storageBus = StorageBus_Null;
    PRUint32 controllerType = StorageControllerType_Null;
    virDomainControllerDefPtr cont = NULL;
    size_t i = 0;
    int model = -1, ret = -1;
    virDomainControllerType type = VIR_DOMAIN_CONTROLLER_TYPE_LAST;

    gVBoxAPI.UArray.vboxArrayGet(&storageControllers, machine,
                 gVBoxAPI.UArray.handleMachineGetStorageControllers(machine));

    for (i = 0; i < storageControllers.count; i++) {
        controller = storageControllers.items[i];
        storageBus = StorageBus_Null;
        controllerType = StorageControllerType_Null;
        type = VIR_DOMAIN_CONTROLLER_TYPE_LAST;
        model = -1;

        if (!controller)
            continue;

        gVBoxAPI.UIStorageController.GetBus(controller, &storageBus);
        gVBoxAPI.UIStorageController.GetControllerType(controller,
                                                       &controllerType);

        /* vbox controller model => libvirt controller model */
        switch ((enum StorageControllerType) controllerType) {
        case StorageControllerType_PIIX3:
            model = VIR_DOMAIN_CONTROLLER_MODEL_IDE_PIIX3;

            break;
        case StorageControllerType_PIIX4:
            model = VIR_DOMAIN_CONTROLLER_MODEL_IDE_PIIX4;

            break;
        case StorageControllerType_ICH6:
            model = VIR_DOMAIN_CONTROLLER_MODEL_IDE_ICH6;

            break;
        case StorageControllerType_BusLogic:
            model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_BUSLOGIC;

            break;
        case StorageControllerType_LsiLogic:
            model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC;

            break;
        case StorageControllerType_LsiLogicSas:
D
Dawid Zamirski 已提交
3144 3145 3146
            model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSISAS1068;

            break;
3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200
        case StorageControllerType_IntelAhci:
        case StorageControllerType_I82078:
        case StorageControllerType_Null:
            model = -1;

            break;
        }

        /* vbox controller bus => libvirt controller type */
        switch ((enum StorageBus) storageBus) {
        case StorageBus_IDE:
            type = VIR_DOMAIN_CONTROLLER_TYPE_IDE;

            break;
        case StorageBus_SCSI:
        case StorageBus_SAS:
            type = VIR_DOMAIN_CONTROLLER_TYPE_SCSI;

            break;
        case StorageBus_SATA:
            type = VIR_DOMAIN_CONTROLLER_TYPE_SATA;

            break;
        case StorageBus_Floppy:
            type = VIR_DOMAIN_CONTROLLER_TYPE_FDC;

            break;
        case StorageBus_Null:
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Unsupported null storage bus"));

            goto cleanup;
        }

        if (type != VIR_DOMAIN_CONTROLLER_TYPE_LAST) {
            cont = virDomainDefAddController(def, type, -1, model);
            if (!cont) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to add %s controller type definition"),
                               virDomainControllerTypeToString(type));
                goto cleanup;
            }
        }
    }

    ret = 0;

 cleanup:
    gVBoxAPI.UArray.vboxArrayRelease(&storageControllers);

    return ret;
}


3201 3202
static int
vboxDumpDisks(virDomainDefPtr def, vboxDriverPtr data, IMachine *machine)
T
Taowei 已提交
3203
{
3204
    vboxArray mediumAttachments = VBOX_ARRAY_INITIALIZER;
3205
    int ret = -1;
3206 3207 3208 3209 3210 3211 3212 3213 3214
    IMediumAttachment *mediumAttachment = NULL;
    IMedium *medium = NULL;
    IStorageController *controller = NULL;
    PRUnichar *controllerName = NULL, *mediumLocUtf16 = NULL;
    PRUint32 deviceType, storageBus;
    PRInt32 devicePort, deviceSlot;
    PRBool readOnly;
    nsresult rc;
    virDomainDiskDefPtr disk = NULL;
D
Dawid Zamirski 已提交
3215
    virDomainControllerDefPtr ctrl = NULL;
3216
    char *mediumLocUtf8 = NULL;
D
Dawid Zamirski 已提交
3217
    size_t sdCount = 0, i, j;
T
Taowei 已提交
3218 3219 3220

    def->ndisks = 0;
    gVBoxAPI.UArray.vboxArrayGet(&mediumAttachments, machine,
D
Dawid Zamirski 已提交
3221
                 gVBoxAPI.UArray.handleMachineGetMediumAttachments(machine));
T
Taowei 已提交
3222 3223 3224

    /* get the number of attachments */
    for (i = 0; i < mediumAttachments.count; i++) {
3225 3226 3227 3228
        mediumAttachment = mediumAttachments.items[i];
        if (!mediumAttachment)
            continue;

3229 3230 3231 3232 3233
        rc = gVBoxAPI.UIMediumAttachment.GetMedium(mediumAttachment, &medium);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not get IMedium, rc=%08x"), rc);
            goto cleanup;
T
Taowei 已提交
3234
        }
3235 3236 3237

        def->ndisks++;
        VBOX_RELEASE(medium);
T
Taowei 已提交
3238 3239 3240
    }

    /* Allocate mem, if fails return error */
3241 3242 3243 3244
    if (VIR_ALLOC_N(def->disks, def->ndisks) < 0)
        goto cleanup;

    for (i = 0; i < def->ndisks; i++) {
3245
        disk = virDomainDiskDefNew(NULL);
3246 3247 3248 3249
        if (!disk)
            goto cleanup;

        def->disks[i] = disk;
T
Taowei 已提交
3250 3251 3252
    }

    /* get the attachment details here */
3253
    for (i = 0; i < mediumAttachments.count; i++) {
3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264
        mediumAttachment = mediumAttachments.items[i];
        controller = NULL;
        controllerName = NULL;
        deviceType = DeviceType_Null;
        storageBus = StorageBus_Null;
        readOnly = PR_FALSE;
        medium = NULL;
        mediumLocUtf16 = NULL;
        mediumLocUtf8 = NULL;
        devicePort = 0;
        deviceSlot = 0;
3265
        disk = def->disks[i];
3266 3267

        if (!mediumAttachment)
T
Taowei 已提交
3268 3269
            continue;

3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283
        rc = gVBoxAPI.UIMediumAttachment.GetMedium(mediumAttachment, &medium);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not get IMedium, rc=%08x"), rc);
            goto cleanup;
        }

        rc = gVBoxAPI.UIMediumAttachment.GetController(mediumAttachment,
                                                       &controllerName);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to get storage controller name, rc=%08x"),
                           rc);
            goto cleanup;
T
Taowei 已提交
3284 3285
        }

3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320
        rc = gVBoxAPI.UIMachine.GetStorageControllerByName(machine,
                                                           controllerName,
                                                           &controller);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not get storage controller by name, rc=%08x"),
                           rc);
            goto cleanup;
        }

        rc = gVBoxAPI.UIMediumAttachment.GetType(mediumAttachment, &deviceType);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not get device type, rc=%08x"), rc);
            goto cleanup;
        }
        rc = gVBoxAPI.UIMediumAttachment.GetPort(mediumAttachment, &devicePort);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not get device port, rc=%08x"), rc);
            goto cleanup;
        }
        rc = gVBoxAPI.UIMediumAttachment.GetDevice(mediumAttachment, &deviceSlot);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not get device slot, rc=%08x"), rc);
            goto cleanup;
        }
        rc = gVBoxAPI.UIStorageController.GetBus(controller, &storageBus);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not get storage controller bus, rc=%08x"),
                           rc);
            goto cleanup;
        }
3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344

        if (medium) {
            rc = gVBoxAPI.UIMedium.GetLocation(medium, &mediumLocUtf16);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Could not get medium storage location, rc=%08x"),
                               rc);
                goto cleanup;
            }

            VBOX_UTF16_TO_UTF8(mediumLocUtf16, &mediumLocUtf8);

            if (virDomainDiskSetSource(disk, mediumLocUtf8) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Could not set disk source"));
                goto cleanup;
            }

            rc = gVBoxAPI.UIMedium.GetReadOnly(medium, &readOnly);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Could not get read only state, rc=%08x"), rc);
                goto cleanup;
            }
T
Taowei 已提交
3345 3346
        }

3347 3348
        disk->dst = vboxGenerateMediumName(storageBus, devicePort, deviceSlot,
                                           sdCount);
3349

3350
        if (!disk->dst) {
3351 3352 3353 3354 3355 3356
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not generate medium name for the disk "
                             "at: port:%d, slot:%d"), devicePort, deviceSlot);
            goto cleanup;
        }

3357 3358 3359 3360 3361 3362
        disk->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE;
        disk->info.addr.drive.bus = 0;
        disk->info.addr.drive.unit = devicePort;

        switch ((enum StorageBus) storageBus) {
        case StorageBus_IDE:
3363
            disk->bus = VIR_DOMAIN_DISK_BUS_IDE;
3364 3365 3366 3367 3368
            disk->info.addr.drive.bus = devicePort; /* primary, secondary */
            disk->info.addr.drive.unit = deviceSlot; /* master, slave */

            break;
        case StorageBus_SATA:
3369
            disk->bus = VIR_DOMAIN_DISK_BUS_SATA;
3370
            sdCount++;
3371 3372 3373

            break;
        case StorageBus_SCSI:
D
Dawid Zamirski 已提交
3374
        case StorageBus_SAS:
3375
            disk->bus = VIR_DOMAIN_DISK_BUS_SCSI;
3376 3377
            sdCount++;

D
Dawid Zamirski 已提交
3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400
            /* In vbox, if there's a disk attached to SAS controller, there will
             * be libvirt SCSI controller present with model "lsi1068", and we
             * need to find its index
             */
            for (j = 0; j < def->ncontrollers; j++) {
                ctrl = def->controllers[j];

                if (ctrl->type != VIR_DOMAIN_CONTROLLER_TYPE_SCSI)
                    continue;

                if (storageBus == StorageBus_SAS &&
                    ctrl->model == VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSISAS1068) {
                    disk->info.addr.drive.controller = ctrl->idx;
                    break;
                }

                if (storageBus == StorageBus_SCSI &&
                    ctrl->model != VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSISAS1068) {
                    disk->info.addr.drive.controller = ctrl->idx;
                    break;
                }
            }

3401 3402
            break;
        case StorageBus_Floppy:
3403
            disk->bus = VIR_DOMAIN_DISK_BUS_FDC;
3404 3405 3406 3407 3408 3409

            break;
        case StorageBus_Null:
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Unsupported null storage bus"));
            goto cleanup;
T
Taowei 已提交
3410 3411
        }

3412 3413
        switch ((enum DeviceType) deviceType) {
        case DeviceType_HardDisk:
3414
            disk->device = VIR_DOMAIN_DISK_DEVICE_DISK;
3415 3416 3417

            break;
        case DeviceType_Floppy:
3418
            disk->device = VIR_DOMAIN_DISK_DEVICE_FLOPPY;
3419 3420 3421

            break;
        case DeviceType_DVD:
3422
            disk->device = VIR_DOMAIN_DISK_DEVICE_CDROM;
T
Taowei 已提交
3423

3424 3425 3426 3427 3428 3429 3430 3431 3432 3433
            break;
        case DeviceType_Network:
        case DeviceType_USB:
        case DeviceType_SharedFolder:
        case DeviceType_Null:
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unsupported vbox device type: %d"), deviceType);
            goto cleanup;
        }

T
Taowei 已提交
3434
        if (readOnly == PR_TRUE)
3435
            disk->src->readonly = true;
T
Taowei 已提交
3436

3437
        virDomainDiskSetType(disk, VIR_STORAGE_TYPE_FILE);
T
Taowei 已提交
3438

3439 3440 3441 3442 3443
        VBOX_UTF16_FREE(controllerName);
        VBOX_UTF8_FREE(mediumLocUtf8);
        VBOX_UTF16_FREE(mediumLocUtf16);
        VBOX_RELEASE(medium);
        VBOX_RELEASE(controller);
T
Taowei 已提交
3444 3445
    }

3446 3447 3448
    ret = 0;

 cleanup:
T
Taowei 已提交
3449 3450
    gVBoxAPI.UArray.vboxArrayRelease(&mediumAttachments);

3451 3452 3453 3454 3455 3456 3457 3458
    if (ret < 0) {
        VBOX_UTF16_FREE(controllerName);
        VBOX_UTF8_FREE(mediumLocUtf8);
        VBOX_UTF16_FREE(mediumLocUtf16);
        VBOX_RELEASE(medium);
        VBOX_RELEASE(controller);
    }

3459
    return ret;
T
Taowei 已提交
3460 3461
}

J
Ján Tomko 已提交
3462
static int
3463
vboxDumpVideo(virDomainDefPtr def, vboxDriverPtr data ATTRIBUTE_UNUSED,
T
Taowei 已提交
3464 3465 3466
              IMachine *machine)
{
    /* dump video options vram/2d/3d/directx/etc. */
J
Ján Tomko 已提交
3467 3468 3469 3470 3471 3472
    /* the default is: vram is 8MB, One monitor, 3dAccel Off */
    PRUint32 VRAMSize = 8;
    PRUint32 monitorCount = 1;
    PRBool accelerate3DEnabled = PR_FALSE;
    PRBool accelerate2DEnabled = PR_FALSE;

T
Taowei 已提交
3473
    /* Currently supports only one graphics card */
J
Ján Tomko 已提交
3474 3475
    if (VIR_ALLOC_N(def->videos, 1) < 0)
        return -1;
T
Taowei 已提交
3476
    def->nvideos = 1;
J
Ján Tomko 已提交
3477 3478 3479 3480 3481 3482 3483

    if (VIR_ALLOC(def->videos[0]) < 0)
        return -1;

    gVBoxAPI.UIMachine.GetVRAMSize(machine, &VRAMSize);
    gVBoxAPI.UIMachine.GetMonitorCount(machine, &monitorCount);
    gVBoxAPI.UIMachine.GetAccelerate3DEnabled(machine, &accelerate3DEnabled);
3484
    gVBoxAPI.UIMachine.GetAccelerate2DVideoEnabled(machine, &accelerate2DEnabled);
J
Ján Tomko 已提交
3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496

    def->videos[0]->type = VIR_DOMAIN_VIDEO_TYPE_VBOX;
    def->videos[0]->vram = VRAMSize * 1024;
    def->videos[0]->heads = monitorCount;
    if (VIR_ALLOC(def->videos[0]->accel) < 0)
        return -1;
    def->videos[0]->accel->accel3d = accelerate3DEnabled ?
        VIR_TRISTATE_BOOL_YES : VIR_TRISTATE_BOOL_NO;
    def->videos[0]->accel->accel2d = accelerate2DEnabled ?
        VIR_TRISTATE_BOOL_YES : VIR_TRISTATE_BOOL_NO;

    return 0;
T
Taowei 已提交
3497 3498
}

3499
static int
3500
vboxDumpDisplay(virDomainDefPtr def, vboxDriverPtr data, IMachine *machine)
T
Taowei 已提交
3501 3502
{
    /* dump display options vrdp/gui/sdl */
3503
    PRUnichar *keyUtf16 = NULL;
T
Taowei 已提交
3504
    PRUnichar *valueTypeUtf16 = NULL;
3505
    char *valueTypeUtf8 = NULL;
3506
    char *netAddressUtf8 = NULL;
3507
    IVRDEServer *VRDEServer = NULL;
3508
    PRBool VRDxEnabled = PR_FALSE;
3509
    virDomainGraphicsDefPtr graphics = NULL;
3510
    int ret = -1;
T
Taowei 已提交
3511 3512 3513

    def->ngraphics = 0;

3514 3515 3516
    VBOX_UTF8_TO_UTF16("FRONTEND/Type", &keyUtf16);
    gVBoxAPI.UIMachine.GetExtraData(machine, keyUtf16, &valueTypeUtf16);
    VBOX_UTF16_FREE(keyUtf16);
T
Taowei 已提交
3517 3518 3519 3520

    if (valueTypeUtf16) {
        VBOX_UTF16_TO_UTF8(valueTypeUtf16, &valueTypeUtf8);
        VBOX_UTF16_FREE(valueTypeUtf16);
3521
    }
T
Taowei 已提交
3522

3523 3524 3525 3526
    if (STREQ_NULLABLE(valueTypeUtf8, "sdl") ||
        STREQ_NULLABLE(valueTypeUtf8, "gui")) {
        PRUnichar *valueDisplayUtf16 = NULL;
        char *valueDisplayUtf8 = NULL;
T
Taowei 已提交
3527

3528 3529 3530
        if (VIR_ALLOC(graphics) < 0)
            goto cleanup;

3531 3532 3533
        VBOX_UTF8_TO_UTF16("FRONTEND/Display", &keyUtf16);
        gVBoxAPI.UIMachine.GetExtraData(machine, keyUtf16, &valueDisplayUtf16);
        VBOX_UTF16_FREE(keyUtf16);
T
Taowei 已提交
3534

3535 3536 3537
        if (valueDisplayUtf16) {
            VBOX_UTF16_TO_UTF8(valueDisplayUtf16, &valueDisplayUtf8);
            VBOX_UTF16_FREE(valueDisplayUtf16);
T
Taowei 已提交
3538

3539
            if (STREQ(valueDisplayUtf8, ""))
3540 3541
                VBOX_UTF8_FREE(valueDisplayUtf8);
        }
T
Taowei 已提交
3542

3543
        if (STREQ(valueTypeUtf8, "sdl")) {
3544
            graphics->type = VIR_DOMAIN_GRAPHICS_TYPE_SDL;
3545 3546
            graphics->data.sdl.display = valueDisplayUtf8;
            valueDisplayUtf8 = NULL;
3547
        }
T
Taowei 已提交
3548

3549
        if (STREQ(valueTypeUtf8, "gui")) {
3550
            graphics->type = VIR_DOMAIN_GRAPHICS_TYPE_DESKTOP;
3551 3552
            graphics->data.desktop.display = valueDisplayUtf8;
            valueDisplayUtf8 = NULL;
T
Taowei 已提交
3553
        }
3554
        VBOX_UTF8_FREE(valueDisplayUtf8);
3555
    } else if (STRNEQ_NULLABLE(valueTypeUtf8, "vrdp")) {
3556 3557
        if (VIR_ALLOC(graphics) < 0)
            goto cleanup;
3558 3559

        graphics->type = VIR_DOMAIN_GRAPHICS_TYPE_DESKTOP;
3560 3561 3562
        if (VIR_STRDUP(graphics->data.desktop.display,
                       virGetEnvBlockSUID("DISPLAY")) < 0)
            goto cleanup;
T
Taowei 已提交
3563 3564
    }

3565 3566 3567
    if (graphics &&
        VIR_APPEND_ELEMENT(def->graphics, def->ngraphics, graphics) < 0)
        goto cleanup;
T
Taowei 已提交
3568

3569 3570 3571
    gVBoxAPI.UIMachine.GetVRDEServer(machine, &VRDEServer);
    if (VRDEServer)
        gVBoxAPI.UIVRDEServer.GetEnabled(VRDEServer, &VRDxEnabled);
T
Taowei 已提交
3572

3573
    if (VRDxEnabled) {
3574 3575 3576 3577 3578
        PRUnichar *netAddressUtf16 = NULL;
        PRBool allowMultiConnection = PR_FALSE;
        PRBool reuseSingleConnection = PR_FALSE;

        if (VIR_ALLOC(graphics) < 0)
3579
            goto cleanup;
T
Taowei 已提交
3580

3581
        gVBoxAPI.UIVRDEServer.GetPorts(data, VRDEServer, machine, graphics);
T
Taowei 已提交
3582

3583
        graphics->type = VIR_DOMAIN_GRAPHICS_TYPE_RDP;
3584

3585
        gVBoxAPI.UIVRDEServer.GetNetAddress(data, VRDEServer, &netAddressUtf16);
3586 3587 3588 3589
        if (netAddressUtf16) {
            VBOX_UTF16_TO_UTF8(netAddressUtf16, &netAddressUtf8);
            VBOX_UTF16_FREE(netAddressUtf16);
        }
T
Taowei 已提交
3590

3591 3592 3593 3594
        if (netAddressUtf8 && STREQ(netAddressUtf8, ""))
            VBOX_UTF8_FREE(netAddressUtf8);

        if (virDomainGraphicsListenAppendAddress(graphics, netAddressUtf8) < 0)
3595 3596
            goto cleanup;

3597
        gVBoxAPI.UIVRDEServer.GetAllowMultiConnection(VRDEServer, &allowMultiConnection);
3598
        if (allowMultiConnection)
3599
            graphics->data.rdp.multiUser = true;
T
Taowei 已提交
3600

3601
        gVBoxAPI.UIVRDEServer.GetReuseSingleConnection(VRDEServer, &reuseSingleConnection);
3602
        if (reuseSingleConnection)
3603
            graphics->data.rdp.replaceUser = true;
3604

3605
        if (VIR_APPEND_ELEMENT(def->graphics, def->ngraphics, graphics) < 0)
3606
            goto cleanup;
T
Taowei 已提交
3607
    }
3608

3609 3610 3611
    ret = 0;

 cleanup:
3612
    VBOX_RELEASE(VRDEServer);
3613
    VBOX_UTF8_FREE(valueTypeUtf8);
3614
    VBOX_UTF8_FREE(netAddressUtf8);
3615
    virDomainGraphicsDefFree(graphics);
3616
    return ret;
T
Taowei 已提交
3617 3618
}

3619
static int
3620
vboxDumpSharedFolders(virDomainDefPtr def, vboxDriverPtr data, IMachine *machine)
T
Taowei 已提交
3621 3622 3623
{
    vboxArray sharedFolders = VBOX_ARRAY_INITIALIZER;
    size_t i = 0;
3624
    int ret = -1;
T
Taowei 已提交
3625 3626 3627 3628 3629 3630

    def->nfss = 0;

    gVBoxAPI.UArray.vboxArrayGet(&sharedFolders, machine,
                                 gVBoxAPI.UArray.handleMachineGetSharedFolders(machine));

3631 3632 3633
    if (sharedFolders.count <= 0) {
        if (sharedFolders.count == 0)
            ret = 0;
3634
        goto cleanup;
3635
    }
T
Taowei 已提交
3636 3637

    if (VIR_ALLOC_N(def->fss, sharedFolders.count) < 0)
3638
        goto cleanup;
T
Taowei 已提交
3639 3640 3641 3642 3643 3644 3645 3646 3647 3648

    for (i = 0; i < sharedFolders.count; i++) {
        ISharedFolder *sharedFolder = sharedFolders.items[i];
        PRUnichar *nameUtf16 = NULL;
        char *name = NULL;
        PRUnichar *hostPathUtf16 = NULL;
        char *hostPath = NULL;
        PRBool writable = PR_FALSE;

        if (VIR_ALLOC(def->fss[i]) < 0)
3649
            goto cleanup;
T
Taowei 已提交
3650 3651 3652 3653 3654

        def->fss[i]->type = VIR_DOMAIN_FS_TYPE_MOUNT;

        gVBoxAPI.UISharedFolder.GetHostPath(sharedFolder, &hostPathUtf16);
        VBOX_UTF16_TO_UTF8(hostPathUtf16, &hostPath);
3655
        if (VIR_STRDUP(def->fss[i]->src->path, hostPath) < 0) {
T
Taowei 已提交
3656 3657
            VBOX_UTF8_FREE(hostPath);
            VBOX_UTF16_FREE(hostPathUtf16);
3658
            goto cleanup;
T
Taowei 已提交
3659 3660 3661 3662 3663 3664 3665 3666 3667
        }
        VBOX_UTF8_FREE(hostPath);
        VBOX_UTF16_FREE(hostPathUtf16);

        gVBoxAPI.UISharedFolder.GetName(sharedFolder, &nameUtf16);
        VBOX_UTF16_TO_UTF8(nameUtf16, &name);
        if (VIR_STRDUP(def->fss[i]->dst, name) < 0) {
            VBOX_UTF8_FREE(name);
            VBOX_UTF16_FREE(nameUtf16);
3668
            goto cleanup;
T
Taowei 已提交
3669 3670 3671 3672 3673 3674 3675 3676 3677 3678
        }
        VBOX_UTF8_FREE(name);
        VBOX_UTF16_FREE(nameUtf16);

        gVBoxAPI.UISharedFolder.GetWritable(sharedFolder, &writable);
        def->fss[i]->readonly = !writable;

        ++def->nfss;
    }

3679 3680
    ret = 0;

3681
 cleanup:
T
Taowei 已提交
3682
    gVBoxAPI.UArray.vboxArrayRelease(&sharedFolders);
3683
    return ret;
T
Taowei 已提交
3684 3685
}

3686 3687
static virDomainNetDefPtr
vboxDumpNetwork(vboxDriverPtr data, INetworkAdapter *adapter)
3688 3689 3690
{
    PRUint32 attachmentType = NetworkAttachmentType_Null;
    PRUint32 adapterType = NetworkAdapterType_Null;
3691
    PRUnichar *utf16 = NULL;
3692
    char *utf8 = NULL;
3693 3694 3695 3696
    virDomainNetDefPtr net = NULL;

    if (VIR_ALLOC(net) < 0)
        return NULL;
3697 3698 3699

    gVBoxAPI.UINetworkAdapter.GetAttachmentType(adapter, &attachmentType);

3700 3701
    switch (attachmentType) {
    case NetworkAttachmentType_NAT:
3702
        net->type = VIR_DOMAIN_NET_TYPE_USER;
3703
        break;
3704

3705
    case NetworkAttachmentType_Bridged:
3706 3707
        net->type = VIR_DOMAIN_NET_TYPE_BRIDGE;

3708
        gVBoxAPI.UINetworkAdapter.GetBridgedInterface(adapter, &utf16);
3709

3710
        VBOX_UTF16_TO_UTF8(utf16, &utf8);
3711
        VIR_STEAL_PTR(net->data.bridge.brname, utf8);
3712
        VBOX_UTF16_FREE(utf16);
3713
        break;
3714

3715
    case NetworkAttachmentType_Internal:
3716 3717
        net->type = VIR_DOMAIN_NET_TYPE_INTERNAL;

3718
        gVBoxAPI.UINetworkAdapter.GetInternalNetwork(adapter, &utf16);
3719

3720
        VBOX_UTF16_TO_UTF8(utf16, &utf8);
3721
        VIR_STEAL_PTR(net->data.internal.name, utf8);
3722
        VBOX_UTF16_FREE(utf16);
3723
        break;
3724

3725
    case NetworkAttachmentType_HostOnly:
3726 3727
        net->type = VIR_DOMAIN_NET_TYPE_NETWORK;

3728
        gVBoxAPI.UINetworkAdapter.GetHostOnlyInterface(adapter, &utf16);
3729

3730
        VBOX_UTF16_TO_UTF8(utf16, &utf8);
3731
        VIR_STEAL_PTR(net->data.network.name, utf8);
3732
        VBOX_UTF16_FREE(utf16);
3733
        break;
3734

3735
    default:
3736 3737 3738 3739 3740 3741 3742
        /* default to user type i.e. NAT in VirtualBox if this
         * dump is ever used to create a machine.
         */
        net->type = VIR_DOMAIN_NET_TYPE_USER;
    }

    gVBoxAPI.UINetworkAdapter.GetAdapterType(adapter, &adapterType);
3743 3744
    switch (adapterType) {
    case NetworkAdapterType_Am79C970A:
C
Cole Robinson 已提交
3745
        net->model = VIR_DOMAIN_NET_MODEL_AM79C970A;
3746 3747
        break;
    case NetworkAdapterType_Am79C973:
C
Cole Robinson 已提交
3748
        net->model = VIR_DOMAIN_NET_MODEL_AM79C973;
3749 3750
        break;
    case NetworkAdapterType_I82540EM:
C
Cole Robinson 已提交
3751
        net->model = VIR_DOMAIN_NET_MODEL_82540EM;
3752 3753
        break;
    case NetworkAdapterType_I82545EM:
C
Cole Robinson 已提交
3754
        net->model = VIR_DOMAIN_NET_MODEL_82545EM;
3755 3756
        break;
    case NetworkAdapterType_I82543GC:
C
Cole Robinson 已提交
3757
        net->model = VIR_DOMAIN_NET_MODEL_82543GC;
3758 3759
        break;
    case NetworkAdapterType_Virtio:
3760
        /* Only vbox 3.1 and later support NetworkAdapterType_Virto */
3761
        if (gVBoxAPI.APIVersion >= 3000051)
C
Cole Robinson 已提交
3762
            net->model = VIR_DOMAIN_NET_MODEL_VIRTIO;
3763
        break;
3764 3765
    }

3766
    gVBoxAPI.UINetworkAdapter.GetMACAddress(adapter, &utf16);
3767
    VBOX_UTF16_TO_UTF8(utf16, &utf8);
3768
    VBOX_UTF16_FREE(utf16);
3769

3770 3771
    if (virMacAddrParseHex(utf8, &net->mac) < 0) {
        VBOX_UTF8_FREE(utf8);
3772 3773
        goto error;
    }
3774

3775
    VBOX_UTF8_FREE(utf8);
3776
    return net;
3777 3778 3779 3780

 error:
    virDomainNetDefFree(net);
    return NULL;
3781 3782
}

3783
static int
3784
vboxDumpNetworks(virDomainDefPtr def, vboxDriverPtr data, IMachine *machine, PRUint32 networkAdapterCount)
T
Taowei 已提交
3785 3786
{
    size_t i = 0;
3787

T
Taowei 已提交
3788 3789
    for (i = 0; i < networkAdapterCount; i++) {
        INetworkAdapter *adapter = NULL;
3790
        virDomainNetDefPtr net = NULL;
3791
        PRBool enabled = PR_FALSE;
T
Taowei 已提交
3792 3793

        gVBoxAPI.UIMachine.GetNetworkAdapter(machine, i, &adapter);
3794
        if (adapter)
T
Taowei 已提交
3795 3796
            gVBoxAPI.UINetworkAdapter.GetEnabled(adapter, &enabled);

3797
        if (enabled) {
3798
            net = vboxDumpNetwork(data, adapter);
3799 3800 3801 3802
            if (VIR_APPEND_ELEMENT(def->nets, def->nnets, net) < 0) {
                VBOX_RELEASE(adapter);
                return -1;
            }
T
Taowei 已提交
3803
        }
3804 3805

        VBOX_RELEASE(adapter);
T
Taowei 已提交
3806
    }
3807 3808

    return 0;
T
Taowei 已提交
3809 3810 3811
}

static void
3812
vboxDumpAudio(virDomainDefPtr def, vboxDriverPtr data ATTRIBUTE_UNUSED,
T
Taowei 已提交
3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850
              IMachine *machine)
{
    /* dump sound card if active */

    /* Set def->nsounds to one as VirtualBox currently supports
     * only one sound card
     */
    IAudioAdapter *audioAdapter = NULL;

    gVBoxAPI.UIMachine.GetAudioAdapter(machine, &audioAdapter);
    if (audioAdapter) {
        PRBool enabled = PR_FALSE;

        gVBoxAPI.UIAudioAdapter.GetEnabled(audioAdapter, &enabled);
        if (enabled) {
            PRUint32 audioController = AudioControllerType_AC97;

            def->nsounds = 1;
            if (VIR_ALLOC_N(def->sounds, def->nsounds) >= 0) {
                if (VIR_ALLOC(def->sounds[0]) >= 0) {
                    gVBoxAPI.UIAudioAdapter.GetAudioController(audioAdapter, &audioController);
                    if (audioController == AudioControllerType_SB16) {
                        def->sounds[0]->model = VIR_DOMAIN_SOUND_MODEL_SB16;
                    } else if (audioController == AudioControllerType_AC97) {
                        def->sounds[0]->model = VIR_DOMAIN_SOUND_MODEL_AC97;
                    }
                } else {
                    VIR_FREE(def->sounds);
                    def->nsounds = 0;
                }
            } else {
                def->nsounds = 0;
            }
        }
        VBOX_RELEASE(audioAdapter);
    }
}

3851
static int
3852
vboxDumpSerial(virDomainDefPtr def, vboxDriverPtr data, IMachine *machine, PRUint32 serialPortCount)
T
Taowei 已提交
3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866
{
    PRUint32 serialPortIncCount = 0;
    size_t i = 0;
    /* dump serial port if active */
    def->nserials = 0;
    /* Get which serial ports are enabled/active */
    for (i = 0; i < serialPortCount; i++) {
        ISerialPort *serialPort = NULL;

        gVBoxAPI.UIMachine.GetSerialPort(machine, i, &serialPort);
        if (serialPort) {
            PRBool enabled = PR_FALSE;

            gVBoxAPI.UISerialPort.GetEnabled(serialPort, &enabled);
3867
            if (enabled)
T
Taowei 已提交
3868 3869 3870 3871 3872 3873 3874
                def->nserials++;

            VBOX_RELEASE(serialPort);
        }
    }

    /* Allocate memory for the serial ports which are enabled */
3875 3876 3877 3878 3879 3880 3881 3882 3883
    if (def->nserials > 0) {
        if (VIR_ALLOC_N(def->serials, def->nserials) < 0)
            return -1;

        for (i = 0; i < def->nserials; i++) {
            def->serials[i] = virDomainChrDefNew(NULL);
            if (!def->serials[i])
                return -1;
        }
T
Taowei 已提交
3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897
    }

    /* Now get the details about the serial ports here */
    for (i = 0;
         serialPortIncCount < def->nserials && i < serialPortCount;
         i++) {
        ISerialPort *serialPort = NULL;

        gVBoxAPI.UIMachine.GetSerialPort(machine, i, &serialPort);
        if (serialPort) {
            PRBool enabled = PR_FALSE;

            gVBoxAPI.UISerialPort.GetEnabled(serialPort, &enabled);
            if (enabled) {
3898 3899 3900
                PRUint32 hostMode = PortMode_Disconnected;
                PRUint32 IOBase = 0;
                PRUint32 IRQ = 0;
T
Taowei 已提交
3901
                PRUnichar *pathUtf16 = NULL;
3902
                char *path = NULL;
T
Taowei 已提交
3903 3904 3905

                gVBoxAPI.UISerialPort.GetHostMode(serialPort, &hostMode);
                if (hostMode == PortMode_HostPipe) {
3906
                    def->serials[serialPortIncCount]->source->type = VIR_DOMAIN_CHR_TYPE_PIPE;
T
Taowei 已提交
3907
                } else if (hostMode == PortMode_HostDevice) {
3908
                    def->serials[serialPortIncCount]->source->type = VIR_DOMAIN_CHR_TYPE_DEV;
T
Taowei 已提交
3909 3910 3911
                } else if (gVBoxAPI.APIVersion >= 2002051 &&
                           hostMode == PortMode_RawFile) {
                    /* PortMode RawFile is used for vbox 3.0 or later */
3912
                    def->serials[serialPortIncCount]->source->type = VIR_DOMAIN_CHR_TYPE_FILE;
T
Taowei 已提交
3913
                } else {
3914
                    def->serials[serialPortIncCount]->source->type = VIR_DOMAIN_CHR_TYPE_NULL;
T
Taowei 已提交
3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930
                }

                def->serials[serialPortIncCount]->deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL;

                gVBoxAPI.UISerialPort.GetIRQ(serialPort, &IRQ);
                gVBoxAPI.UISerialPort.GetIOBase(serialPort, &IOBase);
                if ((IRQ == 4) && (IOBase == 1016)) {
                    def->serials[serialPortIncCount]->target.port = 0;
                } else if ((IRQ == 3) && (IOBase == 760)) {
                    def->serials[serialPortIncCount]->target.port = 1;
                }

                gVBoxAPI.UISerialPort.GetPath(serialPort, &pathUtf16);

                if (pathUtf16) {
                    VBOX_UTF16_TO_UTF8(pathUtf16, &path);
3931 3932
                    if (VIR_STRDUP(def->serials[serialPortIncCount]->source->data.file.path, path) < 0)
                        return -1;
T
Taowei 已提交
3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943
                }

                serialPortIncCount++;

                VBOX_UTF16_FREE(pathUtf16);
                VBOX_UTF8_FREE(path);
            }

            VBOX_RELEASE(serialPort);
        }
    }
3944
    return 0;
T
Taowei 已提交
3945 3946
}

3947
static int
3948
vboxDumpParallel(virDomainDefPtr def, vboxDriverPtr data, IMachine *machine, PRUint32 parallelPortCount)
T
Taowei 已提交
3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962
{
    PRUint32 parallelPortIncCount = 0;
    size_t i = 0;
    /* dump parallel ports if active */
    def->nparallels = 0;
    /* Get which parallel ports are enabled/active */
    for (i = 0; i < parallelPortCount; i++) {
        IParallelPort *parallelPort = NULL;

        gVBoxAPI.UIMachine.GetParallelPort(machine, i, &parallelPort);
        if (parallelPort) {
            PRBool enabled = PR_FALSE;

            gVBoxAPI.UIParallelPort.GetEnabled(parallelPort, &enabled);
3963
            if (enabled)
T
Taowei 已提交
3964 3965 3966 3967 3968 3969 3970
                def->nparallels++;

            VBOX_RELEASE(parallelPort);
        }
    }

    /* Allocate memory for the parallel ports which are enabled */
3971 3972 3973 3974 3975 3976 3977 3978 3979
    if (def->nparallels > 0) {
        if (VIR_ALLOC_N(def->parallels, def->nparallels) < 0)
            return -1;

        for (i = 0; i < def->nparallels; i++) {
            def->parallels[i] = virDomainChrDefNew(NULL);
            if (!def->parallels[i])
                return -1;
        }
T
Taowei 已提交
3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994
    }

    /* Now get the details about the parallel ports here */
    for (i = 0;
         parallelPortIncCount < def->nparallels &&
             i < parallelPortCount;
         i++) {
        IParallelPort *parallelPort = NULL;

        gVBoxAPI.UIMachine.GetParallelPort(machine, i, &parallelPort);
        if (parallelPort) {
            PRBool enabled = PR_FALSE;

            gVBoxAPI.UIParallelPort.GetEnabled(parallelPort, &enabled);
            if (enabled) {
3995 3996
                PRUint32 IOBase = 0;
                PRUint32 IRQ = 0;
T
Taowei 已提交
3997
                PRUnichar *pathUtf16 = NULL;
3998
                char *path = NULL;
T
Taowei 已提交
3999 4000 4001 4002 4003 4004 4005 4006 4007

                gVBoxAPI.UIParallelPort.GetIRQ(parallelPort, &IRQ);
                gVBoxAPI.UIParallelPort.GetIOBase(parallelPort, &IOBase);
                if ((IRQ == 7) && (IOBase == 888)) {
                    def->parallels[parallelPortIncCount]->target.port = 0;
                } else if ((IRQ == 5) && (IOBase == 632)) {
                    def->parallels[parallelPortIncCount]->target.port = 1;
                }

4008
                def->parallels[parallelPortIncCount]->source->type = VIR_DOMAIN_CHR_TYPE_FILE;
T
Taowei 已提交
4009 4010 4011 4012 4013
                def->parallels[parallelPortIncCount]->deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_PARALLEL;

                gVBoxAPI.UIParallelPort.GetPath(parallelPort, &pathUtf16);

                VBOX_UTF16_TO_UTF8(pathUtf16, &path);
4014 4015
                if (VIR_STRDUP(def->parallels[parallelPortIncCount]->source->data.file.path, path) < 0)
                    return -1;
T
Taowei 已提交
4016 4017 4018 4019 4020 4021 4022 4023 4024 4025

                parallelPortIncCount++;

                VBOX_UTF16_FREE(pathUtf16);
                VBOX_UTF8_FREE(path);
            }

            VBOX_RELEASE(parallelPort);
        }
    }
4026
    return 0;
T
Taowei 已提交
4027 4028
}

T
Taowei 已提交
4029
static char *vboxDomainGetXMLDesc(virDomainPtr dom, unsigned int flags)
T
Taowei 已提交
4030
{
4031
    vboxDriverPtr data = dom->conn->privateData;
4032 4033
    virDomainDefPtr def = NULL;
    IMachine *machine = NULL;
4034
    vboxIID iid;
T
Taowei 已提交
4035 4036
    PRBool accessible = PR_FALSE;
    size_t i = 0;
4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048
    PRBool PAEEnabled = PR_FALSE;
    PRBool ACPIEnabled = PR_FALSE;
    PRBool IOAPICEnabled = PR_FALSE;
    PRUint32 CPUCount = 0;
    PRUint32 memorySize = 0;
    PRUint32 networkAdapterCount = 0;
    PRUint32 maxMemorySize = 4 * 1024;
    PRUint32 maxBootPosition = 0;
    PRUint32 serialPortCount = 0;
    PRUint32 parallelPortCount = 0;
    IBIOSSettings *bios = NULL;
    PRUint32 chipsetType = ChipsetType_Null;
T
Taowei 已提交
4049
    ISystemProperties *systemProperties = NULL;
T
Taowei Luo 已提交
4050 4051 4052 4053
    char *ret = NULL;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
4054

4055
    virCheckFlags(VIR_DOMAIN_XML_COMMON_FLAGS, NULL);
T
Taowei 已提交
4056

4057
    if (openSessionForMachine(data, dom->uuid, &iid, &machine) < 0)
T
Taowei 已提交
4058 4059
        goto cleanup;

4060
    if (!(def = virDomainDefNew()))
T
Taowei 已提交
4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093
        goto cleanup;

    gVBoxAPI.UIMachine.GetAccessible(machine, &accessible);
    if (!accessible)
        goto cleanup;

    def->virtType = VIR_DOMAIN_VIRT_VBOX;
    def->id = dom->id;
    memcpy(def->uuid, dom->uuid, VIR_UUID_BUFLEN);
    if (VIR_STRDUP(def->name, dom->name) < 0)
        goto cleanup;

    gVBoxAPI.UIMachine.GetMemorySize(machine, &memorySize);
    def->mem.cur_balloon = memorySize * 1024;

    if (gVBoxAPI.chipsetType)
        gVBoxAPI.UIMachine.GetChipsetType(machine, &chipsetType);

    gVBoxAPI.UIVirtualBox.GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        gVBoxAPI.UISystemProperties.GetMaxGuestRAM(systemProperties, &maxMemorySize);
        gVBoxAPI.UISystemProperties.GetMaxBootPosition(systemProperties, &maxBootPosition);
        gVBoxAPI.UISystemProperties.GetMaxNetworkAdapters(systemProperties, chipsetType, &networkAdapterCount);
        gVBoxAPI.UISystemProperties.GetSerialPortCount(systemProperties, &serialPortCount);
        gVBoxAPI.UISystemProperties.GetParallelPortCount(systemProperties, &parallelPortCount);
        VBOX_RELEASE(systemProperties);
        systemProperties = NULL;
    }
    /* Currently setting memory and maxMemory as same, cause
     * the notation here seems to be inconsistent while
     * reading and while dumping xml
     */
    /* def->mem.max_balloon = maxMemorySize * 1024; */
4094
    virDomainDefSetMemoryTotal(def, memorySize * 1024);
T
Taowei 已提交
4095 4096

    gVBoxAPI.UIMachine.GetCPUCount(machine, &CPUCount);
4097
    if (virDomainDefSetVcpusMax(def, CPUCount, data->xmlopt) < 0)
4098 4099
        goto cleanup;

4100 4101
    if (virDomainDefSetVcpus(def, CPUCount) < 0)
        goto cleanup;
T
Taowei 已提交
4102 4103 4104

    /* Skip cpumasklen, cpumask, onReboot, onPoweroff, onCrash */

4105
    def->os.type = VIR_DOMAIN_OSTYPE_HVM;
T
Taowei 已提交
4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154
    def->os.arch = virArchFromHost();

    def->os.nBootDevs = 0;
    for (i = 0; (i < VIR_DOMAIN_BOOT_LAST) && (i < maxBootPosition); i++) {
        PRUint32 device = DeviceType_Null;

        gVBoxAPI.UIMachine.GetBootOrder(machine, i+1, &device);

        if (device == DeviceType_Floppy) {
            def->os.bootDevs[i] = VIR_DOMAIN_BOOT_FLOPPY;
            def->os.nBootDevs++;
        } else if (device == DeviceType_DVD) {
            def->os.bootDevs[i] = VIR_DOMAIN_BOOT_CDROM;
            def->os.nBootDevs++;
        } else if (device == DeviceType_HardDisk) {
            def->os.bootDevs[i] = VIR_DOMAIN_BOOT_DISK;
            def->os.nBootDevs++;
        } else if (device == DeviceType_Network) {
            def->os.bootDevs[i] = VIR_DOMAIN_BOOT_NET;
            def->os.nBootDevs++;
        } else if (device == DeviceType_USB) {
            /* Not supported by libvirt yet */
        } else if (device == DeviceType_SharedFolder) {
            /* Not supported by libvirt yet */
            /* Can VirtualBox really boot from a shared folder? */
        }
    }

    gVBoxAPI.UIMachine.GetCPUProperty(machine, CPUPropertyType_PAE, &PAEEnabled);
    if (PAEEnabled)
        def->features[VIR_DOMAIN_FEATURE_PAE] = VIR_TRISTATE_SWITCH_ON;

    gVBoxAPI.UIMachine.GetBIOSSettings(machine, &bios);
    if (bios) {
        gVBoxAPI.UIBIOSSettings.GetACPIEnabled(bios, &ACPIEnabled);
        if (ACPIEnabled)
            def->features[VIR_DOMAIN_FEATURE_ACPI] = VIR_TRISTATE_SWITCH_ON;

        gVBoxAPI.UIBIOSSettings.GetIOAPICEnabled(bios, &IOAPICEnabled);
        if (IOAPICEnabled)
            def->features[VIR_DOMAIN_FEATURE_APIC] = VIR_TRISTATE_SWITCH_ON;

        VBOX_RELEASE(bios);
    }

    /* Currently VirtualBox always uses locatime
     * so locatime is always true here */
    def->clock.offset = VIR_DOMAIN_CLOCK_OFFSET_LOCALTIME;

J
Ján Tomko 已提交
4155 4156
    if (vboxDumpVideo(def, data, machine) < 0)
        goto cleanup;
4157 4158
    if (vboxDumpDisplay(def, data, machine) < 0)
        goto cleanup;
4159 4160
    if (vboxDumpStorageControllers(def, machine) < 0)
        goto cleanup;
4161 4162
    if (vboxDumpDisks(def, data, machine) < 0)
        goto cleanup;
T
Taowei 已提交
4163

4164 4165
    if (vboxDumpSharedFolders(def, data, machine) < 0)
        goto cleanup;
4166 4167
    if (vboxDumpNetworks(def, data, machine, networkAdapterCount) < 0)
        goto cleanup;
T
Taowei 已提交
4168
    vboxDumpAudio(def, data, machine);
4169 4170 4171 4172 4173

    if (vboxDumpSerial(def, data, machine, serialPortCount) < 0)
        goto cleanup;
    if (vboxDumpParallel(def, data, machine, parallelPortCount) < 0)
        goto cleanup;
T
Taowei 已提交
4174 4175 4176 4177

    /* dump USB devices/filters if active */
    vboxHostDeviceGetXMLDesc(data, def, machine);

4178 4179
    ret = virDomainDefFormat(def, data->caps,
                             virDomainDefFormatConvertXMLFlags(flags));
T
Taowei 已提交
4180 4181 4182 4183 4184 4185 4186

 cleanup:
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    virDomainDefFree(def);
    return ret;
}
4187

T
Taowei 已提交
4188 4189
static int vboxConnectListDefinedDomains(virConnectPtr conn,
                                         char ** const names, int maxnames)
4190
{
4191
    vboxDriverPtr data = conn->privateData;
4192
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
4193
    char *machineName = NULL;
4194 4195 4196 4197
    PRUnichar *machineNameUtf16 = NULL;
    PRUint32 state;
    nsresult rc;
    size_t i, j;
T
Taowei Luo 已提交
4198 4199 4200 4201
    int ret = -1;

    if (!data->vboxObj)
        return ret;
4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249

    rc = gVBoxAPI.UArray.vboxArrayGet(&machines, data->vboxObj,
                                      ARRAY_GET_MACHINES);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of Defined Domains, rc=%08x"),
                       (unsigned)rc);
        goto cleanup;
    }

    memset(names, 0, sizeof(names[i]) * maxnames);

    ret = 0;
    for (i = 0, j = 0; (i < machines.count) && (j < maxnames); i++) {
        PRBool isAccessible = PR_FALSE;
        IMachine *machine = machines.items[i];

        if (!machine)
            continue;

        gVBoxAPI.UIMachine.GetAccessible(machine, &isAccessible);
        if (!isAccessible)
            continue;

        gVBoxAPI.UIMachine.GetState(machine, &state);
        if (!gVBoxAPI.machineStateChecker.Inactive(state))
            continue;

        gVBoxAPI.UIMachine.GetName(machine, &machineNameUtf16);
        VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineName);
        if (VIR_STRDUP(names[j], machineName) < 0) {
            VBOX_UTF16_FREE(machineNameUtf16);
            VBOX_UTF8_FREE(machineName);
            for (j = 0; j < maxnames; j++)
                VIR_FREE(names[j]);
            ret = -1;
            goto cleanup;
        }
        VBOX_UTF16_FREE(machineNameUtf16);
        VBOX_UTF8_FREE(machineName);
        j++;
        ret++;
    }

 cleanup:
    gVBoxAPI.UArray.vboxArrayRelease(&machines);
    return ret;
}
4250

T
Taowei 已提交
4251
static int vboxConnectNumOfDefinedDomains(virConnectPtr conn)
4252
{
4253
    vboxDriverPtr data = conn->privateData;
4254 4255 4256 4257
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
    PRUint32 state;
    nsresult rc;
    size_t i;
T
Taowei Luo 已提交
4258 4259 4260 4261
    int ret = -1;

    if (!data->vboxObj)
        return ret;
4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284

    rc = gVBoxAPI.UArray.vboxArrayGet(&machines, data->vboxObj,
                                      ARRAY_GET_MACHINES);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get number of Defined Domains, rc=%08x"),
                       (unsigned)rc);
        goto cleanup;
    }

    ret = 0;
    for (i = 0; i < machines.count; ++i) {
        PRBool isAccessible = PR_FALSE;
        IMachine *machine = machines.items[i];

        if (!machine)
            continue;

        gVBoxAPI.UIMachine.GetAccessible(machine, &isAccessible);
        if (!isAccessible)
            continue;

        gVBoxAPI.UIMachine.GetState(machine, &state);
4285
        if (gVBoxAPI.machineStateChecker.Inactive(state))
4286 4287 4288 4289 4290 4291 4292
            ret++;
    }

 cleanup:
    gVBoxAPI.UArray.vboxArrayRelease(&machines);
    return ret;
}
T
Taowei 已提交
4293 4294 4295 4296 4297

static int vboxDomainAttachDeviceImpl(virDomainPtr dom,
                                      const char *xml,
                                      int mediaChangeOnly ATTRIBUTE_UNUSED)
{
4298
    vboxDriverPtr data = dom->conn->privateData;
4299
    IMachine *machine = NULL;
4300
    vboxIID iid;
T
Taowei 已提交
4301
    PRUint32 state;
4302 4303
    virDomainDefPtr def = NULL;
    virDomainDeviceDefPtr dev = NULL;
T
Taowei 已提交
4304
    nsresult rc;
T
Taowei Luo 已提交
4305 4306 4307 4308
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
4309 4310

    VBOX_IID_INITIALIZE(&iid);
4311
    if (!(def = virDomainDefNew()))
T
Taowei 已提交
4312 4313
        return ret;

4314
    def->os.type = VIR_DOMAIN_OSTYPE_HVM;
T
Taowei 已提交
4315 4316

    dev = virDomainDeviceDefParse(xml, def, data->caps, data->xmlopt,
4317
                                  VIR_DOMAIN_DEF_PARSE_INACTIVE);
T
Taowei 已提交
4318 4319 4320
    if (dev == NULL)
        goto cleanup;

4321
    if (openSessionForMachine(data, dom->uuid, &iid, &machine) < 0)
T
Taowei 已提交
4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343
        goto cleanup;

    if (!machine)
        goto cleanup;

    gVBoxAPI.UIMachine.GetState(machine, &state);

    if (gVBoxAPI.machineStateChecker.Running(state) ||
        gVBoxAPI.machineStateChecker.Paused(state)) {
        rc = gVBoxAPI.UISession.OpenExisting(data, &iid, machine);
    } else {
        rc = gVBoxAPI.UISession.Open(data, &iid, machine);
    }

    if (NS_FAILED(rc))
        goto cleanup;

    rc = gVBoxAPI.UISession.GetMachine(data->vboxSession, &machine);

    if (NS_SUCCEEDED(rc) && machine) {
        /* ret = -VIR_ERR_ARGUMENT_UNSUPPORTED means the current device don't support hotplug. */
        ret = -VIR_ERR_ARGUMENT_UNSUPPORTED;
4344 4345
        if (dev->type == VIR_DOMAIN_DEVICE_FS &&
            dev->data.fs->type == VIR_DOMAIN_FS_TYPE_MOUNT) {
T
Taowei 已提交
4346 4347 4348 4349 4350
            PRUnichar *nameUtf16;
            PRUnichar *hostPathUtf16;
            PRBool writable;

            VBOX_UTF8_TO_UTF16(dev->data.fs->dst, &nameUtf16);
4351
            VBOX_UTF8_TO_UTF16(dev->data.fs->src->path, &hostPathUtf16);
T
Taowei 已提交
4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385
            writable = !dev->data.fs->readonly;

            rc = gVBoxAPI.UIMachine.CreateSharedFolder(machine, nameUtf16, hostPathUtf16,
                                                       writable, PR_FALSE);

            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("could not attach shared folder '%s', rc=%08x"),
                               dev->data.fs->dst, (unsigned)rc);
                ret = -1;
            } else {
                ret = 0;
            }

            VBOX_UTF16_FREE(nameUtf16);
            VBOX_UTF16_FREE(hostPathUtf16);
        }
        gVBoxAPI.UIMachine.SaveSettings(machine);
        VBOX_RELEASE(machine);

        if (ret == -VIR_ERR_ARGUMENT_UNSUPPORTED) {
            virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, _("Unsupported device type %d"), dev->type);
            ret = -1;
        }
    }
    gVBoxAPI.UISession.Close(data->vboxSession);

 cleanup:
    vboxIIDUnalloc(&iid);
    virDomainDefFree(def);
    virDomainDeviceDefFree(dev);
    return ret;
}

T
Taowei 已提交
4386
static int vboxDomainAttachDevice(virDomainPtr dom, const char *xml)
T
Taowei 已提交
4387 4388 4389
{
    return vboxDomainAttachDeviceImpl(dom, xml, 0);
}
4390

T
Taowei 已提交
4391 4392
static int vboxDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags)
4393 4394 4395 4396 4397
{
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE, -1);

    return vboxDomainAttachDeviceImpl(dom, xml, 0);
}
4398

T
Taowei 已提交
4399 4400
static int vboxDomainUpdateDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags)
4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413
{
    virCheckFlags(VIR_DOMAIN_AFFECT_CURRENT |
                  VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot modify the persistent configuration of a domain"));
        return -1;
    }

    return vboxDomainAttachDeviceImpl(dom, xml, 1);
}
T
Taowei 已提交
4414

T
Taowei 已提交
4415
static int vboxDomainDetachDevice(virDomainPtr dom, const char *xml)
T
Taowei 已提交
4416
{
4417
    vboxDriverPtr data = dom->conn->privateData;
4418
    IMachine *machine = NULL;
4419
    vboxIID iid;
T
Taowei 已提交
4420
    PRUint32 state;
4421 4422
    virDomainDefPtr def = NULL;
    virDomainDeviceDefPtr dev = NULL;
T
Taowei 已提交
4423
    nsresult rc;
T
Taowei Luo 已提交
4424 4425 4426 4427
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
4428 4429

    VBOX_IID_INITIALIZE(&iid);
4430
    if (!(def = virDomainDefNew()))
T
Taowei 已提交
4431 4432
        return ret;

4433
    def->os.type = VIR_DOMAIN_OSTYPE_HVM;
T
Taowei 已提交
4434 4435

    dev = virDomainDeviceDefParse(xml, def, data->caps, data->xmlopt,
4436 4437
                                  VIR_DOMAIN_DEF_PARSE_INACTIVE |
                                  VIR_DOMAIN_DEF_PARSE_SKIP_VALIDATE);
T
Taowei 已提交
4438 4439 4440
    if (dev == NULL)
        goto cleanup;

4441
    if (openSessionForMachine(data, dom->uuid, &iid, &machine) < 0)
T
Taowei 已提交
4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462
        goto cleanup;

    if (!machine)
        goto cleanup;

    gVBoxAPI.UIMachine.GetState(machine, &state);

    if (gVBoxAPI.machineStateChecker.Running(state) ||
        gVBoxAPI.machineStateChecker.Paused(state)) {
        rc = gVBoxAPI.UISession.OpenExisting(data, &iid, machine);
    } else {
        rc = gVBoxAPI.UISession.Open(data, &iid, machine);
    }

    if (NS_FAILED(rc))
        goto cleanup;

    rc = gVBoxAPI.UISession.GetMachine(data->vboxSession, &machine);
    if (NS_SUCCEEDED(rc) && machine) {
        /* ret = -VIR_ERR_ARGUMENT_UNSUPPORTED means the current device don't support hotplug. */
        ret = -VIR_ERR_ARGUMENT_UNSUPPORTED;
4463
        if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV) {
T
Taowei 已提交
4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501
            if (dev->data.hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {
                if (dev->data.hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) {
                }
            }
        } else if (dev->type == VIR_DOMAIN_DEVICE_FS &&
                   dev->data.fs->type == VIR_DOMAIN_FS_TYPE_MOUNT) {
            PRUnichar *nameUtf16;

            VBOX_UTF8_TO_UTF16(dev->data.fs->dst, &nameUtf16);

            rc = gVBoxAPI.UIMachine.RemoveSharedFolder(machine, nameUtf16);

            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("could not detach shared folder '%s', rc=%08x"),
                               dev->data.fs->dst, (unsigned)rc);
            } else {
                ret = 0;
            }

            VBOX_UTF16_FREE(nameUtf16);
        }
        gVBoxAPI.UIMachine.SaveSettings(machine);
        VBOX_RELEASE(machine);

        if (ret == -VIR_ERR_ARGUMENT_UNSUPPORTED) {
            virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, _("Unsupported device type %d"), dev->type);
            ret = -1;
        }
    }
    gVBoxAPI.UISession.Close(data->vboxSession);

 cleanup:
    vboxIIDUnalloc(&iid);
    virDomainDefFree(def);
    virDomainDeviceDefFree(dev);
    return ret;
}
4502

T
Taowei 已提交
4503 4504
static int vboxDomainDetachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags)
4505 4506 4507 4508 4509
{
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE, -1);

    return vboxDomainDetachDevice(dom, xml);
}
4510 4511 4512

static int vboxCloseDisksRecursively(virDomainPtr dom, char *location)
{
4513
    vboxDriverPtr data = dom->conn->privateData;
4514 4515 4516 4517 4518 4519
    nsresult rc;
    size_t i = 0;
    PRUnichar *locationUtf = NULL;
    IMedium *medium = NULL;
    IMedium **children = NULL;
    PRUint32 childrenSize = 0;
T
Taowei Luo 已提交
4520 4521 4522 4523
    int ret = -1;

    if (!data->vboxObj)
        return ret;
4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541

    if (!gVBoxAPI.vboxSnapshotRedefine)
        VIR_WARN("This function may not work in current version");

    VBOX_UTF8_TO_UTF16(location, &locationUtf);
    rc = gVBoxAPI.UIVirtualBox.OpenMedium(data->vboxObj,
                                          locationUtf,
                                          DeviceType_HardDisk,
                                          AccessMode_ReadWrite,
                                          &medium);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to open HardDisk, rc=%08x"),
                       (unsigned)rc);
        goto cleanup;
    }
    rc = gVBoxAPI.UIMedium.GetChildren(medium, &childrenSize, &children);
    if (NS_FAILED(rc)) {
4542 4543
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to get disk children"));
4544 4545 4546 4547 4548 4549 4550 4551
        goto cleanup;
    }
    for (i = 0; i < childrenSize; i++) {
        IMedium *childMedium = children[i];
        if (childMedium) {
            PRUnichar *childLocationUtf = NULL;
            char *childLocation = NULL;
            rc = gVBoxAPI.UIMedium.GetLocation(childMedium, &childLocationUtf);
4552 4553 4554 4555 4556
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to get childMedium location"));
                goto cleanup;
            }
4557 4558 4559
            VBOX_UTF16_TO_UTF8(childLocationUtf, &childLocation);
            VBOX_UTF16_FREE(childLocationUtf);
            if (vboxCloseDisksRecursively(dom, childLocation) < 0) {
4560 4561
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to close disk children"));
4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613
                goto cleanup;
            }
            VIR_FREE(childLocation);
        }
    }
    rc = gVBoxAPI.UIMedium.Close(medium);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to close HardDisk, rc=%08x"),
                       (unsigned)rc);
        goto cleanup;
    }

    ret = 0;
 cleanup:
    VBOX_UTF16_FREE(locationUtf);
    return ret;
}

static int
vboxSnapshotRedefine(virDomainPtr dom,
                     virDomainSnapshotDefPtr def,
                     bool isCurrent)
{
    /*
     * If your snapshot has a parent,
     * it will only be redefined if you have already
     * redefined the parent.
     *
     * The general algorithm of this function is below :
     * First of all, we are going to create our vboxSnapshotXmlMachinePtr struct from
     * the machine settings path.
     * Then, if the machine current snapshot xml file is saved in the machine location,
     * it means that this snapshot was previously modified by us and has fake disks.
     * Fake disks are added when the flag VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT was not set
     * yet, in order to not corrupt read-only disks. The first thing to do is to remove those
     * disks and restore the read-write disks, if any, in the vboxSnapshotXmlMachinePtr struct.
     * We also delete the current snapshot xml file.
     *
     * After that, we are going to register the snapshot read-only disks that we want to redefine,
     * if they are not in the media registry struct.
     *
     * The next step is to unregister the machine and close all disks.
     *
     * Then, we check if the flag VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE has already been set.
     * If this flag was set, we just add read-write disks to the media registry
     * struct. Otherwise, we save the snapshot xml file into the machine location in order
     * to recover the read-write disks during the next redefine and we create differential disks
     * from the snapshot read-only disks and add them to the media registry struct.
     *
     * Finally, we register the machine with the new virtualbox description file.
     */
4614
    vboxDriverPtr data = dom->conn->privateData;
4615
    vboxIID domiid;
4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629
    IMachine *machine = NULL;
    nsresult rc;
    PRUnichar *settingsFilePath = NULL;
    char *settingsFilePath_Utf8 = NULL;
    virVBoxSnapshotConfMachinePtr snapshotMachineDesc = NULL;
    char *currentSnapshotXmlFilePath = NULL;
    PRUnichar *machineNameUtf16 = NULL;
    char *machineName = NULL;
    char **realReadWriteDisksPath = NULL;
    int realReadWriteDisksPathSize = 0;
    char **realReadOnlyDisksPath = NULL;
    int realReadOnlyDisksPathSize = 0;
    virVBoxSnapshotConfSnapshotPtr newSnapshotPtr = NULL;
    unsigned char snapshotUuid[VIR_UUID_BUFLEN];
J
John Ferlan 已提交
4630 4631
    virVBoxSnapshotConfHardDiskPtr *hardDiskToOpen = NULL;
    size_t hardDiskToOpenSize = 0;
J
John Ferlan 已提交
4632
    virVBoxSnapshotConfHardDiskPtr newHardDisk = NULL;
4633 4634
    char **searchResultTab = NULL;
    ssize_t resultSize = 0;
4635 4636 4637 4638 4639 4640 4641 4642
    int it = 0;
    int jt = 0;
    PRUint32 aMediaSize = 0;
    IMedium **aMedia = NULL;
    char *machineLocationPath = NULL;
    char *nameTmpUse = NULL;
    bool snapshotFileExists = false;
    bool needToChangeStorageController = false;
T
Taowei Luo 已提交
4643 4644 4645 4646
    int ret = -1;

    if (!data->vboxObj)
        return ret;
4647 4648 4649 4650

    if (!gVBoxAPI.vboxSnapshotRedefine)
        VIR_WARN("This function may not work in current version");

4651
    if (openSessionForMachine(data, dom->uuid, &domiid, &machine) < 0)
4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726
        goto cleanup;

    rc = gVBoxAPI.UIMachine.SaveSettings(machine);
    /*It may failed when the machine is not mutable.*/
    rc = gVBoxAPI.UIMachine.GetSettingsFilePath(machine, &settingsFilePath);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot get settings file path"));
        goto cleanup;
    }
    VBOX_UTF16_TO_UTF8(settingsFilePath, &settingsFilePath_Utf8);

    /*Getting the machine name to retrieve the machine location path.*/
    rc = gVBoxAPI.UIMachine.GetName(machine, &machineNameUtf16);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot get machine name"));
        goto cleanup;
    }
    VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineName);

    if (virAsprintf(&nameTmpUse, "%s.vbox", machineName) < 0)
        goto cleanup;
    machineLocationPath = virStringReplace(settingsFilePath_Utf8, nameTmpUse, "");
    if (machineLocationPath == NULL) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to get the machine location path"));
        goto cleanup;
    }

    /*We create the xml struct with the settings file path.*/
    snapshotMachineDesc = virVBoxSnapshotConfLoadVboxFile(settingsFilePath_Utf8, machineLocationPath);
    if (snapshotMachineDesc == NULL) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot create a vboxSnapshotXmlPtr"));
        goto cleanup;
    }
    if (snapshotMachineDesc->currentSnapshot != NULL) {
        if (virAsprintf(&currentSnapshotXmlFilePath, "%s%s.xml", machineLocationPath,
                       snapshotMachineDesc->currentSnapshot) < 0)
            goto cleanup;
        snapshotFileExists = virFileExists(currentSnapshotXmlFilePath);
    }

    if (snapshotFileExists) {
        /*
         * We have created fake disks, so we have to remove them and replace them with
         * the read-write disks if there are any. The fake disks will be closed during
         * the machine unregistration.
         */
        if (virVBoxSnapshotConfRemoveFakeDisks(snapshotMachineDesc) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Unable to remove Fake Disks"));
            goto cleanup;
        }
        realReadWriteDisksPathSize = virVBoxSnapshotConfGetRWDisksPathsFromLibvirtXML(currentSnapshotXmlFilePath,
                                                             &realReadWriteDisksPath);
        realReadOnlyDisksPathSize = virVBoxSnapshotConfGetRODisksPathsFromLibvirtXML(currentSnapshotXmlFilePath,
                                                                         &realReadOnlyDisksPath);
        /*The read-only disk number is necessarily greater or equal to the
         *read-write disk number*/
        if (realReadOnlyDisksPathSize < realReadWriteDisksPathSize) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("The read only disk number must be greater or equal to the "
                           " read write disk number"));
            goto cleanup;
        }
        for (it = 0; it < realReadWriteDisksPathSize; it++) {
            virVBoxSnapshotConfHardDiskPtr readWriteDisk = NULL;
            PRUnichar *locationUtf = NULL;
            IMedium *readWriteMedium = NULL;
            char *uuid = NULL;
            PRUnichar *formatUtf = NULL;
            char *format = NULL;
            const char *parentUuid = NULL;
4727
            vboxIID iid;
4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772

            VBOX_IID_INITIALIZE(&iid);
            VBOX_UTF8_TO_UTF16(realReadWriteDisksPath[it], &locationUtf);
            rc = gVBoxAPI.UIVirtualBox.OpenMedium(data->vboxObj,
                                                  locationUtf,
                                                  DeviceType_HardDisk,
                                                  AccessMode_ReadWrite,
                                                  &readWriteMedium);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to open HardDisk, rc=%08x"),
                               (unsigned)rc);
                VBOX_UTF16_FREE(locationUtf);
                goto cleanup;
            }
            VBOX_UTF16_FREE(locationUtf);

            rc = gVBoxAPI.UIMedium.GetId(readWriteMedium, &iid);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to get the read write medium id"));
                goto cleanup;
            }
            gVBoxAPI.UIID.vboxIIDToUtf8(data, &iid, &uuid);
            vboxIIDUnalloc(&iid);

            rc = gVBoxAPI.UIMedium.GetFormat(readWriteMedium, &formatUtf);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to get the read write medium format"));
                goto cleanup;
            }
            VBOX_UTF16_TO_UTF8(formatUtf, &format);
            VBOX_UTF16_FREE(formatUtf);

            if (VIR_ALLOC(readWriteDisk) < 0) {
                VIR_FREE(formatUtf);
                goto cleanup;
            }

            readWriteDisk->format = format;
            readWriteDisk->uuid = uuid;
            readWriteDisk->location = realReadWriteDisksPath[it];
            /*
             * We get the current snapshot's read-only disk uuid in order to add the
4773
             * read-write disk to the media registry as its child. The read-only disk
4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813
             * is already in the media registry because it is the fake disk's parent.
             */
            parentUuid = virVBoxSnapshotConfHardDiskUuidByLocation(snapshotMachineDesc,
                                                                   realReadOnlyDisksPath[it]);
            if (parentUuid == NULL) {
                VIR_FREE(readWriteDisk);
                goto cleanup;
            }

            if (virVBoxSnapshotConfAddHardDiskToMediaRegistry(readWriteDisk,
                                           snapshotMachineDesc->mediaRegistry,
                                           parentUuid) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to add hard disk to media Registry"));
                VIR_FREE(readWriteDisk);
                goto cleanup;
            }
            rc = gVBoxAPI.UIMedium.Close(readWriteMedium);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to close HardDisk, rc=%08x"),
                               (unsigned)rc);
                goto cleanup;
            }
        }
        /*
         * Now we have done this swap, we remove the snapshot xml file from the
         * current machine location.
         */
        if (unlink(currentSnapshotXmlFilePath) < 0) {
            virReportSystemError(errno,
                                 _("Unable to delete file %s"), currentSnapshotXmlFilePath);
            goto cleanup;
        }
    }
    /*
     * Before unregistering the machine, while all disks are still open, ensure that all
     * read-only disks are in the redefined snapshot's media registry (the disks need to
     * be open to query their uuid).
     */
4814
    for (it = 0; it < def->parent.dom->ndisks; it++) {
4815 4816 4817 4818 4819 4820 4821 4822
        int diskInMediaRegistry = 0;
        IMedium *readOnlyMedium = NULL;
        PRUnichar *locationUtf = NULL;
        char *uuid = NULL;
        PRUnichar *formatUtf = NULL;
        char *format = NULL;
        char *parentUuid = NULL;
        virVBoxSnapshotConfHardDiskPtr readOnlyDisk = NULL;
4823
        vboxIID iid, parentiid;
4824 4825 4826 4827

        VBOX_IID_INITIALIZE(&iid);
        VBOX_IID_INITIALIZE(&parentiid);
        diskInMediaRegistry = virVBoxSnapshotConfDiskIsInMediaRegistry(snapshotMachineDesc,
4828
                                                        def->parent.dom->disks[it]->src->path);
4829 4830 4831 4832 4833 4834 4835 4836 4837
        if (diskInMediaRegistry == -1) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Unable to know if disk is in media registry"));
            goto cleanup;
        }
        if (diskInMediaRegistry == 1) /*Nothing to do.*/
            continue;
        /*The read only disk is not in the media registry*/

4838
        VBOX_UTF8_TO_UTF16(def->parent.dom->disks[it]->src->path, &locationUtf);
4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910
        rc = gVBoxAPI.UIVirtualBox.OpenMedium(data->vboxObj,
                                              locationUtf,
                                              DeviceType_HardDisk,
                                              AccessMode_ReadWrite,
                                              &readOnlyMedium);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to open HardDisk, rc=%08x"),
                           (unsigned)rc);
            VBOX_UTF16_FREE(locationUtf);
            goto cleanup;
        }
        VBOX_UTF16_FREE(locationUtf);

        rc = gVBoxAPI.UIMedium.GetId(readOnlyMedium, &iid);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Unable to get hard disk id"));
            goto cleanup;
        }
        gVBoxAPI.UIID.vboxIIDToUtf8(data, &iid, &uuid);
        vboxIIDUnalloc(&iid);

        rc = gVBoxAPI.UIMedium.GetFormat(readOnlyMedium, &formatUtf);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Unable to get hard disk format"));
            VIR_FREE(uuid);
            goto cleanup;
        }
        VBOX_UTF16_TO_UTF8(formatUtf, &format);
        VBOX_UTF16_FREE(formatUtf);

        /*This disk is already in the media registry*/
        IMedium *parentReadOnlyMedium = NULL;
        rc = gVBoxAPI.UIMedium.GetParent(readOnlyMedium, &parentReadOnlyMedium);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Unable to get parent hard disk"));
            VIR_FREE(uuid);
            goto cleanup;
        }

        rc = gVBoxAPI.UIMedium.GetId(parentReadOnlyMedium, &parentiid);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to get hard disk id, rc=%08x"),
                           (unsigned)rc);
            VIR_FREE(uuid);
            goto cleanup;
        }
        gVBoxAPI.UIID.vboxIIDToUtf8(data, &parentiid, &parentUuid);
        vboxIIDUnalloc(&parentiid);

        rc = gVBoxAPI.UIMedium.Close(readOnlyMedium);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to close HardDisk, rc=%08x"),
                           (unsigned)rc);
            VIR_FREE(uuid);
            VIR_FREE(parentUuid);
            goto cleanup;
        }

        if (VIR_ALLOC(readOnlyDisk) < 0) {
            VIR_FREE(uuid);
            VIR_FREE(parentUuid);
            goto cleanup;
        }

        readOnlyDisk->format = format;
        readOnlyDisk->uuid = uuid;
4911
        if (VIR_STRDUP(readOnlyDisk->location, def->parent.dom->disks[it]->src->path) < 0) {
4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987
            VIR_FREE(readOnlyDisk);
            goto cleanup;
        }

        if (virVBoxSnapshotConfAddHardDiskToMediaRegistry(readOnlyDisk, snapshotMachineDesc->mediaRegistry,
                                       parentUuid) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Unable to add hard disk to media registry"));
            VIR_FREE(readOnlyDisk);
            goto cleanup;
        }
    }

    /*Now, we can unregister the machine*/
    rc = gVBoxAPI.UIMachine.Unregister(machine,
                                       CleanupMode_DetachAllReturnHardDisksOnly,
                                       &aMediaSize,
                                       &aMedia);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to unregister machine, rc=%08x"),
                       (unsigned)rc);
        goto cleanup;
    }
    VBOX_RELEASE(machine);

    /*
     * Unregister the machine, and then close all disks returned by the unregister method.
     * Some close operations will fail because some disks that need to be closed will not
     * be returned by virtualbox. We will close them just after. We have to use this
     * solution because it is the only way to delete fake disks.
     */
    for (it = 0; it < aMediaSize; it++) {
        IMedium *medium = aMedia[it];
        if (medium) {
            PRUnichar *locationUtf16 = NULL;
            char *locationUtf8 = NULL;
            rc = gVBoxAPI.UIMedium.GetLocation(medium, &locationUtf16);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to get medium location"));
                goto cleanup;
            }
            VBOX_UTF16_TO_UTF8(locationUtf16, &locationUtf8);
            VBOX_UTF16_FREE(locationUtf16);
            if (strstr(locationUtf8, "fake") != NULL) {
                /*we delete the fake disk because we don't need it anymore*/
                IProgress *progress = NULL;
                resultCodeUnion resultCode;
                rc = gVBoxAPI.UIMedium.DeleteStorage(medium, &progress);
                if (NS_FAILED(rc)) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unable to delete medium, rc=%08x"),
                                   (unsigned)rc);
                    VIR_FREE(locationUtf8);
                    goto cleanup;
                }
                gVBoxAPI.UIProgress.WaitForCompletion(progress, -1);
                gVBoxAPI.UIProgress.GetResultCode(progress, &resultCode);
                if (RC_FAILED(resultCode)) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Error while closing medium, rc=%08x"),
                                   resultCode.uResultCode);
                    VIR_FREE(locationUtf8);
                    goto cleanup;
                }
                VBOX_RELEASE(progress);
            } else {
                /*
                 * This a comment from vboxmanage code in the handleUnregisterVM
                 * function in VBoxManageMisc.cpp :
                 * Note that the IMachine::Unregister method will return the medium
                 * reference in a sane order, which means that closing will normally
                 * succeed, unless there is still another machine which uses the
                 * medium. No harm done if we ignore the error.
                 */
4988
                ignore_value(gVBoxAPI.UIMedium.Close(medium));
4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015
            }
            VBOX_UTF8_FREE(locationUtf8);
        }
    }
    /*Close all disks that failed to close normally.*/
    for (it = 0; it < snapshotMachineDesc->mediaRegistry->ndisks; it++) {
        if (vboxCloseDisksRecursively(dom, snapshotMachineDesc->mediaRegistry->disks[it]->location) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Unable to close recursively all disks"));
            goto cleanup;
        }
    }
    /*Here, all disks are closed or deleted*/

    /*We are now going to create and fill the Snapshot xml struct*/
    if (VIR_ALLOC(newSnapshotPtr) < 0)
        goto cleanup;

    if (virUUIDGenerate(snapshotUuid) < 0)
        goto cleanup;

    char uuidtmp[VIR_UUID_STRING_BUFLEN];
    virUUIDFormat(snapshotUuid, uuidtmp);
    if (VIR_STRDUP(newSnapshotPtr->uuid, uuidtmp) < 0)
        goto cleanup;

    VIR_DEBUG("New snapshot UUID: %s", newSnapshotPtr->uuid);
5016
    if (VIR_STRDUP(newSnapshotPtr->name, def->parent.name) < 0)
5017 5018
        goto cleanup;

5019
    newSnapshotPtr->timeStamp = virTimeStringThen(def->parent.creationTime * 1000);
5020

5021
    if (VIR_STRDUP(newSnapshotPtr->description, def->parent.description) < 0)
5022 5023 5024 5025 5026 5027 5028 5029 5030
        goto cleanup;

    if (VIR_STRDUP(newSnapshotPtr->hardware, snapshotMachineDesc->hardware) < 0)
        goto cleanup;

    if (VIR_STRDUP(newSnapshotPtr->storageController, snapshotMachineDesc->storageController) < 0)
        goto cleanup;

    /*We get the parent disk uuid from the parent disk location to correctly fill the storage controller.*/
5031
    for (it = 0; it < def->parent.dom->ndisks; it++) {
5032 5033 5034 5035
        char *location = NULL;
        const char *uuidReplacing = NULL;
        char *tmp = NULL;

5036
        location = def->parent.dom->disks[it]->src->path;
5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053
        if (!location)
            goto cleanup;
        /*Replacing the uuid*/
        uuidReplacing = virVBoxSnapshotConfHardDiskUuidByLocation(snapshotMachineDesc, location);
        if (uuidReplacing == NULL)
            goto cleanup;

        resultSize = virStringSearch(newSnapshotPtr->storageController,
                                     VBOX_UUID_REGEX,
                                     it + 1,
                                     &searchResultTab);
        if (resultSize != it + 1)
            goto cleanup;

        tmp = virStringReplace(newSnapshotPtr->storageController,
                               searchResultTab[it],
                               uuidReplacing);
5054
        virStringListFree(searchResultTab);
5055
        searchResultTab = NULL;
5056 5057 5058 5059 5060 5061 5062 5063
        VIR_FREE(newSnapshotPtr->storageController);
        if (!tmp)
            goto cleanup;
        if (VIR_STRDUP(newSnapshotPtr->storageController, tmp) < 0)
            goto cleanup;

        VIR_FREE(tmp);
    }
5064
    if (virVBoxSnapshotConfAddSnapshotToXmlMachine(newSnapshotPtr, snapshotMachineDesc, def->parent.parent_name) < 0) {
5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to add the snapshot to the machine description"));
        goto cleanup;
    }
    /*
     * We change the current snapshot only if there is no current snapshot or if the
     * snapshotFile exists, otherwise, it means that the correct current snapshot is
     * already set.
     */

    if (snapshotMachineDesc->currentSnapshot == NULL || snapshotFileExists) {
        snapshotMachineDesc->currentSnapshot = newSnapshotPtr->uuid;
        needToChangeStorageController = true;
    }

    /*
     * Open the snapshot's read-write disk's full ancestry to allow opening the
     * read-write disk itself.
     */
5084
    for (it = 0; it < def->parent.dom->ndisks; it++) {
5085 5086
        char *location = NULL;

5087
        location = def->parent.dom->disks[it]->src->path;
5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126
        if (!location)
            goto cleanup;

        hardDiskToOpenSize = virVBoxSnapshotConfDiskListToOpen(snapshotMachineDesc,
                                                   &hardDiskToOpen, location);
        for (jt = hardDiskToOpenSize -1; jt >= 0; jt--) {
            IMedium *medium = NULL;
            PRUnichar *locationUtf16 = NULL;
            VBOX_UTF8_TO_UTF16(hardDiskToOpen[jt]->location, &locationUtf16);

            rc = gVBoxAPI.UIVirtualBox.OpenMedium(data->vboxObj,
                                                  locationUtf16,
                                                  DeviceType_HardDisk,
                                                  AccessMode_ReadWrite,
                                                  &medium);
            VBOX_UTF16_FREE(locationUtf16);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to open HardDisk, rc=%08x"),
                               (unsigned)rc);
                goto cleanup;
            }
        }
    }
    if (isCurrent || !needToChangeStorageController) {
        /* We don't create a differential hard disk because either the current snapshot
         * has already been defined or the snapshot to redefine is the current snapshot.
         * If the snapshot to redefine is the current snapshot, we add read-write disks in
         * the machine storage controllers.
         */
        for (it = 0; it < def->ndisks; it++) {
            IMedium *medium = NULL;
            PRUnichar *locationUtf16 = NULL;
            virVBoxSnapshotConfHardDiskPtr disk = NULL;
            PRUnichar *formatUtf16 = NULL;
            char *format = NULL;
            char *uuid = NULL;
            IMedium *parentDisk = NULL;
            char *parentUuid = NULL;
5127
            vboxIID iid, parentiid;
5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172

            VBOX_IID_INITIALIZE(&iid);
            VBOX_IID_INITIALIZE(&parentiid);
            VBOX_UTF8_TO_UTF16(def->disks[it].src->path, &locationUtf16);
            rc = gVBoxAPI.UIVirtualBox.OpenMedium(data->vboxObj,
                                                 locationUtf16,
                                                 DeviceType_HardDisk,
                                                 AccessMode_ReadWrite,
                                                 &medium);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to open HardDisk, rc=%08x"),
                               (unsigned)rc);
                goto cleanup;
            }
            VBOX_UTF16_FREE(locationUtf16);

            if (VIR_ALLOC(disk) < 0)
                goto cleanup;

            rc = gVBoxAPI.UIMedium.GetFormat(medium, &formatUtf16);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to get disk format"));
                VIR_FREE(disk);
                goto cleanup;
            }

            VBOX_UTF16_TO_UTF8(formatUtf16, &format);
            disk->format = format;
            VBOX_UTF16_FREE(formatUtf16);

            if (VIR_STRDUP(disk->location, def->disks[it].src->path) < 0) {
                VIR_FREE(disk);
                goto cleanup;
            }

            rc = gVBoxAPI.UIMedium.GetId(medium, &iid);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to get disk uuid"));
                VIR_FREE(disk);
                goto cleanup;
            }
            gVBoxAPI.UIID.vboxIIDToUtf8(data, &iid, &uuid);
5173
            disk->uuid = uuid;
5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230
            vboxIIDUnalloc(&iid);

            rc = gVBoxAPI.UIMedium.GetParent(medium, &parentDisk);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to get disk parent"));
                VIR_FREE(disk);
                goto cleanup;
            }

            gVBoxAPI.UIMedium.GetId(parentDisk, &parentiid);
            gVBoxAPI.UIID.vboxIIDToUtf8(data, &parentiid, &parentUuid);
            vboxIIDUnalloc(&parentiid);
            if (virVBoxSnapshotConfAddHardDiskToMediaRegistry(disk,
                                           snapshotMachineDesc->mediaRegistry,
                                           parentUuid) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to add hard disk to the media registry"));
                VIR_FREE(disk);
                goto cleanup;
            }

            if (needToChangeStorageController) {
                /*We need to append this disk in the storage controller*/
                char *tmp = NULL;
                resultSize = virStringSearch(snapshotMachineDesc->storageController,
                                             VBOX_UUID_REGEX,
                                             it + 1,
                                             &searchResultTab);
                if (resultSize != it + 1) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unable to find UUID %s"), searchResultTab[it]);
                    goto cleanup;
                }

                tmp = virStringReplace(snapshotMachineDesc->storageController,
                                       searchResultTab[it],
                                       disk->uuid);
                VIR_FREE(snapshotMachineDesc->storageController);
                if (!tmp)
                    goto cleanup;
                if (VIR_STRDUP(snapshotMachineDesc->storageController, tmp) < 0)
                    goto cleanup;

                VIR_FREE(tmp);
            }
            /*Close disk*/
            rc = gVBoxAPI.UIMedium.Close(medium);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to close HardDisk, rc=%08x"),
                               (unsigned)rc);
                goto cleanup;
            }
        }
    } else {
        /*Create a "fake" disk to avoid corrupting children snapshot disks.*/
5231
        for (it = 0; it < def->parent.dom->ndisks; it++) {
5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242
            IMedium *medium = NULL;
            PRUnichar *locationUtf16 = NULL;
            char *parentUuid = NULL;
            IMedium *newMedium = NULL;
            PRUnichar *formatUtf16 = NULL;
            PRUnichar *newLocation = NULL;
            char *newLocationUtf8 = NULL;
            resultCodeUnion resultCode;
            char *uuid = NULL;
            char *format = NULL;
            char *tmp = NULL;
5243
            vboxIID iid, parentiid;
5244 5245 5246

            VBOX_IID_INITIALIZE(&iid);
            VBOX_IID_INITIALIZE(&parentiid);
5247
            VBOX_UTF8_TO_UTF16(def->parent.dom->disks[it]->src->path, &locationUtf16);
5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275
            rc = gVBoxAPI.UIVirtualBox.OpenMedium(data->vboxObj,
                                                  locationUtf16,
                                                  DeviceType_HardDisk,
                                                  AccessMode_ReadWrite,
                                                  &medium);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to open HardDisk, rc=%08x"),
                               (unsigned)rc);
                VBOX_UTF16_FREE(locationUtf16);
                goto cleanup;
            }
            VBOX_UTF16_FREE(locationUtf16);

            rc = gVBoxAPI.UIMedium.GetId(medium, &parentiid);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to get hardDisk Id, rc=%08x"),
                               (unsigned)rc);
                goto cleanup;
            }
            gVBoxAPI.UIID.vboxIIDToUtf8(data, &parentiid, &parentUuid);
            vboxIIDUnalloc(&parentiid);
            VBOX_UTF8_TO_UTF16("VDI", &formatUtf16);

            if (virAsprintf(&newLocationUtf8, "%sfakedisk-%d.vdi", machineLocationPath, it) < 0)
                goto cleanup;
            VBOX_UTF8_TO_UTF16(newLocationUtf8, &newLocation);
5276 5277 5278 5279
            rc = gVBoxAPI.UIVirtualBox.CreateHardDisk(data->vboxObj,
                                                      formatUtf16,
                                                      newLocation,
                                                      &newMedium);
5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290
            VBOX_UTF16_FREE(newLocation);
            VBOX_UTF16_FREE(formatUtf16);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to create HardDisk, rc=%08x"),
                               (unsigned)rc);
                goto cleanup;
            }

            IProgress *progress = NULL;
            PRUint32 tab[1];
5291
            tab[0] = MediumVariant_Diff;
5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303
            gVBoxAPI.UIMedium.CreateDiffStorage(medium, newMedium, 1, tab, &progress);

            gVBoxAPI.UIProgress.WaitForCompletion(progress, -1);
            gVBoxAPI.UIProgress.GetResultCode(progress, &resultCode);
            if (RC_FAILED(resultCode)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Error while creating diff storage, rc=%08x"),
                               resultCode.uResultCode);
                goto cleanup;
            }
            VBOX_RELEASE(progress);
            /*
J
John Ferlan 已提交
5304 5305
             * The differential newHardDisk is created, we add it to the
             * media registry and the machine storage controllers.
5306 5307
             */

J
John Ferlan 已提交
5308
            if (VIR_ALLOC(newHardDisk) < 0)
5309 5310 5311 5312 5313 5314 5315 5316 5317 5318
                goto cleanup;

            rc = gVBoxAPI.UIMedium.GetId(newMedium, &iid);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to get medium uuid, rc=%08x"),
                               (unsigned)rc);
                goto cleanup;
            }
            gVBoxAPI.UIID.vboxIIDToUtf8(data, &iid, &uuid);
J
John Ferlan 已提交
5319
            newHardDisk->uuid = uuid;
5320 5321
            vboxIIDUnalloc(&iid);

J
John Ferlan 已提交
5322
            if (VIR_STRDUP(newHardDisk->location, newLocationUtf8) < 0)
5323 5324 5325 5326
                goto cleanup;

            rc = gVBoxAPI.UIMedium.GetFormat(newMedium, &formatUtf16);
            VBOX_UTF16_TO_UTF8(formatUtf16, &format);
J
John Ferlan 已提交
5327
            newHardDisk->format = format;
5328 5329
            VBOX_UTF16_FREE(formatUtf16);

J
John Ferlan 已提交
5330
            if (virVBoxSnapshotConfAddHardDiskToMediaRegistry(newHardDisk,
5331 5332 5333 5334 5335 5336
                                           snapshotMachineDesc->mediaRegistry,
                                           parentUuid) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to add hard disk to the media registry"));
                goto cleanup;
            }
J
John Ferlan 已提交
5337
            newHardDisk = NULL;  /* Consumed by above */
5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351
            /*Adding the fake disk to the machine storage controllers*/

            resultSize = virStringSearch(snapshotMachineDesc->storageController,
                                         VBOX_UUID_REGEX,
                                         it + 1,
                                         &searchResultTab);
            if (resultSize != it + 1) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to find UUID %s"), searchResultTab[it]);
                goto cleanup;
            }

            tmp = virStringReplace(snapshotMachineDesc->storageController,
                                   searchResultTab[it],
J
John Ferlan 已提交
5352
                                   uuid);
5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375
            VIR_FREE(snapshotMachineDesc->storageController);
            if (!tmp)
                goto cleanup;
            if (VIR_STRDUP(snapshotMachineDesc->storageController, tmp) < 0)
                goto cleanup;

            VIR_FREE(tmp);
            /*Closing the "fake" disk*/
            rc = gVBoxAPI.UIMedium.Close(newMedium);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to close the new medium, rc=%08x"),
                               (unsigned)rc);
                goto cleanup;
            }
        }
        /*
         * We save the snapshot xml file to retrieve the real read-write disk during the
         * next define. This file is saved as "'machineLocation'/snapshot-'uuid'.xml"
         */
        VIR_FREE(currentSnapshotXmlFilePath);
        if (virAsprintf(&currentSnapshotXmlFilePath, "%s%s.xml", machineLocationPath, snapshotMachineDesc->currentSnapshot) < 0)
            goto cleanup;
5376 5377 5378 5379
        char *snapshotContent = virDomainSnapshotDefFormat(NULL, def,
                                                           data->caps,
                                                           data->xmlopt,
                                                           VIR_DOMAIN_SNAPSHOT_FORMAT_SECURE);
5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395
        if (snapshotContent == NULL) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Unable to get snapshot content"));
            goto cleanup;
        }
        if (virFileWriteStr(currentSnapshotXmlFilePath, snapshotContent, 0644) < 0) {
            virReportSystemError(errno, "%s",
                                 _("Unable to save new snapshot xml file"));
            goto cleanup;
        }
        VIR_FREE(snapshotContent);
    }
    /*
     * All the snapshot structure manipulation is done, we close the disks we have
     * previously opened.
     */
5396 5397
    for (it = 0; it < def->parent.dom->ndisks; it++) {
        char *location = def->parent.dom->disks[it]->src->path;
5398 5399 5400
        if (!location)
            goto cleanup;

J
John Ferlan 已提交
5401
        hardDiskToOpenSize = virVBoxSnapshotConfDiskListToOpen(snapshotMachineDesc,
5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461
                                                   &hardDiskToOpen, location);
        for (jt = 0; jt < hardDiskToOpenSize; jt++) {
            IMedium *medium = NULL;
            PRUnichar *locationUtf16 = NULL;
            VBOX_UTF8_TO_UTF16(hardDiskToOpen[jt]->location, &locationUtf16);
            rc = gVBoxAPI.UIVirtualBox.OpenMedium(data->vboxObj,
                                                  locationUtf16,
                                                  DeviceType_HardDisk,
                                                  AccessMode_ReadWrite,
                                                  &medium);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to open HardDisk, rc=%08x"),
                               (unsigned)rc);
                goto cleanup;
            }
            rc = gVBoxAPI.UIMedium.Close(medium);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to close HardDisk, rc=%08x"),
                               (unsigned)rc);
                goto cleanup;
            }
            VBOX_UTF16_FREE(locationUtf16);
        }
    }

    /*Now, we rewrite the 'machineName'.vbox file to redefine the machine.*/
    if (virVBoxSnapshotConfSaveVboxFile(snapshotMachineDesc, settingsFilePath_Utf8) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to serialize the machine description"));
        goto cleanup;
    }
    rc = gVBoxAPI.UIVirtualBox.OpenMachine(data->vboxObj,
                                           settingsFilePath,
                                           &machine);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to open Machine, rc=%08x"),
                       (unsigned)rc);
        goto cleanup;
    }

    rc = gVBoxAPI.UIVirtualBox.RegisterMachine(data->vboxObj, machine);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to register Machine, rc=%08x"),
                       (unsigned)rc);
        goto cleanup;
    }

    ret = 0;
 cleanup:
    VBOX_RELEASE(machine);
    VBOX_UTF16_FREE(settingsFilePath);
    VBOX_UTF8_FREE(settingsFilePath_Utf8);
    VIR_FREE(snapshotMachineDesc);
    VIR_FREE(currentSnapshotXmlFilePath);
    VBOX_UTF16_FREE(machineNameUtf16);
    VBOX_UTF8_FREE(machineName);
5462 5463 5464
    virStringListFree(realReadOnlyDisksPath);
    virStringListFree(realReadWriteDisksPath);
    virStringListFree(searchResultTab);
J
John Ferlan 已提交
5465
    virVboxSnapshotConfHardDiskFree(newHardDisk);
J
John Ferlan 已提交
5466
    VIR_FREE(hardDiskToOpen);
5467 5468 5469 5470 5471 5472
    VIR_FREE(newSnapshotPtr);
    VIR_FREE(machineLocationPath);
    VIR_FREE(nameTmpUse);
    return ret;
}

T
Taowei 已提交
5473
static virDomainSnapshotPtr
5474 5475 5476 5477
vboxDomainSnapshotCreateXML(virDomainPtr dom,
                            const char *xmlDesc,
                            unsigned int flags)
{
5478
    vboxDriverPtr data = dom->conn->privateData;
5479
    vboxIID domiid;
5480 5481 5482 5483 5484 5485 5486 5487 5488
    IMachine *machine = NULL;
    IConsole *console = NULL;
    IProgress *progress = NULL;
    ISnapshot *snapshot = NULL;
    PRUnichar *name = NULL;
    PRUnichar *description = NULL;
    PRUint32 state;
    nsresult rc;
    resultCodeUnion result;
T
Taowei Luo 已提交
5489
    virDomainSnapshotPtr ret = NULL;
5490 5491
    unsigned int parse_flags = (VIR_DOMAIN_SNAPSHOT_PARSE_DISKS |
                                VIR_DOMAIN_SNAPSHOT_PARSE_REDEFINE);
5492
    VIR_AUTOUNREF(virDomainSnapshotDefPtr) def = NULL;
T
Taowei Luo 已提交
5493 5494 5495

    if (!data->vboxObj)
        return ret;
5496 5497 5498 5499 5500

    VBOX_IID_INITIALIZE(&domiid);
    /* VBox has no snapshot metadata, so this flag is trivial.  */
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA |
                  VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE |
5501 5502 5503 5504 5505
                  VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT |
                  VIR_DOMAIN_SNAPSHOT_CREATE_VALIDATE, NULL);

    if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_VALIDATE)
        parse_flags |= VIR_DOMAIN_SNAPSHOT_PARSE_VALIDATE;
5506 5507

    if (!(def = virDomainSnapshotDefParseString(xmlDesc, data->caps,
5508
                                                data->xmlopt, NULL,
5509
                                                parse_flags)))
5510 5511 5512
        goto cleanup;


5513
    if (openSessionForMachine(data, dom->uuid, &domiid, &machine) < 0)
5514 5515 5516 5517 5518 5519 5520
        goto cleanup;

    if (gVBoxAPI.vboxSnapshotRedefine) {
        PRBool isCurrent = flags & VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT;
        if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE) {
            if (vboxSnapshotRedefine(dom, def, isCurrent) < 0)
                goto cleanup;
5521
            ret = virGetDomainSnapshot(dom, def->parent.name);
5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547
            goto cleanup;
        }
    }

    rc = gVBoxAPI.UIMachine.GetState(machine, &state);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get domain state"));
        goto cleanup;
    }

    if (gVBoxAPI.machineStateChecker.Online(state)) {
        rc = gVBoxAPI.UISession.OpenExisting(data, &domiid, machine);
    } else {
        rc = gVBoxAPI.UISession.Open(data, &domiid, machine);
    }

    if (NS_SUCCEEDED(rc))
        rc = gVBoxAPI.UISession.GetConsole(data->vboxSession, &console);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not open VirtualBox session with domain %s"),
                       dom->name);
        goto cleanup;
    }

5548
    VBOX_UTF8_TO_UTF16(def->parent.name, &name);
5549 5550 5551 5552 5553
    if (!name) {
        virReportOOMError();
        goto cleanup;
    }

5554 5555
    if (def->parent.description) {
        VBOX_UTF8_TO_UTF16(def->parent.description, &description);
5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584
        if (!description) {
            virReportOOMError();
            goto cleanup;
        }
    }

    rc = gVBoxAPI.UIConsole.TakeSnapshot(console, name, description, &progress);
    if (NS_FAILED(rc) || !progress) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not take snapshot of domain %s"), dom->name);
        goto cleanup;
    }

    gVBoxAPI.UIProgress.WaitForCompletion(progress, -1);
    gVBoxAPI.UIProgress.GetResultCode(progress, &result);
    if (RC_FAILED(result)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not take snapshot of domain %s"), dom->name);
        goto cleanup;
    }

    rc = gVBoxAPI.UIMachine.GetCurrentSnapshot(machine, &snapshot);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get current snapshot of domain %s"),
                  dom->name);
        goto cleanup;
    }

5585
    ret = virGetDomainSnapshot(dom, def->parent.name);
5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596

 cleanup:
    VBOX_RELEASE(progress);
    VBOX_UTF16_FREE(description);
    VBOX_UTF16_FREE(name);
    VBOX_RELEASE(console);
    gVBoxAPI.UISession.Close(data->vboxSession);
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&domiid);
    return ret;
}
5597 5598 5599 5600 5601 5602

static int
vboxDomainSnapshotGetAll(virDomainPtr dom,
                         IMachine *machine,
                         ISnapshot ***snapshots)
{
5603
    vboxIID empty;
5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682
    ISnapshot **list = NULL;
    PRUint32 count;
    nsresult rc;
    unsigned int next;
    unsigned int top;

    VBOX_IID_INITIALIZE(&empty);
    rc = gVBoxAPI.UIMachine.GetSnapshotCount(machine, &count);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get snapshot count for domain %s"),
                       dom->name);
        goto error;
    }

    if (count == 0)
        goto out;

    if (VIR_ALLOC_N(list, count) < 0)
        goto error;

    rc = gVBoxAPI.UIMachine.FindSnapshot(machine, &empty, list);
    if (NS_FAILED(rc) || !list[0]) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get root snapshot for domain %s"),
                       dom->name);
        goto error;
    }

    /* BFS walk through snapshot tree */
    top = 1;
    for (next = 0; next < count; next++) {
        vboxArray children = VBOX_ARRAY_INITIALIZER;
        size_t i;

        if (!list[next]) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected number of snapshots < %u"), count);
            goto error;
        }

        rc = gVBoxAPI.UArray.vboxArrayGet(&children, list[next],
                                          gVBoxAPI.UArray.handleSnapshotGetChildren(list[next]));
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("could not get children snapshots"));
            goto error;
        }
        for (i = 0; i < children.count; i++) {
            ISnapshot *child = children.items[i];
            if (!child)
                continue;
            if (top == count) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unexpected number of snapshots > %u"), count);
                gVBoxAPI.UArray.vboxArrayRelease(&children);
                goto error;
            }
            VBOX_ADDREF(child);
            list[top++] = child;
        }
        gVBoxAPI.UArray.vboxArrayRelease(&children);
    }

 out:
    *snapshots = list;
    return count;

 error:
    if (list) {
        for (next = 0; next < count; next++)
            VBOX_RELEASE(list[next]);
    }
    VIR_FREE(list);

    return -1;
}

static ISnapshot *
5683
vboxDomainSnapshotGet(vboxDriverPtr data,
5684 5685 5686 5687 5688 5689 5690
                      virDomainPtr dom,
                      IMachine *machine,
                      const char *name)
{
    ISnapshot **snapshots = NULL;
    ISnapshot *snapshot = NULL;
    nsresult rc;
5691
    ssize_t i, count = 0;
5692 5693

    if ((count = vboxDomainSnapshotGetAll(dom, machine, &snapshots)) < 0)
5694
        return NULL;
5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723

    for (i = 0; i < count; i++) {
        PRUnichar *nameUtf16;
        char *nameUtf8;

        rc = gVBoxAPI.UISnapshot.GetName(snapshots[i], &nameUtf16);
        if (NS_FAILED(rc) || !nameUtf16) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("could not get snapshot name"));
            goto cleanup;
        }
        VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
        VBOX_UTF16_FREE(nameUtf16);
        if (STREQ(name, nameUtf8))
            snapshot = snapshots[i];
        VBOX_UTF8_FREE(nameUtf8);

        if (snapshot)
            break;
    }

    if (!snapshot) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("domain %s has no snapshots with name %s"),
                       dom->name, name);
        goto cleanup;
    }

 cleanup:
5724 5725 5726
    for (i = 0; i < count; i++) {
        if (snapshots[i] != snapshot)
            VBOX_RELEASE(snapshots[i]);
5727 5728 5729 5730 5731
    }
    VIR_FREE(snapshots);
    return snapshot;
}

5732 5733 5734
static int
vboxSnapshotGetReadWriteDisks(virDomainSnapshotDefPtr def,
                              virDomainSnapshotPtr snapshot)
5735 5736
{
    virDomainPtr dom = snapshot->domain;
5737
    vboxDriverPtr data = dom->conn->privateData;
5738
    vboxIID domiid;
5739 5740 5741 5742
    IMachine *machine = NULL;
    ISnapshot *snap = NULL;
    IMachine *snapMachine = NULL;
    vboxArray mediumAttachments = VBOX_ARRAY_INITIALIZER;
5743
    size_t diskCount = 0, sdCount = 0;
5744
    nsresult rc;
5745
    vboxIID snapIid;
5746 5747
    char *snapshotUuidStr = NULL;
    size_t i = 0;
T
Taowei Luo 已提交
5748 5749 5750 5751
    int ret = -1;

    if (!data->vboxObj)
        return ret;
5752 5753 5754 5755 5756

    if (!gVBoxAPI.vboxSnapshotRedefine)
        VIR_WARN("This function may not work in current version");

    VBOX_IID_INITIALIZE(&snapIid);
5757
    if (openSessionForMachine(data, dom->uuid, &domiid, &machine) < 0)
5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815
        goto cleanup;

    if (!(snap = vboxDomainSnapshotGet(data, dom, machine, snapshot->name)))
        goto cleanup;

    rc = gVBoxAPI.UISnapshot.GetId(snap, &snapIid);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not get snapshot id"));
        goto cleanup;
    }

    gVBoxAPI.UIID.vboxIIDToUtf8(data, &snapIid, &snapshotUuidStr);
    vboxIIDUnalloc(&snapIid);
    rc = gVBoxAPI.UISnapshot.GetMachine(snap, &snapMachine);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get machine"));
        goto cleanup;
    }
    def->ndisks = 0;
    rc = gVBoxAPI.UArray.vboxArrayGet(&mediumAttachments, snapMachine,
                                      gVBoxAPI.UArray.handleMachineGetMediumAttachments(snapMachine));
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("no medium attachments"));
        goto cleanup;
    }
    /* get the number of attachments */
    for (i = 0; i < mediumAttachments.count; i++) {
        IMediumAttachment *imediumattach = mediumAttachments.items[i];
        if (imediumattach) {
            IMedium *medium = NULL;

            rc = gVBoxAPI.UIMediumAttachment.GetMedium(imediumattach, &medium);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cannot get medium"));
                goto cleanup;
            }
            if (medium) {
                def->ndisks++;
                VBOX_RELEASE(medium);
            }
        }
    }
    /* Allocate mem, if fails return error */
    if (VIR_ALLOC_N(def->disks, def->ndisks) < 0)
        goto cleanup;
    for (i = 0; i < def->ndisks; i++) {
        if (VIR_ALLOC(def->disks[i].src) < 0)
            goto cleanup;
    }

    /* get the attachment details here */
    for (i = 0; i < mediumAttachments.count && diskCount < def->ndisks; i++) {
        IStorageController *storageController = NULL;
        PRUnichar *storageControllerName = NULL;
5816 5817 5818
        PRUint32 deviceType = DeviceType_Null;
        PRUint32 storageBus = StorageBus_Null;
        IMedium *disk = NULL;
5819
        PRUnichar *childLocUtf16 = NULL;
5820 5821 5822
        char *childLocUtf8 = NULL;
        PRInt32 devicePort = 0;
        PRInt32 deviceSlot = 0;
5823 5824 5825 5826 5827 5828
        vboxArray children = VBOX_ARRAY_INITIALIZER;
        vboxArray snapshotIids = VBOX_ARRAY_INITIALIZER;
        IMediumAttachment *imediumattach = mediumAttachments.items[i];
        void *handle;
        size_t j = 0;
        size_t k = 0;
5829

5830 5831
        if (!imediumattach)
            continue;
5832 5833 5834

        rc = gVBoxAPI.UIMediumAttachment.GetController(imediumattach,
                                                       &storageControllerName);
5835 5836
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
5837
                           _("Cannot get storage controller name"));
5838 5839
            goto cleanup;
        }
5840 5841 5842 5843 5844

        rc = gVBoxAPI.UIMachine.GetStorageControllerByName(machine,
                                                           storageControllerName,
                                                           &storageController);
        VBOX_UTF16_FREE(storageControllerName);
5845 5846
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
5847
                           _("Cannot get storage controller by name"));
5848 5849
            goto cleanup;
        }
5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890

        rc = gVBoxAPI.UIStorageController.GetBus(storageController, &storageBus);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Cannot get storage controller bus"));
            VBOX_RELEASE(storageController);
            goto cleanup;
        }

        rc = gVBoxAPI.UIMediumAttachment.GetType(imediumattach, &deviceType);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Cannot get medium attachment type"));
            VBOX_RELEASE(storageController);
            goto cleanup;
        }
        rc = gVBoxAPI.UIMediumAttachment.GetPort(imediumattach, &devicePort);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Cannot get medium attachment port"));
            VBOX_RELEASE(storageController);
            goto cleanup;
        }
        rc = gVBoxAPI.UIMediumAttachment.GetDevice(imediumattach, &deviceSlot);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Cannot get medium attachment slot"));
            VBOX_RELEASE(storageController);
            goto cleanup;
        }

        rc = gVBoxAPI.UIMediumAttachment.GetMedium(imediumattach, &disk);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Cannot get medium"));
            VBOX_RELEASE(storageController);
            goto cleanup;
        }

        /* skip empty removable disk */
        if (!disk) {
5891 5892 5893 5894
            /* removable disks with empty (ejected) media won't be displayed
             * in XML, but we need to update "sdCount" so that device names match
             * in domain dumpxml and snapshot dumpxml
             */
D
Dawid Zamirski 已提交
5895 5896
            if (storageBus == StorageBus_SATA || storageBus == StorageBus_SCSI ||
                storageBus == StorageBus_SAS)
5897 5898
                sdCount++;

5899
            VBOX_RELEASE(storageController);
5900 5901
            continue;
        }
5902

5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928
        handle = gVBoxAPI.UArray.handleMediumGetChildren(disk);
        rc = gVBoxAPI.UArray.vboxArrayGet(&children, disk, handle);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot get children disk"));
            goto cleanup;
        }
        handle = gVBoxAPI.UArray.handleMediumGetSnapshotIds(disk);
        rc = gVBoxAPI.UArray.vboxArrayGetWithIIDArg(&snapshotIids, disk,
                                                    handle, &domiid);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot get snapshot ids"));
            goto cleanup;
        }
        for (j = 0; j < children.count; ++j) {
            IMedium *child = children.items[j];
            for (k = 0; k < snapshotIids.count; ++k) {
                PRUnichar *diskSnapId = snapshotIids.items[k];
                char *diskSnapIdStr = NULL;
                VBOX_UTF16_TO_UTF8(diskSnapId, &diskSnapIdStr);
                if (STREQ(diskSnapIdStr, snapshotUuidStr)) {
                    rc = gVBoxAPI.UIMedium.GetLocation(child, &childLocUtf16);
                    if (NS_FAILED(rc)) {
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("cannot get disk location"));
5929 5930 5931
                        VBOX_RELEASE(storageController);
                        VBOX_RELEASE(disk);
                        VBOX_RELEASE(child);
5932 5933 5934 5935 5936 5937
                        goto cleanup;
                    }
                    VBOX_UTF16_TO_UTF8(childLocUtf16, &childLocUtf8);
                    VBOX_UTF16_FREE(childLocUtf16);
                    if (VIR_STRDUP(def->disks[diskCount].src->path, childLocUtf8) < 0) {
                        VBOX_RELEASE(storageController);
5938 5939
                        VBOX_RELEASE(disk);
                        VBOX_RELEASE(child);
5940 5941 5942 5943 5944 5945 5946 5947
                        goto cleanup;
                    }
                    VBOX_UTF8_FREE(childLocUtf8);

                    def->disks[diskCount].src->type = VIR_STORAGE_TYPE_FILE;
                    def->disks[diskCount].name = vboxGenerateMediumName(storageBus,
                                                                        devicePort,
                                                                        deviceSlot,
5948
                                                                        sdCount);
5949 5950 5951 5952 5953 5954 5955
                }
                VBOX_UTF8_FREE(diskSnapIdStr);
            }
        }
        VBOX_RELEASE(storageController);
        VBOX_RELEASE(disk);
        diskCount++;
5956

D
Dawid Zamirski 已提交
5957 5958
        if (storageBus == StorageBus_SATA || storageBus == StorageBus_SCSI ||
            storageBus == StorageBus_SAS)
5959
            sdCount++;
D
Dawid Zamirski 已提交
5960

5961 5962 5963 5964
    }
    gVBoxAPI.UArray.vboxArrayRelease(&mediumAttachments);

    ret = 0;
5965

5966 5967
 cleanup:
    VBOX_RELEASE(snap);
5968

5969 5970 5971
    return ret;
}

5972
static int
5973 5974
vboxSnapshotGetReadOnlyDisks(virDomainSnapshotDefPtr def,
                             virDomainSnapshotPtr snapshot)
5975 5976
{
    virDomainPtr dom = snapshot->domain;
5977
    vboxDriverPtr data = dom->conn->privateData;
5978
    vboxIID domiid;
5979 5980 5981 5982 5983 5984 5985
    ISnapshot *snap = NULL;
    IMachine *machine = NULL;
    IMachine *snapMachine = NULL;
    IStorageController *storageController = NULL;
    IMedium *disk = NULL;
    nsresult rc;
    vboxArray mediumAttachments = VBOX_ARRAY_INITIALIZER;
5986
    size_t i = 0, diskCount = 0, sdCount = 0;
T
Taowei Luo 已提交
5987
    int ret = -1;
5988
    virDomainDefPtr defdom = def->parent.dom;
T
Taowei Luo 已提交
5989 5990 5991

    if (!data->vboxObj)
        return ret;
5992 5993 5994 5995

    if (!gVBoxAPI.vboxSnapshotRedefine)
        VIR_WARN("This function may not work in current version");

5996
    if (openSessionForMachine(data, dom->uuid, &domiid, &machine) < 0)
5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031
        goto cleanup;

    if (!(snap = vboxDomainSnapshotGet(data, dom, machine, snapshot->name)))
        goto cleanup;

    rc = gVBoxAPI.UISnapshot.GetMachine(snap, &snapMachine);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot get machine"));
        goto cleanup;
    }
    /*
     * Get READ ONLY disks
     * In the snapshot metadata, these are the disks written inside the <domain> node
    */
    rc = gVBoxAPI.UArray.vboxArrayGet(&mediumAttachments, snapMachine,
                                      gVBoxAPI.UArray.handleMachineGetMediumAttachments(snapMachine));
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot get medium attachments"));
        goto cleanup;
    }
    /* get the number of attachments */
    for (i = 0; i < mediumAttachments.count; i++) {
        IMediumAttachment *imediumattach = mediumAttachments.items[i];
        if (imediumattach) {
            IMedium *medium = NULL;

            rc = gVBoxAPI.UIMediumAttachment.GetMedium(imediumattach, &medium);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cannot get medium"));
                goto cleanup;
            }
            if (medium) {
E
Eric Blake 已提交
6032
                defdom->ndisks++;
6033 6034 6035 6036 6037 6038
                VBOX_RELEASE(medium);
            }
        }
    }

    /* Allocate mem, if fails return error */
E
Eric Blake 已提交
6039 6040
    if (VIR_ALLOC_N(defdom->disks, defdom->ndisks) >= 0) {
        for (i = 0; i < defdom->ndisks; i++) {
6041
            virDomainDiskDefPtr diskDef = virDomainDiskDefNew(NULL);
6042 6043
            if (!diskDef)
                goto cleanup;
E
Eric Blake 已提交
6044
            defdom->disks[i] = diskDef;
6045 6046 6047 6048 6049 6050
        }
    } else {
        goto cleanup;
    }

    /* get the attachment details here */
E
Eric Blake 已提交
6051
    for (i = 0; i < mediumAttachments.count && diskCount < defdom->ndisks; i++) {
6052
        PRUnichar *storageControllerName = NULL;
6053 6054 6055
        PRUint32 deviceType = DeviceType_Null;
        PRUint32 storageBus = StorageBus_Null;
        PRBool readOnly = PR_FALSE;
6056
        PRUnichar *mediumLocUtf16 = NULL;
6057 6058 6059
        char *mediumLocUtf8 = NULL;
        PRInt32 devicePort = 0;
        PRInt32 deviceSlot = 0;
6060 6061 6062 6063 6064 6065
        IMediumAttachment *imediumattach = mediumAttachments.items[i];
        if (!imediumattach)
            continue;
        rc = gVBoxAPI.UIMediumAttachment.GetController(imediumattach, &storageControllerName);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
6066
                           _("Cannot get storage controller name"));
6067 6068 6069 6070 6071 6072 6073
            goto cleanup;
        }
        if (!storageControllerName)
            continue;
        rc = gVBoxAPI.UIMachine.GetStorageControllerByName(machine,
                                                           storageControllerName,
                                                           &storageController);
6074
        VBOX_UTF16_FREE(storageControllerName);
6075 6076
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
6077
                           _("Cannot get storage controller"));
6078 6079 6080 6081
            goto cleanup;
        }
        if (!storageController)
            continue;
6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109
        rc = gVBoxAPI.UIStorageController.GetBus(storageController, &storageBus);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Cannot get storage controller bus"));
            goto cleanup;
        }
        rc = gVBoxAPI.UIMediumAttachment.GetPort(imediumattach, &devicePort);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Cannot get medium attachment port"));
            goto cleanup;
        }
        rc = gVBoxAPI.UIMediumAttachment.GetDevice(imediumattach, &deviceSlot);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Cannot get device slot"));
            goto cleanup;
        }

        rc = gVBoxAPI.UIMediumAttachment.GetMedium(imediumattach, &disk);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Cannot get medium"));
            goto cleanup;
        }

        /* skip empty removable disk */
        if (!disk) {
6110 6111 6112 6113
            /* removable disks with empty (ejected) media won't be displayed
             * in XML, but we need to update "sdCount" so that device names match
             * in domain dumpxml and snapshot dumpxml
             */
D
Dawid Zamirski 已提交
6114 6115
            if (storageBus == StorageBus_SATA || storageBus == StorageBus_SCSI ||
                storageBus == StorageBus_SAS)
6116 6117
                sdCount++;

6118 6119 6120 6121
            VBOX_RELEASE(storageController);
            continue;
        }

6122 6123 6124
        rc = gVBoxAPI.UIMedium.GetLocation(disk, &mediumLocUtf16);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
6125
                           _("Cannot get disk location"));
6126 6127 6128 6129
            goto cleanup;
        }
        VBOX_UTF16_TO_UTF8(mediumLocUtf16, &mediumLocUtf8);
        VBOX_UTF16_FREE(mediumLocUtf16);
E
Eric Blake 已提交
6130
        if (VIR_STRDUP(defdom->disks[diskCount]->src->path, mediumLocUtf8) < 0)
6131 6132 6133
            goto cleanup;

        VBOX_UTF8_FREE(mediumLocUtf8);
6134
        rc = gVBoxAPI.UIMedium.GetReadOnly(disk, &readOnly);
6135 6136
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
6137
                           _("Cannot get read only attribute"));
6138 6139
            goto cleanup;
        }
6140

E
Eric Blake 已提交
6141 6142 6143 6144 6145
        defdom->disks[diskCount]->dst = vboxGenerateMediumName(storageBus,
                                                               devicePort,
                                                               deviceSlot,
                                                               sdCount);
        if (!defdom->disks[diskCount]->dst) {
6146 6147 6148 6149 6150 6151 6152
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not generate medium name for the disk "
                             "at: port:%d, slot:%d"), devicePort, deviceSlot);
            ret = -1;
            goto cleanup;
        }

6153
        if (storageBus == StorageBus_IDE) {
E
Eric Blake 已提交
6154
            defdom->disks[diskCount]->bus = VIR_DOMAIN_DISK_BUS_IDE;
6155
        } else if (storageBus == StorageBus_SATA) {
6156
            sdCount++;
E
Eric Blake 已提交
6157
            defdom->disks[diskCount]->bus = VIR_DOMAIN_DISK_BUS_SATA;
D
Dawid Zamirski 已提交
6158 6159
        } else if (storageBus == StorageBus_SCSI ||
                   storageBus == StorageBus_SAS) {
6160
            sdCount++;
E
Eric Blake 已提交
6161
            defdom->disks[diskCount]->bus = VIR_DOMAIN_DISK_BUS_SCSI;
6162
        } else if (storageBus == StorageBus_Floppy) {
E
Eric Blake 已提交
6163
            defdom->disks[diskCount]->bus = VIR_DOMAIN_DISK_BUS_FDC;
6164 6165 6166 6167 6168 6169 6170 6171 6172
        }

        rc = gVBoxAPI.UIMediumAttachment.GetType(imediumattach, &deviceType);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot get medium attachment type"));
            goto cleanup;
        }
        if (deviceType == DeviceType_HardDisk)
E
Eric Blake 已提交
6173
            defdom->disks[diskCount]->device = VIR_DOMAIN_DISK_DEVICE_DISK;
6174
        else if (deviceType == DeviceType_Floppy)
E
Eric Blake 已提交
6175
            defdom->disks[diskCount]->device = VIR_DOMAIN_DISK_DEVICE_FLOPPY;
6176
        else if (deviceType == DeviceType_DVD)
E
Eric Blake 已提交
6177
            defdom->disks[diskCount]->device = VIR_DOMAIN_DISK_DEVICE_CDROM;
6178 6179

        if (readOnly == PR_TRUE)
E
Eric Blake 已提交
6180 6181
            defdom->disks[diskCount]->src->readonly = true;
        defdom->disks[diskCount]->src->type = VIR_STORAGE_TYPE_FILE;
6182 6183

        diskCount++;
6184 6185 6186
    }

    ret = 0;
6187

6188 6189 6190 6191 6192
 cleanup:
    VBOX_RELEASE(disk);
    VBOX_RELEASE(storageController);
    gVBoxAPI.UArray.vboxArrayRelease(&mediumAttachments);
    VBOX_RELEASE(snap);
6193

6194 6195 6196
    return ret;
}

T
Taowei 已提交
6197 6198
static char *vboxDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                                          unsigned int flags)
6199 6200
{
    virDomainPtr dom = snapshot->domain;
6201
    vboxDriverPtr data = dom->conn->privateData;
6202
    vboxIID domiid;
6203 6204 6205 6206 6207 6208 6209 6210 6211
    IMachine *machine = NULL;
    ISnapshot *snap = NULL;
    ISnapshot *parent = NULL;
    nsresult rc;
    PRUnichar *str16;
    char *str8;
    PRInt64 timestamp;
    PRBool online = PR_FALSE;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
T
Taowei Luo 已提交
6212
    char *ret = NULL;
E
Eric Blake 已提交
6213
    virDomainDefPtr defdom;
6214
    VIR_AUTOUNREF(virDomainSnapshotDefPtr) def = NULL;
T
Taowei Luo 已提交
6215 6216 6217

    if (!data->vboxObj)
        return ret;
6218 6219 6220

    virCheckFlags(0, NULL);

6221
    if (openSessionForMachine(data, dom->uuid, &domiid, &machine) < 0)
6222 6223 6224 6225 6226
        goto cleanup;

    if (!(snap = vboxDomainSnapshotGet(data, dom, machine, snapshot->name)))
        goto cleanup;

6227 6228
    if (!(def = virDomainSnapshotDefNew()) ||
        !(def->parent.dom = virDomainDefNew()))
6229
        goto cleanup;
6230 6231
    defdom = def->parent.dom;
    if (VIR_STRDUP(def->parent.name, snapshot->name) < 0)
6232 6233 6234 6235 6236 6237 6238 6239 6240
        goto cleanup;

    if (gVBoxAPI.vboxSnapshotRedefine) {
        /* Register def->dom properties for them to be saved inside the snapshot XMl
         * Otherwise, there is a problem while parsing the xml
         */
        PRUint32 memorySize = 0;
        PRUint32 CPUCount = 0;

E
Eric Blake 已提交
6241 6242 6243 6244
        defdom->virtType = VIR_DOMAIN_VIRT_VBOX;
        defdom->id = dom->id;
        memcpy(defdom->uuid, dom->uuid, VIR_UUID_BUFLEN);
        if (VIR_STRDUP(defdom->name, dom->name) < 0)
6245 6246
            goto cleanup;
        gVBoxAPI.UIMachine.GetMemorySize(machine, &memorySize);
E
Eric Blake 已提交
6247
        defdom->mem.cur_balloon = memorySize * 1024;
6248 6249 6250 6251
        /* Currently setting memory and maxMemory as same, cause
         * the notation here seems to be inconsistent while
         * reading and while dumping xml
         */
E
Eric Blake 已提交
6252 6253 6254
        virDomainDefSetMemoryTotal(defdom, memorySize * 1024);
        defdom->os.type = VIR_DOMAIN_OSTYPE_HVM;
        defdom->os.arch = virArchFromHost();
6255
        gVBoxAPI.UIMachine.GetCPUCount(machine, &CPUCount);
E
Eric Blake 已提交
6256
        if (virDomainDefSetVcpusMax(defdom, CPUCount, data->xmlopt) < 0)
6257 6258
            goto cleanup;

E
Eric Blake 已提交
6259
        if (virDomainDefSetVcpus(defdom, CPUCount) < 0)
6260
            goto cleanup;
6261

6262
        if (vboxSnapshotGetReadWriteDisks(def, snapshot) < 0)
6263 6264
            VIR_DEBUG("Could not get read write disks for snapshot");

6265
        if (vboxSnapshotGetReadOnlyDisks(def, snapshot) < 0)
6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278
            VIR_DEBUG("Could not get Readonly disks for snapshot");
    }

    rc = gVBoxAPI.UISnapshot.GetDescription(snap, &str16);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get description of snapshot %s"),
                       snapshot->name);
        goto cleanup;
    }
    if (str16) {
        VBOX_UTF16_TO_UTF8(str16, &str8);
        VBOX_UTF16_FREE(str16);
6279
        if (VIR_STRDUP(def->parent.description, str8) < 0) {
6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293
            VBOX_UTF8_FREE(str8);
            goto cleanup;
        }
        VBOX_UTF8_FREE(str8);
    }

    rc = gVBoxAPI.UISnapshot.GetTimeStamp(snap, &timestamp);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get creation time of snapshot %s"),
                       snapshot->name);
        goto cleanup;
    }
    /* timestamp is in milliseconds while creationTime in seconds */
6294
    def->parent.creationTime = timestamp / 1000;
6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312

    rc = gVBoxAPI.UISnapshot.GetParent(snap, &parent);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get parent of snapshot %s"),
                       snapshot->name);
        goto cleanup;
    }
    if (parent) {
        rc = gVBoxAPI.UISnapshot.GetName(parent, &str16);
        if (NS_FAILED(rc) || !str16) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("could not get name of parent of snapshot %s"),
                           snapshot->name);
            goto cleanup;
        }
        VBOX_UTF16_TO_UTF8(str16, &str8);
        VBOX_UTF16_FREE(str16);
6313
        if (VIR_STRDUP(def->parent.parent_name, str8) < 0) {
6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327
            VBOX_UTF8_FREE(str8);
            goto cleanup;
        }
        VBOX_UTF8_FREE(str8);
    }

    rc = gVBoxAPI.UISnapshot.GetOnline(snap, &online);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get online state of snapshot %s"),
                       snapshot->name);
        goto cleanup;
    }
    if (online)
6328
        def->state = VIR_DOMAIN_SNAPSHOT_RUNNING;
6329
    else
6330
        def->state = VIR_DOMAIN_SNAPSHOT_SHUTOFF;
6331 6332

    virUUIDFormat(dom->uuid, uuidstr);
E
Eric Blake 已提交
6333
    memcpy(defdom->uuid, dom->uuid, VIR_UUID_BUFLEN);
6334
    ret = virDomainSnapshotDefFormat(uuidstr, def, data->caps, data->xmlopt, 0);
6335 6336 6337 6338 6339 6340 6341 6342

 cleanup:
    VBOX_RELEASE(parent);
    VBOX_RELEASE(snap);
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&domiid);
    return ret;
}
T
Taowei 已提交
6343

T
Taowei 已提交
6344
static int vboxDomainSnapshotNum(virDomainPtr dom, unsigned int flags)
T
Taowei 已提交
6345
{
6346
    vboxDriverPtr data = dom->conn->privateData;
6347
    vboxIID iid;
T
Taowei 已提交
6348 6349 6350
    IMachine *machine = NULL;
    nsresult rc;
    PRUint32 snapshotCount;
T
Taowei Luo 已提交
6351 6352 6353 6354
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
6355 6356 6357 6358

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA, -1);

6359
    if (openSessionForMachine(data, dom->uuid, &iid, &machine) < 0)
T
Taowei 已提交
6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386
        goto cleanup;

    /* VBox snapshots do not require libvirt to maintain any metadata.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA) {
        ret = 0;
        goto cleanup;
    }

    rc = gVBoxAPI.UIMachine.GetSnapshotCount(machine, &snapshotCount);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get snapshot count for domain %s"),
                       dom->name);
        goto cleanup;
    }

    /* VBox has at most one root snapshot.  */
    if (snapshotCount && (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS))
        ret = 1;
    else
        ret = snapshotCount;

 cleanup:
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}
6387

T
Taowei 已提交
6388 6389
static int vboxDomainSnapshotListNames(virDomainPtr dom, char **names,
                                       int nameslen, unsigned int flags)
6390
{
6391
    vboxDriverPtr data = dom->conn->privateData;
6392
    vboxIID iid;
6393 6394 6395
    IMachine *machine = NULL;
    nsresult rc;
    ISnapshot **snapshots = NULL;
6396
    ssize_t i, count = 0;
T
Taowei Luo 已提交
6397 6398 6399 6400
    int ret = -1;

    if (!data->vboxObj)
        return ret;
6401 6402 6403 6404

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA, -1);

6405
    if (openSessionForMachine(data, dom->uuid, &iid, &machine) < 0)
6406 6407 6408 6409 6410 6411 6412 6413
        goto cleanup;

    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA) {
        ret = 0;
        goto cleanup;
    }

    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) {
6414
        vboxIID empty;
6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459

        VBOX_IID_INITIALIZE(&empty);
        if (VIR_ALLOC_N(snapshots, 1) < 0)
            goto cleanup;
        rc = gVBoxAPI.UIMachine.FindSnapshot(machine, &empty, snapshots);
        if (NS_FAILED(rc) || !snapshots[0]) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("could not get root snapshot for domain %s"),
                           dom->name);
            goto cleanup;
        }
        count = 1;
    } else {
        if ((count = vboxDomainSnapshotGetAll(dom, machine, &snapshots)) < 0)
            goto cleanup;
    }

    for (i = 0; i < nameslen; i++) {
        PRUnichar *nameUtf16;
        char *name;

        if (i >= count)
            break;

        rc = gVBoxAPI.UISnapshot.GetName(snapshots[i], &nameUtf16);
        if (NS_FAILED(rc) || !nameUtf16) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("could not get snapshot name"));
            goto cleanup;
        }
        VBOX_UTF16_TO_UTF8(nameUtf16, &name);
        VBOX_UTF16_FREE(nameUtf16);
        if (VIR_STRDUP(names[i], name) < 0) {
            VBOX_UTF8_FREE(name);
            goto cleanup;
        }
        VBOX_UTF8_FREE(name);
    }

    if (count <= nameslen)
        ret = count;
    else
        ret = nameslen;

 cleanup:
6460 6461
    for (i = 0; i < count; i++)
        VBOX_RELEASE(snapshots[i]);
6462 6463 6464 6465 6466
    VIR_FREE(snapshots);
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}
T
Taowei 已提交
6467

T
Taowei 已提交
6468
static virDomainSnapshotPtr
T
Taowei 已提交
6469 6470 6471
vboxDomainSnapshotLookupByName(virDomainPtr dom, const char *name,
                               unsigned int flags)
{
6472
    vboxDriverPtr data = dom->conn->privateData;
6473
    vboxIID iid;
T
Taowei 已提交
6474 6475
    IMachine *machine = NULL;
    ISnapshot *snapshot = NULL;
T
Taowei Luo 已提交
6476 6477 6478 6479
    virDomainSnapshotPtr ret = NULL;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
6480 6481 6482

    virCheckFlags(0, NULL);

6483
    if (openSessionForMachine(data, dom->uuid, &iid, &machine) < 0)
T
Taowei 已提交
6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496
        goto cleanup;

    if (!(snapshot = vboxDomainSnapshotGet(data, dom, machine, name)))
        goto cleanup;

    ret = virGetDomainSnapshot(dom, name);

 cleanup:
    VBOX_RELEASE(snapshot);
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}
6497

T
Taowei 已提交
6498 6499
static int vboxDomainHasCurrentSnapshot(virDomainPtr dom,
                                        unsigned int flags)
6500
{
6501
    vboxDriverPtr data = dom->conn->privateData;
6502
    vboxIID iid;
6503 6504 6505
    IMachine *machine = NULL;
    ISnapshot *snapshot = NULL;
    nsresult rc;
T
Taowei Luo 已提交
6506 6507 6508 6509
    int ret = -1;

    if (!data->vboxObj)
        return ret;
6510 6511 6512

    virCheckFlags(0, -1);

6513
    if (openSessionForMachine(data, dom->uuid, &iid, &machine) < 0)
6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532
        goto cleanup;

    rc = gVBoxAPI.UIMachine.GetCurrentSnapshot(machine, &snapshot);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get current snapshot"));
        goto cleanup;
    }

    if (snapshot)
        ret = 1;
    else
        ret = 0;

 cleanup:
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}
6533

T
Taowei 已提交
6534
static virDomainSnapshotPtr
6535 6536 6537 6538
vboxDomainSnapshotGetParent(virDomainSnapshotPtr snapshot,
                            unsigned int flags)
{
    virDomainPtr dom = snapshot->domain;
6539
    vboxDriverPtr data = dom->conn->privateData;
6540
    vboxIID iid;
6541 6542 6543 6544 6545 6546
    IMachine *machine = NULL;
    ISnapshot *snap = NULL;
    ISnapshot *parent = NULL;
    PRUnichar *nameUtf16 = NULL;
    char *name = NULL;
    nsresult rc;
T
Taowei Luo 已提交
6547 6548 6549 6550
    virDomainSnapshotPtr ret = NULL;

    if (!data->vboxObj)
        return ret;
6551 6552 6553

    virCheckFlags(0, NULL);

6554
    if (openSessionForMachine(data, dom->uuid, &iid, &machine) < 0)
6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597
        goto cleanup;

    if (!(snap = vboxDomainSnapshotGet(data, dom, machine, snapshot->name)))
        goto cleanup;

    rc = gVBoxAPI.UISnapshot.GetParent(snap, &parent);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get parent of snapshot %s"),
                       snapshot->name);
        goto cleanup;
    }
    if (!parent) {
        virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                       _("snapshot '%s' does not have a parent"),
                       snapshot->name);
        goto cleanup;
    }

    rc = gVBoxAPI.UISnapshot.GetName(parent, &nameUtf16);
    if (NS_FAILED(rc) || !nameUtf16) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get name of parent of snapshot %s"),
                       snapshot->name);
        goto cleanup;
    }
    VBOX_UTF16_TO_UTF8(nameUtf16, &name);
    if (!name) {
        virReportOOMError();
        goto cleanup;
    }

    ret = virGetDomainSnapshot(dom, name);

 cleanup:
    VBOX_UTF8_FREE(name);
    VBOX_UTF16_FREE(nameUtf16);
    VBOX_RELEASE(snap);
    VBOX_RELEASE(parent);
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}
T
Taowei 已提交
6598

T
Taowei 已提交
6599
static virDomainSnapshotPtr
T
Taowei 已提交
6600 6601
vboxDomainSnapshotCurrent(virDomainPtr dom, unsigned int flags)
{
6602
    vboxDriverPtr data = dom->conn->privateData;
6603
    vboxIID iid;
T
Taowei 已提交
6604 6605 6606 6607 6608
    IMachine *machine = NULL;
    ISnapshot *snapshot = NULL;
    PRUnichar *nameUtf16 = NULL;
    char *name = NULL;
    nsresult rc;
T
Taowei Luo 已提交
6609 6610 6611 6612
    virDomainSnapshotPtr ret = NULL;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
6613 6614 6615

    virCheckFlags(0, NULL);

6616
    if (openSessionForMachine(data, dom->uuid, &iid, &machine) < 0)
T
Taowei 已提交
6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654
        goto cleanup;

    rc = gVBoxAPI.UIMachine.GetCurrentSnapshot(machine, &snapshot);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get current snapshot"));
        goto cleanup;
    }

    if (!snapshot) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("domain has no snapshots"));
        goto cleanup;
    }

    rc = gVBoxAPI.UISnapshot.GetName(snapshot, &nameUtf16);
    if (NS_FAILED(rc) || !nameUtf16) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get current snapshot name"));
        goto cleanup;
    }

    VBOX_UTF16_TO_UTF8(nameUtf16, &name);
    if (!name) {
        virReportOOMError();
        goto cleanup;
    }

    ret = virGetDomainSnapshot(dom, name);

 cleanup:
    VBOX_UTF8_FREE(name);
    VBOX_UTF16_FREE(nameUtf16);
    VBOX_RELEASE(snapshot);
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}
6655

T
Taowei 已提交
6656 6657
static int vboxDomainSnapshotIsCurrent(virDomainSnapshotPtr snapshot,
                                       unsigned int flags)
6658 6659
{
    virDomainPtr dom = snapshot->domain;
6660
    vboxDriverPtr data = dom->conn->privateData;
6661
    vboxIID iid;
6662 6663 6664 6665 6666 6667
    IMachine *machine = NULL;
    ISnapshot *snap = NULL;
    ISnapshot *current = NULL;
    PRUnichar *nameUtf16 = NULL;
    char *name = NULL;
    nsresult rc;
T
Taowei Luo 已提交
6668 6669 6670 6671
    int ret = -1;

    if (!data->vboxObj)
        return ret;
6672 6673 6674

    virCheckFlags(0, -1);

6675
    if (openSessionForMachine(data, dom->uuid, &iid, &machine) < 0)
6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715
        goto cleanup;

    if (!(snap = vboxDomainSnapshotGet(data, dom, machine, snapshot->name)))
        goto cleanup;

    rc = gVBoxAPI.UIMachine.GetCurrentSnapshot(machine, &current);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get current snapshot"));
        goto cleanup;
    }
    if (!current) {
        ret = 0;
        goto cleanup;
    }

    rc = gVBoxAPI.UISnapshot.GetName(current, &nameUtf16);
    if (NS_FAILED(rc) || !nameUtf16) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get current snapshot name"));
        goto cleanup;
    }

    VBOX_UTF16_TO_UTF8(nameUtf16, &name);
    if (!name) {
        virReportOOMError();
        goto cleanup;
    }

    ret = STREQ(snapshot->name, name);

 cleanup:
    VBOX_UTF8_FREE(name);
    VBOX_UTF16_FREE(nameUtf16);
    VBOX_RELEASE(snap);
    VBOX_RELEASE(current);
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}
6716

T
Taowei 已提交
6717 6718
static int vboxDomainSnapshotHasMetadata(virDomainSnapshotPtr snapshot,
                                         unsigned int flags)
6719 6720
{
    virDomainPtr dom = snapshot->domain;
6721
    vboxDriverPtr data = dom->conn->privateData;
6722
    vboxIID iid;
6723 6724
    IMachine *machine = NULL;
    ISnapshot *snap = NULL;
T
Taowei Luo 已提交
6725 6726 6727 6728
    int ret = -1;

    if (!data->vboxObj)
        return ret;
6729 6730 6731

    virCheckFlags(0, -1);

6732
    if (openSessionForMachine(data, dom->uuid, &iid, &machine) < 0)
6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746
        goto cleanup;

    /* Check that snapshot exists.  If so, there is no metadata.  */
    if (!(snap = vboxDomainSnapshotGet(data, dom, machine, snapshot->name)))
        goto cleanup;

    ret = 0;

 cleanup:
    VBOX_RELEASE(snap);
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}
6747

T
Taowei 已提交
6748 6749
static int vboxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot,
                                      unsigned int flags)
6750 6751
{
    virDomainPtr dom = snapshot->domain;
6752
    vboxDriverPtr data = dom->conn->privateData;
6753
    vboxIID domiid;
6754 6755 6756 6757 6758 6759
    IMachine *machine = NULL;
    ISnapshot *newSnapshot = NULL;
    ISnapshot *prevSnapshot = NULL;
    PRBool online = PR_FALSE;
    PRUint32 state;
    nsresult rc;
T
Taowei Luo 已提交
6760 6761 6762 6763
    int ret = -1;

    if (!data->vboxObj)
        return ret;
6764 6765 6766

    virCheckFlags(0, -1);

6767
    if (openSessionForMachine(data, dom->uuid, &domiid, &machine) < 0)
6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809
        goto cleanup;

    newSnapshot = vboxDomainSnapshotGet(data, dom, machine, snapshot->name);
    if (!newSnapshot)
        goto cleanup;

    rc = gVBoxAPI.UISnapshot.GetOnline(newSnapshot, &online);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get online state of snapshot %s"),
                       snapshot->name);
        goto cleanup;
    }

    rc = gVBoxAPI.UIMachine.GetCurrentSnapshot(machine, &prevSnapshot);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get current snapshot of domain %s"),
                       dom->name);
        goto cleanup;
    }

    rc = gVBoxAPI.UIMachine.GetState(machine, &state);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get domain state"));
        goto cleanup;
    }

    if (gVBoxAPI.machineStateChecker.Online(state)) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot revert snapshot of running domain"));
        goto cleanup;
    }

    if (gVBoxAPI.snapshotRestore(dom, machine, newSnapshot))
        goto cleanup;

    if (online) {
        ret = vboxDomainCreate(dom);
        if (!ret)
            gVBoxAPI.snapshotRestore(dom, machine, prevSnapshot);
6810
    } else {
6811
        ret = 0;
6812
    }
6813 6814 6815 6816 6817 6818 6819

 cleanup:
    VBOX_RELEASE(prevSnapshot);
    VBOX_RELEASE(newSnapshot);
    vboxIIDUnalloc(&domiid);
    return ret;
}
T
Taowei 已提交
6820 6821

static int
6822
vboxDomainSnapshotDeleteSingle(vboxDriverPtr data,
T
Taowei 已提交
6823 6824 6825 6826
                               IConsole *console,
                               ISnapshot *snapshot)
{
    IProgress *progress = NULL;
6827
    vboxIID iid;
T
Taowei 已提交
6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868
    int ret = -1;
    nsresult rc;
    resultCodeUnion result;

    VBOX_IID_INITIALIZE(&iid);
    rc = gVBoxAPI.UISnapshot.GetId(snapshot, &iid);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get snapshot UUID"));
        goto cleanup;
    }

    rc = gVBoxAPI.UIConsole.DeleteSnapshot(console, &iid, &progress);
    if (NS_FAILED(rc) || !progress) {
        if (rc == VBOX_E_INVALID_VM_STATE) {
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("cannot delete domain snapshot for running domain"));
        } else {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("could not delete snapshot"));
        }
        goto cleanup;
    }

    gVBoxAPI.UIProgress.WaitForCompletion(progress, -1);
    gVBoxAPI.UIProgress.GetResultCode(progress, &result);
    if (RC_FAILED(result)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not delete snapshot"));
        goto cleanup;
    }

    ret = 0;

 cleanup:
    VBOX_RELEASE(progress);
    vboxIIDUnalloc(&iid);
    return ret;
}

static int
6869
vboxDomainSnapshotDeleteTree(vboxDriverPtr data,
T
Taowei 已提交
6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915
                             IConsole *console,
                             ISnapshot *snapshot)
{
    vboxArray children = VBOX_ARRAY_INITIALIZER;
    int ret = -1;
    nsresult rc;
    size_t i;

    rc = gVBoxAPI.UArray.vboxArrayGet(&children, snapshot,
                  gVBoxAPI.UArray.handleSnapshotGetChildren(snapshot));
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get children snapshots"));
        goto cleanup;
    }

    for (i = 0; i < children.count; i++) {
        if (vboxDomainSnapshotDeleteTree(data, console, children.items[i]))
            goto cleanup;
    }

    ret = vboxDomainSnapshotDeleteSingle(data, console, snapshot);

 cleanup:
    gVBoxAPI.UArray.vboxArrayRelease(&children);
    return ret;
}

static int
vboxDomainSnapshotDeleteMetadataOnly(virDomainSnapshotPtr snapshot)
{
    /*
     * This function will remove the node in the vbox xml corresponding to the snapshot.
     * It is usually called by vboxDomainSnapshotDelete() with the flag
     * VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY.
     * If you want to use it anywhere else, be careful, if the snapshot you want to delete
     * has children, the result is not granted, they will probably will be deleted in the
     * xml, but you may have a problem with hard drives.
     *
     * If the snapshot which is being deleted is the current one, we will set the current
     * snapshot of the machine to the parent of this snapshot. Before writing the modified
     * xml file, we undefine the machine from vbox. After writing the file, we redefine
     * the machine with the new file.
     */

    virDomainPtr dom = snapshot->domain;
6916
    vboxDriverPtr data = dom->conn->privateData;
T
Taowei 已提交
6917 6918
    virDomainSnapshotDefPtr def = NULL;
    char *defXml = NULL;
6919
    vboxIID domiid;
T
Taowei 已提交
6920 6921 6922 6923 6924 6925
    nsresult rc;
    IMachine *machine = NULL;
    PRUnichar *settingsFilePathUtf16 = NULL;
    char *settingsFilepath = NULL;
    virVBoxSnapshotConfMachinePtr snapshotMachineDesc = NULL;
    int isCurrent = -1;
6926 6927
    char **searchResultTab = NULL;
    ssize_t resultSize = 0;
T
Taowei 已提交
6928 6929 6930 6931 6932 6933 6934
    int it = 0;
    PRUnichar *machineNameUtf16 = NULL;
    char *machineName = NULL;
    char *nameTmpUse = NULL;
    char *machineLocationPath = NULL;
    PRUint32 aMediaSize = 0;
    IMedium **aMedia = NULL;
T
Taowei Luo 已提交
6935 6936 6937 6938
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951

    VBOX_IID_INITIALIZE(&domiid);
    if (!gVBoxAPI.vboxSnapshotRedefine)
        VIR_WARN("This function may not work in current version");

    defXml = vboxDomainSnapshotGetXMLDesc(snapshot, 0);
    if (!defXml) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to get XML Desc of snapshot"));
        goto cleanup;
    }
    def = virDomainSnapshotDefParseString(defXml,
                                          data->caps,
6952
                                          data->xmlopt, NULL,
T
Taowei 已提交
6953 6954 6955 6956 6957 6958 6959 6960
                                          VIR_DOMAIN_SNAPSHOT_PARSE_DISKS |
                                          VIR_DOMAIN_SNAPSHOT_PARSE_REDEFINE);
    if (!def) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to get a virDomainSnapshotDefPtr"));
        goto cleanup;
    }

6961
    if (openSessionForMachine(data, dom->uuid, &domiid, &machine) < 0)
T
Taowei 已提交
6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993
        goto cleanup;
    rc = gVBoxAPI.UIMachine.GetSettingsFilePath(machine, &settingsFilePathUtf16);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot get settings file path"));
        goto cleanup;
    }
    VBOX_UTF16_TO_UTF8(settingsFilePathUtf16, &settingsFilepath);

    /*Getting the machine name to retrieve the machine location path.*/
    rc = gVBoxAPI.UIMachine.GetName(machine, &machineNameUtf16);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot get machine name"));
        goto cleanup;
    }
    VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineName);
    if (virAsprintf(&nameTmpUse, "%s.vbox", machineName) < 0)
        goto cleanup;
    machineLocationPath = virStringReplace(settingsFilepath, nameTmpUse, "");
    if (machineLocationPath == NULL) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to get the machine location path"));
        goto cleanup;
    }
    snapshotMachineDesc = virVBoxSnapshotConfLoadVboxFile(settingsFilepath, machineLocationPath);
    if (!snapshotMachineDesc) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot create a vboxSnapshotXmlPtr"));
        goto cleanup;
    }

6994
    isCurrent = virVBoxSnapshotConfIsCurrentSnapshot(snapshotMachineDesc, def->parent.name);
T
Taowei 已提交
6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005
    if (isCurrent < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to know if the snapshot is the current snapshot"));
        goto cleanup;
    }
    if (isCurrent) {
        /*
         * If the snapshot is the current snapshot, it means that the machine has read-write
         * disks. The first thing to do is to manipulate VirtualBox API to create
         * differential read-write disks if the parent snapshot is not null.
         */
7006 7007
        if (def->parent.parent_name != NULL) {
            for (it = 0; it < def->parent.dom->ndisks; it++) {
T
Taowei 已提交
7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020
                virVBoxSnapshotConfHardDiskPtr readOnly = NULL;
                IMedium *medium = NULL;
                PRUnichar *locationUtf16 = NULL;
                char *parentUuid = NULL;
                IMedium *newMedium = NULL;
                PRUnichar *formatUtf16 = NULL;
                PRUnichar *newLocation = NULL;
                char *newLocationUtf8 = NULL;
                IProgress *progress = NULL;
                virVBoxSnapshotConfHardDiskPtr disk = NULL;
                char *uuid = NULL;
                char *format = NULL;
                char *tmp = NULL;
7021
                vboxIID iid, parentiid;
T
Taowei 已提交
7022 7023 7024 7025 7026
                resultCodeUnion resultCode;

                VBOX_IID_INITIALIZE(&iid);
                VBOX_IID_INITIALIZE(&parentiid);
                readOnly = virVBoxSnapshotConfHardDiskPtrByLocation(snapshotMachineDesc,
7027
                                                 def->parent.dom->disks[it]->src->path);
T
Taowei 已提交
7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064
                if (!readOnly) {
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("Cannot get hard disk by location"));
                    goto cleanup;
                }
                if (readOnly->parent == NULL) {
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("The read only disk has no parent"));
                    goto cleanup;
                }

                VBOX_UTF8_TO_UTF16(readOnly->parent->location, &locationUtf16);
                rc = gVBoxAPI.UIVirtualBox.OpenMedium(data->vboxObj,
                                                      locationUtf16,
                                                      DeviceType_HardDisk,
                                                      AccessMode_ReadWrite,
                                                      &medium);
                if (NS_FAILED(rc)) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unable to open HardDisk, rc=%08x"),
                                   (unsigned)rc);
                    goto cleanup;
                }

                rc = gVBoxAPI.UIMedium.GetId(medium, &parentiid);
                if (NS_FAILED(rc)) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unable to get hardDisk Id, rc=%08x"),
                                   (unsigned)rc);
                    goto cleanup;
                }
                gVBoxAPI.UIID.vboxIIDToUtf8(data, &parentiid, &parentUuid);
                vboxIIDUnalloc(&parentiid);
                VBOX_UTF16_FREE(locationUtf16);
                VBOX_UTF8_TO_UTF16("VDI", &formatUtf16);

                if (virAsprintf(&newLocationUtf8, "%sfakedisk-%s-%d.vdi",
7065
                                machineLocationPath, def->parent.parent_name, it) < 0)
T
Taowei 已提交
7066 7067
                    goto cleanup;
                VBOX_UTF8_TO_UTF16(newLocationUtf8, &newLocation);
7068 7069 7070 7071
                rc = gVBoxAPI.UIVirtualBox.CreateHardDisk(data->vboxObj,
                                                          formatUtf16,
                                                          newLocation,
                                                          &newMedium);
T
Taowei 已提交
7072 7073 7074 7075 7076 7077 7078 7079 7080 7081
                if (NS_FAILED(rc)) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unable to create HardDisk, rc=%08x"),
                                   (unsigned)rc);
                    goto cleanup;
                }
                VBOX_UTF16_FREE(formatUtf16);
                VBOX_UTF16_FREE(newLocation);

                PRUint32 tab[1];
7082
                tab[0] = MediumVariant_Diff;
T
Taowei 已提交
7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162
                gVBoxAPI.UIMedium.CreateDiffStorage(medium, newMedium, 1, tab, &progress);

                gVBoxAPI.UIProgress.WaitForCompletion(progress, -1);
                gVBoxAPI.UIProgress.GetResultCode(progress, &resultCode);
                if (RC_FAILED(resultCode)) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Error while creating diff storage, rc=%08x"),
                                   resultCode.uResultCode);
                    goto cleanup;
                }
                VBOX_RELEASE(progress);
                /*
                 * The differential disk is created, we add it to the media registry and
                 * the machine storage controller.
                 */

                if (VIR_ALLOC(disk) < 0)
                    goto cleanup;

                rc = gVBoxAPI.UIMedium.GetId(newMedium, &iid);
                if (NS_FAILED(rc)) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unable to get medium uuid, rc=%08x"),
                                   (unsigned)rc);
                    VIR_FREE(disk);
                    goto cleanup;
                }
                gVBoxAPI.UIID.vboxIIDToUtf8(data, &iid, &uuid);
                disk->uuid = uuid;
                vboxIIDUnalloc(&iid);

                if (VIR_STRDUP(disk->location, newLocationUtf8) < 0) {
                    VIR_FREE(disk);
                    goto cleanup;
                }

                rc = gVBoxAPI.UIMedium.GetFormat(newMedium, &formatUtf16);
                VBOX_UTF16_TO_UTF8(formatUtf16, &format);
                disk->format = format;
                VBOX_UTF16_FREE(formatUtf16);

                if (virVBoxSnapshotConfAddHardDiskToMediaRegistry(disk,
                                               snapshotMachineDesc->mediaRegistry,
                                               parentUuid) < 0) {
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("Unable to add hard disk to the media registry"));
                    goto cleanup;
                }
                /*Adding fake disks to the machine storage controllers*/

                resultSize = virStringSearch(snapshotMachineDesc->storageController,
                                             VBOX_UUID_REGEX,
                                             it + 1,
                                             &searchResultTab);
                if (resultSize != it + 1) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unable to find UUID %s"), searchResultTab[it]);
                    goto cleanup;
                }

                tmp = virStringReplace(snapshotMachineDesc->storageController,
                                       searchResultTab[it],
                                       disk->uuid);
                VIR_FREE(snapshotMachineDesc->storageController);
                if (!tmp)
                    goto cleanup;
                if (VIR_STRDUP(snapshotMachineDesc->storageController, tmp) < 0)
                    goto cleanup;

                VIR_FREE(tmp);
                /*Closing the "fake" disk*/
                rc = gVBoxAPI.UIMedium.Close(newMedium);
                if (NS_FAILED(rc)) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unable to close the new medium, rc=%08x"),
                                   (unsigned)rc);
                    goto cleanup;
                }
            }
        } else {
7163
            for (it = 0; it < def->parent.dom->ndisks; it++) {
T
Taowei 已提交
7164 7165 7166
                const char *uuidRO = NULL;
                char *tmp = NULL;
                uuidRO = virVBoxSnapshotConfHardDiskUuidByLocation(snapshotMachineDesc,
7167
                                                      def->parent.dom->disks[it]->src->path);
T
Taowei 已提交
7168 7169 7170
                if (!uuidRO) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("No such disk in media registry %s"),
7171
                                   def->parent.dom->disks[it]->src->path);
T
Taowei 已提交
7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215
                    goto cleanup;
                }

                resultSize = virStringSearch(snapshotMachineDesc->storageController,
                                             VBOX_UUID_REGEX,
                                             it + 1,
                                             &searchResultTab);
                if (resultSize != it + 1) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unable to find UUID %s"),
                                   searchResultTab[it]);
                    goto cleanup;
                }

                tmp = virStringReplace(snapshotMachineDesc->storageController,
                                       searchResultTab[it],
                                       uuidRO);
                VIR_FREE(snapshotMachineDesc->storageController);
                if (!tmp)
                    goto cleanup;
                if (VIR_STRDUP(snapshotMachineDesc->storageController, tmp) < 0)
                    goto cleanup;

                VIR_FREE(tmp);
            }
        }
    }
    /*We remove the read write disks from the media registry*/
    for (it = 0; it < def->ndisks; it++) {
        const char *uuidRW =
            virVBoxSnapshotConfHardDiskUuidByLocation(snapshotMachineDesc,
                                                      def->disks[it].src->path);
        if (!uuidRW) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to find UUID for location %s"), def->disks[it].src->path);
            goto cleanup;
        }
        if (virVBoxSnapshotConfRemoveHardDisk(snapshotMachineDesc->mediaRegistry, uuidRW) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to remove disk from media registry. uuid = %s"), uuidRW);
            goto cleanup;
        }
    }
    /*If the parent snapshot is not NULL, we remove the-read only disks from the media registry*/
7216 7217
    if (def->parent.parent_name != NULL) {
        for (it = 0; it < def->parent.dom->ndisks; it++) {
T
Taowei 已提交
7218 7219
            const char *uuidRO =
                virVBoxSnapshotConfHardDiskUuidByLocation(snapshotMachineDesc,
7220
                                                          def->parent.dom->disks[it]->src->path);
T
Taowei 已提交
7221 7222
            if (!uuidRO) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
7223
                               _("Unable to find UUID for location %s"), def->parent.dom->disks[it]->src->path);
T
Taowei 已提交
7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280
                goto cleanup;
            }
            if (virVBoxSnapshotConfRemoveHardDisk(snapshotMachineDesc->mediaRegistry, uuidRO) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to remove disk from media registry. uuid = %s"), uuidRO);
                goto cleanup;
            }
        }
    }
    rc = gVBoxAPI.UIMachine.Unregister(machine,
                                       CleanupMode_DetachAllReturnHardDisksOnly,
                                       &aMediaSize,
                                       &aMedia);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to unregister machine, rc=%08x"),
                       (unsigned)rc);
        goto cleanup;
    }
    VBOX_RELEASE(machine);
    for (it = 0; it < aMediaSize; it++) {
        IMedium *medium = aMedia[it];
        PRUnichar *locationUtf16 = NULL;
        char *locationUtf8 = NULL;

        if (!medium)
            continue;

        rc = gVBoxAPI.UIMedium.GetLocation(medium, &locationUtf16);
        VBOX_UTF16_TO_UTF8(locationUtf16, &locationUtf8);
        if (isCurrent && strstr(locationUtf8, "fake") != NULL) {
            /*we delete the fake disk because we don't need it anymore*/
            IProgress *progress = NULL;
            resultCodeUnion resultCode;
            rc = gVBoxAPI.UIMedium.DeleteStorage(medium, &progress);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to delete medium, rc=%08x"),
                               (unsigned)rc);
                goto cleanup;
            }
            gVBoxAPI.UIProgress.WaitForCompletion(progress, -1);
            gVBoxAPI.UIProgress.GetResultCode(progress, &resultCode);
            if (RC_FAILED(resultCode)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Error while closing medium, rc=%08x"),
                               resultCode.uResultCode);
                goto cleanup;
            }
            VBOX_RELEASE(progress);
        } else {
            /* This a comment from vboxmanage code in the handleUnregisterVM
             * function in VBoxManageMisc.cpp :
             * Note that the IMachine::Unregister method will return the medium
             * reference in a sane order, which means that closing will normally
             * succeed, unless there is still another machine which uses the
             * medium. No harm done if we ignore the error. */
7281
            ignore_value(gVBoxAPI.UIMedium.Close(medium));
T
Taowei 已提交
7282 7283 7284 7285 7286 7287
        }
        VBOX_UTF16_FREE(locationUtf16);
        VBOX_UTF8_FREE(locationUtf8);
    }

    /*removing the snapshot*/
7288
    if (virVBoxSnapshotConfRemoveSnapshot(snapshotMachineDesc, def->parent.name) < 0) {
T
Taowei 已提交
7289
        virReportError(VIR_ERR_INTERNAL_ERROR,
7290
                       _("Unable to remove snapshot %s"), def->parent.name);
T
Taowei 已提交
7291 7292 7293 7294 7295
        goto cleanup;
    }

    if (isCurrent) {
        VIR_FREE(snapshotMachineDesc->currentSnapshot);
7296 7297
        if (def->parent.parent_name != NULL) {
            virVBoxSnapshotConfSnapshotPtr snap = virVBoxSnapshotConfSnapshotByName(snapshotMachineDesc->snapshot, def->parent.parent_name);
T
Taowei 已提交
7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338
            if (!snap) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to get the snapshot to remove"));
                goto cleanup;
            }
            if (VIR_STRDUP(snapshotMachineDesc->currentSnapshot, snap->uuid) < 0)
                goto cleanup;
        }
    }

    /*Registering the machine*/
    if (virVBoxSnapshotConfSaveVboxFile(snapshotMachineDesc, settingsFilepath) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to serialize the machine description"));
        goto cleanup;
    }
    rc = gVBoxAPI.UIVirtualBox.OpenMachine(data->vboxObj,
                                           settingsFilePathUtf16,
                                           &machine);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to open Machine, rc=%08x"),
                       (unsigned)rc);
        goto cleanup;
    }

    rc = gVBoxAPI.UIVirtualBox.RegisterMachine(data->vboxObj, machine);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to register Machine, rc=%08x"),
                       (unsigned)rc);
        goto cleanup;
    }

    ret = 0;
 cleanup:
    VIR_FREE(def);
    VIR_FREE(defXml);
    VBOX_RELEASE(machine);
    VBOX_UTF16_FREE(settingsFilePathUtf16);
    VBOX_UTF8_FREE(settingsFilepath);
7339
    virStringListFree(searchResultTab);
T
Taowei 已提交
7340 7341 7342 7343 7344 7345 7346 7347 7348
    VIR_FREE(snapshotMachineDesc);
    VBOX_UTF16_FREE(machineNameUtf16);
    VBOX_UTF8_FREE(machineName);
    VIR_FREE(machineLocationPath);
    VIR_FREE(nameTmpUse);

    return ret;
}

T
Taowei 已提交
7349 7350
static int vboxDomainSnapshotDelete(virDomainSnapshotPtr snapshot,
                                    unsigned int flags)
T
Taowei 已提交
7351 7352
{
    virDomainPtr dom = snapshot->domain;
7353
    vboxDriverPtr data = dom->conn->privateData;
7354
    vboxIID domiid;
T
Taowei 已提交
7355 7356 7357 7358 7359 7360
    IMachine *machine = NULL;
    ISnapshot *snap = NULL;
    IConsole *console = NULL;
    PRUint32 state;
    nsresult rc;
    vboxArray snapChildren = VBOX_ARRAY_INITIALIZER;
T
Taowei Luo 已提交
7361 7362 7363 7364
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
7365 7366 7367 7368

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
                  VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY, -1);

7369
    if (openSessionForMachine(data, dom->uuid, &domiid, &machine) < 0)
T
Taowei 已提交
7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397
        goto cleanup;

    snap = vboxDomainSnapshotGet(data, dom, machine, snapshot->name);
    if (!snap)
        goto cleanup;

    rc = gVBoxAPI.UIMachine.GetState(machine, &state);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get domain state"));
        goto cleanup;
    }

    /* In case we just want to delete the metadata, we will edit the vbox file in order
     *to remove the node concerning the snapshot
    */
    if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY) {
        rc = gVBoxAPI.UArray.vboxArrayGet(&snapChildren, snap,
                             gVBoxAPI.UArray.handleSnapshotGetChildren(snap));
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("could not get snapshot children"));
            goto cleanup;
        }
        if (snapChildren.count != 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot delete metadata of a snapshot with children"));
            goto cleanup;
7398
        } else if (gVBoxAPI.vboxSnapshotRedefine) {
T
Taowei 已提交
7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431
            ret = vboxDomainSnapshotDeleteMetadataOnly(snapshot);
        }
        goto cleanup;
    }

    if (gVBoxAPI.machineStateChecker.Online(state)) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot delete snapshots of running domain"));
        goto cleanup;
    }

    rc = gVBoxAPI.UISession.Open(data, &domiid, machine);
    if (NS_SUCCEEDED(rc))
        rc = gVBoxAPI.UISession.GetConsole(data->vboxSession, &console);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not open VirtualBox session with domain %s"),
                       dom->name);
        goto cleanup;
    }

    if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN)
        ret = vboxDomainSnapshotDeleteTree(data, console, snap);
    else
        ret = vboxDomainSnapshotDeleteSingle(data, console, snap);

 cleanup:
    VBOX_RELEASE(console);
    VBOX_RELEASE(snap);
    vboxIIDUnalloc(&domiid);
    gVBoxAPI.UISession.Close(data->vboxSession);
    return ret;
}
T
Taowei 已提交
7432

T
Taowei 已提交
7433
static char *
T
Taowei 已提交
7434 7435 7436 7437 7438
vboxDomainScreenshot(virDomainPtr dom,
                     virStreamPtr st,
                     unsigned int screen,
                     unsigned int flags)
{
7439
    vboxDriverPtr data = dom->conn->privateData;
T
Taowei 已提交
7440
    IConsole *console = NULL;
7441
    vboxIID iid;
T
Taowei 已提交
7442 7443 7444
    IMachine *machine = NULL;
    nsresult rc;
    char *tmp;
7445
    char *cacheDir;
T
Taowei 已提交
7446 7447
    int tmp_fd = -1;
    unsigned int max_screen;
7448
    bool privileged = geteuid() == 0;
T
Taowei Luo 已提交
7449 7450 7451 7452
    char *ret = NULL;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
7453 7454 7455

    virCheckFlags(0, NULL);

7456
    if (openSessionForMachine(data, dom->uuid, &iid, &machine) < 0)
T
Taowei 已提交
7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474
        return NULL;

    rc = gVBoxAPI.UIMachine.GetMonitorCount(machine, &max_screen);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("unable to get monitor count"));
        VBOX_RELEASE(machine);
        return NULL;
    }

    if (screen >= max_screen) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("screen ID higher than monitor "
                         "count (%d)"), max_screen);
        VBOX_RELEASE(machine);
        return NULL;
    }

7475 7476
    if ((privileged && virAsprintf(&cacheDir, "%s/cache/libvirt", LOCALSTATEDIR) < 0) ||
        (!privileged && !(cacheDir = virGetUserCacheDirectory()))) {
T
Taowei 已提交
7477 7478 7479 7480
        VBOX_RELEASE(machine);
        return NULL;
    }

7481 7482 7483 7484 7485 7486
    if (virAsprintf(&tmp, "%s/vbox.screendump.XXXXXX", cacheDir) < 0) {
        VBOX_RELEASE(machine);
        VIR_FREE(cacheDir);
        return NULL;
    }

T
Taowei 已提交
7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561
    if ((tmp_fd = mkostemp(tmp, O_CLOEXEC)) == -1) {
        virReportSystemError(errno, _("mkostemp(\"%s\") failed"), tmp);
        VIR_FREE(tmp);
        VBOX_RELEASE(machine);
        return NULL;
    }


    rc = gVBoxAPI.UISession.OpenExisting(data, &iid, machine);
    if (NS_SUCCEEDED(rc)) {
        rc = gVBoxAPI.UISession.GetConsole(data->vboxSession, &console);
        if (NS_SUCCEEDED(rc) && console) {
            IDisplay *display = NULL;

            gVBoxAPI.UIConsole.GetDisplay(console, &display);

            if (display) {
                PRUint32 width, height, bitsPerPixel;
                PRUint32 screenDataSize;
                PRUint8 *screenData;
                PRInt32 xOrigin, yOrigin;

                rc = gVBoxAPI.UIDisplay.GetScreenResolution(display, screen,
                                                            &width, &height,
                                                            &bitsPerPixel,
                                                            &xOrigin, &yOrigin);

                if (NS_FAILED(rc) || !width || !height) {
                    virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                                   _("unable to get screen resolution"));
                    goto endjob;
                }

                rc = gVBoxAPI.UIDisplay.TakeScreenShotPNGToArray(display, screen,
                                                                 width, height,
                                                                 &screenDataSize,
                                                                 &screenData);
                if (NS_FAILED(rc)) {
                    virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                                   _("failed to take screenshot"));
                    goto endjob;
                }

                if (safewrite(tmp_fd, (char *) screenData,
                              screenDataSize) < 0) {
                    virReportSystemError(errno, _("unable to write data "
                                                  "to '%s'"), tmp);
                    goto endjob;
                }

                if (VIR_CLOSE(tmp_fd) < 0) {
                    virReportSystemError(errno, _("unable to close %s"), tmp);
                    goto endjob;
                }

                if (VIR_STRDUP(ret, "image/png") < 0)
                    goto endjob;

                if (virFDStreamOpenFile(st, tmp, 0, 0, O_RDONLY) < 0) {
                    virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                                   _("unable to open stream"));
                    VIR_FREE(ret);
                }
 endjob:
                VIR_FREE(screenData);
                VBOX_RELEASE(display);
            }
            VBOX_RELEASE(console);
        }
        gVBoxAPI.UISession.Close(data->vboxSession);
    }

    VIR_FORCE_CLOSE(tmp_fd);
    unlink(tmp);
    VIR_FREE(tmp);
7562
    VIR_FREE(cacheDir);
T
Taowei 已提交
7563 7564 7565 7566
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}
T
Taowei 已提交
7567 7568

#define MATCH(FLAG) (flags & (FLAG))
T
Taowei 已提交
7569
static int
T
Taowei 已提交
7570 7571 7572 7573
vboxConnectListAllDomains(virConnectPtr conn,
                          virDomainPtr **domains,
                          unsigned int flags)
{
7574
    vboxDriverPtr data = conn->privateData;
T
Taowei 已提交
7575
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
7576
    char *machineNameUtf8 = NULL;
T
Taowei 已提交
7577 7578
    PRUnichar *machineNameUtf16 = NULL;
    unsigned char uuid[VIR_UUID_BUFLEN];
7579
    vboxIID iid;
T
Taowei 已提交
7580 7581 7582 7583 7584 7585 7586 7587
    PRUint32 state;
    nsresult rc;
    size_t i;
    virDomainPtr dom;
    virDomainPtr *doms = NULL;
    int count = 0;
    bool active;
    PRUint32 snapshotCount;
T
Taowei Luo 已提交
7588 7589 7590 7591
    int ret = -1;

    if (!data->vboxObj)
        return ret;
T
Taowei 已提交
7592 7593 7594 7595 7596 7597

    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);

    /* filter out flag options that will produce 0 results in vbox driver:
     * - managed save: vbox guests don't have managed save images
     * - autostart: vbox doesn't support autostarting guests
M
Martin Kletzander 已提交
7598
     * - persistence: vbox doesn't support transient guests
T
Taowei 已提交
7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626
     */
    if ((MATCH(VIR_CONNECT_LIST_DOMAINS_TRANSIENT) &&
         !MATCH(VIR_CONNECT_LIST_DOMAINS_PERSISTENT)) ||
        (MATCH(VIR_CONNECT_LIST_DOMAINS_AUTOSTART) &&
         !MATCH(VIR_CONNECT_LIST_DOMAINS_NO_AUTOSTART)) ||
        (MATCH(VIR_CONNECT_LIST_DOMAINS_MANAGEDSAVE) &&
         !MATCH(VIR_CONNECT_LIST_DOMAINS_NO_MANAGEDSAVE))) {
        if (domains &&
            VIR_ALLOC_N(*domains, 1) < 0)
            goto cleanup;

        ret = 0;
        goto cleanup;
    }

    rc = gVBoxAPI.UArray.vboxArrayGet(&machines, data->vboxObj, ARRAY_GET_MACHINES);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of domains, rc=%08x"), (unsigned)rc);
        goto cleanup;
    }

    if (domains &&
        VIR_ALLOC_N(doms, machines.count + 1) < 0)
        goto cleanup;

    for (i = 0; i < machines.count; i++) {
        IMachine *machine = machines.items[i];
7627
        int id = -1;
T
Taowei 已提交
7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691

        if (!machine)
            continue;

        PRBool isAccessible = PR_FALSE;
        gVBoxAPI.UIMachine.GetAccessible(machine, &isAccessible);

        if (!isAccessible)
            continue;

      gVBoxAPI.UIMachine.GetState(machine, &state);

      if (gVBoxAPI.machineStateChecker.Online(state))
          active = true;
      else
          active = false;

      /* filter by active state */
      if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_ACTIVE) &&
          !((MATCH(VIR_CONNECT_LIST_DOMAINS_ACTIVE) && active) ||
            (MATCH(VIR_CONNECT_LIST_DOMAINS_INACTIVE) && !active)))
          continue;

      /* filter by snapshot existence */
      if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_SNAPSHOT)) {
          rc = gVBoxAPI.UIMachine.GetSnapshotCount(machine, &snapshotCount);
          if (NS_FAILED(rc)) {
              virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                             _("could not get snapshot count for listed domains"));
              goto cleanup;
          }
          if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT) &&
                 snapshotCount > 0) ||
                (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT) &&
                 snapshotCount == 0)))
              continue;
      }

      /* filter by machine state */
      if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_STATE) &&
          !((MATCH(VIR_CONNECT_LIST_DOMAINS_RUNNING) &&
             gVBoxAPI.machineStateChecker.Running(state)) ||
            (MATCH(VIR_CONNECT_LIST_DOMAINS_PAUSED) &&
             gVBoxAPI.machineStateChecker.Paused(state)) ||
            (MATCH(VIR_CONNECT_LIST_DOMAINS_SHUTOFF) &&
             gVBoxAPI.machineStateChecker.PoweredOff(state)) ||
            (MATCH(VIR_CONNECT_LIST_DOMAINS_OTHER) &&
             (!gVBoxAPI.machineStateChecker.Running(state) &&
              !gVBoxAPI.machineStateChecker.Paused(state) &&
              !gVBoxAPI.machineStateChecker.PoweredOff(state)))))
          continue;

      /* just count the machines */
      if (!doms) {
          count++;
          continue;
      }

      gVBoxAPI.UIMachine.GetName(machine, &machineNameUtf16);
      VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);
      gVBoxAPI.UIMachine.GetId(machine, &iid);
      vboxIIDToUUID(&iid, uuid);
      vboxIIDUnalloc(&iid);

7692 7693 7694 7695
      if (active)
          id = i + 1;

      dom = virGetDomain(conn, machineNameUtf8, uuid, id);
T
Taowei 已提交
7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717

      VBOX_UTF8_FREE(machineNameUtf8);
      VBOX_UTF16_FREE(machineNameUtf16);

      if (!dom)
          goto cleanup;

      doms[count++] = dom;
    }

    if (doms) {
        /* safe to ignore, new size will be equal or less than
         * previous allocation*/
        ignore_value(VIR_REALLOC_N(doms, count + 1));
        *domains = doms;
        doms = NULL;
    }

    ret = count;

 cleanup:
    if (doms) {
7718 7719
        for (i = 0; i < count; i++)
            virObjectUnref(doms[i]);
T
Taowei 已提交
7720 7721 7722 7723 7724 7725 7726
    }
    VIR_FREE(doms);

    gVBoxAPI.UArray.vboxArrayRelease(&machines);
    return ret;
}
#undef MATCH
T
Taowei 已提交
7727

T
Taowei 已提交
7728
static int
T
Taowei 已提交
7729 7730 7731
vboxNodeGetInfo(virConnectPtr conn ATTRIBUTE_UNUSED,
                virNodeInfoPtr nodeinfo)
{
M
Martin Kletzander 已提交
7732
    return virCapabilitiesGetNodeInfo(nodeinfo);
T
Taowei 已提交
7733 7734
}

T
Taowei 已提交
7735
static int
T
Taowei 已提交
7736 7737 7738 7739 7740
vboxNodeGetCellsFreeMemory(virConnectPtr conn ATTRIBUTE_UNUSED,
                           unsigned long long *freeMems,
                           int startCell,
                           int maxCells)
{
7741
    return virHostMemGetCellsFree(freeMems, startCell, maxCells);
T
Taowei 已提交
7742 7743
}

T
Taowei 已提交
7744
static unsigned long long
T
Taowei 已提交
7745 7746 7747
vboxNodeGetFreeMemory(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    unsigned long long freeMem;
7748
    if (virHostMemGetInfo(NULL, &freeMem) < 0)
T
Taowei 已提交
7749 7750 7751 7752
        return 0;
    return freeMem;
}

T
Taowei 已提交
7753
static int
T
Taowei 已提交
7754 7755 7756 7757 7758 7759 7760 7761 7762 7763
vboxNodeGetFreePages(virConnectPtr conn ATTRIBUTE_UNUSED,
                     unsigned int npages,
                     unsigned int *pages,
                     int startCell,
                     unsigned int cellCount,
                     unsigned long long *counts,
                     unsigned int flags)
{
    virCheckFlags(0, -1);

7764
    return virHostMemGetFreePages(npages, pages, startCell, cellCount, counts);
T
Taowei 已提交
7765
}
T
Taowei 已提交
7766

7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779
static int
vboxNodeAllocPages(virConnectPtr conn ATTRIBUTE_UNUSED,
                   unsigned int npages,
                   unsigned int *pageSizes,
                   unsigned long long *pageCounts,
                   int startCell,
                   unsigned int cellCount,
                   unsigned int flags)
{
    bool add = !(flags & VIR_NODE_ALLOC_PAGES_SET);

    virCheckFlags(VIR_NODE_ALLOC_PAGES_SET, -1);

7780 7781
    return virHostMemAllocPages(npages, pageSizes, pageCounts,
                                startCell, cellCount, add);
7782 7783
}

7784 7785 7786
static int
vboxDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags)
{
7787
    vboxDriverPtr data = dom->conn->privateData;
7788
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
7789
    vboxIID iid;
7790
    char *machineNameUtf8 = NULL;
7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853
    PRUnichar *machineNameUtf16 = NULL;
    unsigned char uuid[VIR_UUID_BUFLEN];
    size_t i;
    bool matched = false;
    nsresult rc;
    int ret = -1;

    virCheckFlags(0, -1);

    if (!data->vboxObj)
        return ret;

    VBOX_IID_INITIALIZE(&iid);
    rc = gVBoxAPI.UArray.vboxArrayGet(&machines, data->vboxObj, ARRAY_GET_MACHINES);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of machines, rc=%08x"), (unsigned)rc);
        return ret;
    }

    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
        PRBool isAccessible = PR_FALSE;

        if (!machine)
            continue;

        gVBoxAPI.UIMachine.GetAccessible(machine, &isAccessible);
        if (!isAccessible)
            continue;

        gVBoxAPI.UIMachine.GetId(machine, &iid);
        if (NS_FAILED(rc))
            continue;
        vboxIIDToUUID(&iid, uuid);
        vboxIIDUnalloc(&iid);

        if (memcmp(dom->uuid, uuid, VIR_UUID_BUFLEN) == 0) {

            PRUint32 state;

            matched = true;

            gVBoxAPI.UIMachine.GetName(machine, &machineNameUtf16);
            VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);

            gVBoxAPI.UIMachine.GetState(machine, &state);

            ret = 0;
        }

        if (matched)
            break;
    }

    /* Do the cleanup and take care you dont leak any memory */
    VBOX_UTF8_FREE(machineNameUtf8);
    VBOX_COM_UNALLOC_MEM(machineNameUtf16);
    gVBoxAPI.UArray.vboxArrayRelease(&machines);

    return ret;
}

7854 7855 7856 7857 7858 7859 7860 7861 7862
static int
vboxDomainSendKey(virDomainPtr dom,
                  unsigned int codeset,
                  unsigned int holdtime,
                  unsigned int *keycodes,
                  int nkeycodes,
                  unsigned int flags)
{
    int ret = -1;
7863
    vboxDriverPtr data = dom->conn->privateData;
7864
    IConsole *console = NULL;
7865
    vboxIID iid;
7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903
    IMachine *machine = NULL;
    IKeyboard *keyboard = NULL;
    PRInt32 *keyDownCodes = NULL;
    PRInt32 *keyUpCodes = NULL;
    PRUint32 codesStored = 0;
    nsresult rc;
    size_t i;
    int keycode;

    if (!data->vboxObj)
        return ret;

    virCheckFlags(0, -1);

    keyDownCodes = (PRInt32 *) keycodes;

    if (VIR_ALLOC_N(keyUpCodes, nkeycodes) < 0)
        return ret;

    /* translate keycodes to xt and generate keyup scancodes */
    for (i = 0; i < nkeycodes; i++) {
        if (codeset != VIR_KEYCODE_SET_XT) {
            keycode = virKeycodeValueTranslate(codeset, VIR_KEYCODE_SET_XT,
                                               keyDownCodes[i]);
            if (keycode < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("cannot translate keycode %u of %s codeset to"
                                 " xt keycode"),
                                 keyDownCodes[i],
                                 virKeycodeSetTypeToString(codeset));
                goto cleanup;
            }
            keyDownCodes[i] = keycode;
        }

        keyUpCodes[i] = keyDownCodes[i] + 0x80;
    }

7904
    if (openSessionForMachine(data, dom->uuid, &iid, &machine) < 0)
7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971
        goto cleanup;

    rc = gVBoxAPI.UISession.OpenExisting(data, &iid, machine);

    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Unable to open VirtualBox session with domain %s"),
                       dom->name);
        goto cleanup;
    }

    rc = gVBoxAPI.UISession.GetConsole(data->vboxSession, &console);

    if (NS_FAILED(rc) || !console) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Unable to get Console object for domain %s"),
                       dom->name);
        goto cleanup;
    }

    rc = gVBoxAPI.UIConsole.GetKeyboard(console, &keyboard);

    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Unable to get Keyboard object for domain %s"),
                       dom->name);
        goto cleanup;
    }

    rc = gVBoxAPI.UIKeyboard.PutScancodes(keyboard, nkeycodes, keyDownCodes,
                                          &codesStored);

    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Unable to send keyboard scancodes for domain %s"),
                       dom->name);
        goto cleanup;
    }

    /* since VBOX does not support holdtime, simulate it by sleeping and
       then sending the release key scancodes */
    if (holdtime > 0)
        usleep(holdtime * 1000);

    rc = gVBoxAPI.UIKeyboard.PutScancodes(keyboard, nkeycodes, keyUpCodes,
                                          &codesStored);

    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Unable to send keyboard scan codes to domain %s"),
                       dom->name);
        goto cleanup;
    }

    ret = 0;

 cleanup:
    VIR_FREE(keyUpCodes);
    VBOX_RELEASE(keyboard);
    VBOX_RELEASE(console);
    gVBoxAPI.UISession.Close(data->vboxSession);
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);

    return ret;
}

7972

T
Taowei 已提交
7973 7974 7975 7976
/**
 * Function Tables
 */

7977
static virHypervisorDriver vboxCommonDriver = {
T
Taowei 已提交
7978
    .name = "VBOX",
7979
    .connectURIProbe = vboxConnectURIProbe,
T
Taowei 已提交
7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015
    .connectOpen = vboxConnectOpen, /* 0.6.3 */
    .connectClose = vboxConnectClose, /* 0.6.3 */
    .connectGetVersion = vboxConnectGetVersion, /* 0.6.3 */
    .connectGetHostname = vboxConnectGetHostname, /* 0.6.3 */
    .connectGetMaxVcpus = vboxConnectGetMaxVcpus, /* 0.6.3 */
    .nodeGetInfo = vboxNodeGetInfo, /* 0.6.3 */
    .connectGetCapabilities = vboxConnectGetCapabilities, /* 0.6.3 */
    .connectListDomains = vboxConnectListDomains, /* 0.6.3 */
    .connectNumOfDomains = vboxConnectNumOfDomains, /* 0.6.3 */
    .connectListAllDomains = vboxConnectListAllDomains, /* 0.9.13 */
    .domainCreateXML = vboxDomainCreateXML, /* 0.6.3 */
    .domainLookupByID = vboxDomainLookupByID, /* 0.6.3 */
    .domainLookupByUUID = vboxDomainLookupByUUID, /* 0.6.3 */
    .domainLookupByName = vboxDomainLookupByName, /* 0.6.3 */
    .domainSuspend = vboxDomainSuspend, /* 0.6.3 */
    .domainResume = vboxDomainResume, /* 0.6.3 */
    .domainShutdown = vboxDomainShutdown, /* 0.6.3 */
    .domainShutdownFlags = vboxDomainShutdownFlags, /* 0.9.10 */
    .domainReboot = vboxDomainReboot, /* 0.6.3 */
    .domainDestroy = vboxDomainDestroy, /* 0.6.3 */
    .domainDestroyFlags = vboxDomainDestroyFlags, /* 0.9.4 */
    .domainGetOSType = vboxDomainGetOSType, /* 0.6.3 */
    .domainSetMemory = vboxDomainSetMemory, /* 0.6.3 */
    .domainGetInfo = vboxDomainGetInfo, /* 0.6.3 */
    .domainGetState = vboxDomainGetState, /* 0.9.2 */
    .domainSave = vboxDomainSave, /* 0.6.3 */
    .domainSetVcpus = vboxDomainSetVcpus, /* 0.7.1 */
    .domainSetVcpusFlags = vboxDomainSetVcpusFlags, /* 0.8.5 */
    .domainGetVcpusFlags = vboxDomainGetVcpusFlags, /* 0.8.5 */
    .domainGetMaxVcpus = vboxDomainGetMaxVcpus, /* 0.7.1 */
    .domainGetXMLDesc = vboxDomainGetXMLDesc, /* 0.6.3 */
    .connectListDefinedDomains = vboxConnectListDefinedDomains, /* 0.6.3 */
    .connectNumOfDefinedDomains = vboxConnectNumOfDefinedDomains, /* 0.6.3 */
    .domainCreate = vboxDomainCreate, /* 0.6.3 */
    .domainCreateWithFlags = vboxDomainCreateWithFlags, /* 0.8.2 */
    .domainDefineXML = vboxDomainDefineXML, /* 0.6.3 */
8016
    .domainDefineXMLFlags = vboxDomainDefineXMLFlags, /* 1.2.12 */
T
Taowei 已提交
8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044
    .domainUndefine = vboxDomainUndefine, /* 0.6.3 */
    .domainUndefineFlags = vboxDomainUndefineFlags, /* 0.9.5 */
    .domainAttachDevice = vboxDomainAttachDevice, /* 0.6.3 */
    .domainAttachDeviceFlags = vboxDomainAttachDeviceFlags, /* 0.7.7 */
    .domainDetachDevice = vboxDomainDetachDevice, /* 0.6.3 */
    .domainDetachDeviceFlags = vboxDomainDetachDeviceFlags, /* 0.7.7 */
    .domainUpdateDeviceFlags = vboxDomainUpdateDeviceFlags, /* 0.8.0 */
    .nodeGetCellsFreeMemory = vboxNodeGetCellsFreeMemory, /* 0.6.5 */
    .nodeGetFreeMemory = vboxNodeGetFreeMemory, /* 0.6.5 */
    .connectIsEncrypted = vboxConnectIsEncrypted, /* 0.7.3 */
    .connectIsSecure = vboxConnectIsSecure, /* 0.7.3 */
    .domainIsActive = vboxDomainIsActive, /* 0.7.3 */
    .domainIsPersistent = vboxDomainIsPersistent, /* 0.7.3 */
    .domainIsUpdated = vboxDomainIsUpdated, /* 0.8.6 */
    .domainSnapshotCreateXML = vboxDomainSnapshotCreateXML, /* 0.8.0 */
    .domainSnapshotGetXMLDesc = vboxDomainSnapshotGetXMLDesc, /* 0.8.0 */
    .domainSnapshotNum = vboxDomainSnapshotNum, /* 0.8.0 */
    .domainSnapshotListNames = vboxDomainSnapshotListNames, /* 0.8.0 */
    .domainSnapshotLookupByName = vboxDomainSnapshotLookupByName, /* 0.8.0 */
    .domainHasCurrentSnapshot = vboxDomainHasCurrentSnapshot, /* 0.8.0 */
    .domainSnapshotGetParent = vboxDomainSnapshotGetParent, /* 0.9.7 */
    .domainSnapshotCurrent = vboxDomainSnapshotCurrent, /* 0.8.0 */
    .domainSnapshotIsCurrent = vboxDomainSnapshotIsCurrent, /* 0.9.13 */
    .domainSnapshotHasMetadata = vboxDomainSnapshotHasMetadata, /* 0.9.13 */
    .domainRevertToSnapshot = vboxDomainRevertToSnapshot, /* 0.8.0 */
    .domainSnapshotDelete = vboxDomainSnapshotDelete, /* 0.8.0 */
    .connectIsAlive = vboxConnectIsAlive, /* 0.9.8 */
    .nodeGetFreePages = vboxNodeGetFreePages, /* 1.2.6 */
8045
    .nodeAllocPages = vboxNodeAllocPages, /* 1.2.9 */
8046
    .domainHasManagedSaveImage = vboxDomainHasManagedSaveImage, /* 1.2.13 */
8047
    .domainSendKey = vboxDomainSendKey, /* 1.2.15 */
8048
    .domainScreenshot = vboxDomainScreenshot, /* 0.9.2 */
T
Taowei 已提交
8049 8050
};

8051
virHypervisorDriverPtr vboxGetHypervisorDriver(uint32_t uVersion)
T
Taowei 已提交
8052
{
8053 8054 8055
    /* Install gVBoxAPI according to the vbox API version. */
    int result = 0;
    installUniformedAPI(gVBoxAPI, result);
8056 8057 8058 8059 8060
    if (result < 0) {
        VIR_WARN("Libvirt doesn't support VirtualBox API version %u",
                 uVersion);
        return NULL;
    }
8061

T
Taowei 已提交
8062 8063
    return &vboxCommonDriver;
}