esx_driver.c 133.9 KB
Newer Older
1 2

/*
3
 * esx_driver.c: core driver functions for managing VMware ESX hosts
4
 *
E
Eric Blake 已提交
5
 * Copyright (C) 2010 Red Hat, Inc.
6
 * Copyright (C) 2009-2010 Matthias Bolte <matthias.bolte@googlemail.com>
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
 * Copyright (C) 2009 Maximilian Wilhelm <max@rfc2324.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 */

#include <config.h>

#include <netdb.h>

#include "internal.h"
#include "domain_conf.h"
31
#include "authhelper.h"
32 33 34 35 36
#include "util.h"
#include "memory.h"
#include "logging.h"
#include "uuid.h"
#include "esx_driver.h"
37 38 39 40 41
#include "esx_interface_driver.h"
#include "esx_network_driver.h"
#include "esx_storage_driver.h"
#include "esx_device_monitor.h"
#include "esx_secret_driver.h"
M
Matthias Bolte 已提交
42
#include "esx_nwfilter_driver.h"
43
#include "esx_private.h"
44 45 46 47 48 49 50 51 52
#include "esx_vi.h"
#include "esx_vi_methods.h"
#include "esx_util.h"
#include "esx_vmx.h"

#define VIR_FROM_THIS VIR_FROM_ESX

static int esxDomainGetMaxVcpus(virDomainPtr domain);

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 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 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
typedef struct _esxVMX_Data esxVMX_Data;

struct _esxVMX_Data {
    esxVI_Context *ctx;
    const char *datastoreName;
    const char *directoryName;
};



static char *
esxAbsolutePathToDatastorePath(esxVI_Context *ctx, const char *absolutePath)
{
    bool success = false;
    char *copyOfAbsolutePath = NULL;
    char *tmp = NULL;
    char *saveptr = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *datastore = NULL;

    char *datastorePath = NULL;
    char *preliminaryDatastoreName = NULL;
    char *directoryAndFileName = NULL;
    char *datastoreName = NULL;

    if (esxVI_String_DeepCopyValue(&copyOfAbsolutePath, absolutePath) < 0) {
        return NULL;
    }

    /* Expected format: '/vmfs/volumes/<datastore>/<path>' */
    if ((tmp = STRSKIP(copyOfAbsolutePath, "/vmfs/volumes/")) == NULL ||
        (preliminaryDatastoreName = strtok_r(tmp, "/", &saveptr)) == NULL ||
        (directoryAndFileName = strtok_r(NULL, "", &saveptr)) == NULL) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Absolute path '%s' doesn't have expected format "
                    "'/vmfs/volumes/<datastore>/<path>'"), absolutePath);
        goto cleanup;
    }

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "summary.name") < 0 ||
        esxVI_LookupDatastoreByAbsolutePath(ctx, absolutePath,
                                            propertyNameList, &datastore,
                                            esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
    }

    if (datastore == NULL) {
        if (esxVI_LookupDatastoreByName(ctx, preliminaryDatastoreName,
                                        propertyNameList, &datastore,
                                        esxVI_Occurrence_OptionalItem) < 0) {
            goto cleanup;
        }
    }

    if (datastore != NULL) {
        if (esxVI_GetStringValue(datastore, "summary.name", &datastoreName,
                                 esxVI_Occurrence_RequiredItem)) {
            goto cleanup;
        }
    }

    if (datastoreName == NULL) {
        VIR_WARN("Could not retrieve datastore name for absolute "
                 "path '%s', falling back to preliminary name '%s'",
                 absolutePath, preliminaryDatastoreName);

        datastoreName = preliminaryDatastoreName;
    }

    if (virAsprintf(&datastorePath, "[%s] %s", datastoreName,
                    directoryAndFileName) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    /* FIXME: Check if referenced path/file really exists */

    success = true;

  cleanup:
    if (! success) {
        VIR_FREE(datastorePath);
    }

    VIR_FREE(copyOfAbsolutePath);
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&datastore);

    return datastorePath;
}



static char *
esxParseVMXFileName(const char *fileName, void *opaque)
{
    char *src = NULL;
    esxVMX_Data *data = opaque;

    if (STRPREFIX(fileName, "/vmfs/volumes/")) {
        /* Found absolute path referencing a file inside a datastore */
        return esxAbsolutePathToDatastorePath(data->ctx, fileName);
    } else if (STRPREFIX(fileName, "/")) {
        /* Found absolute path referencing a file outside a datastore */
        src = strdup(fileName);

        if (src == NULL) {
            virReportOOMError();
            return NULL;
        }

        /* FIXME: Check if referenced path/file really exists */

        return src;
    } else if (strchr(fileName, '/') != NULL) {
        /* Found relative path, this is not supported */
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Found relative path '%s' in VMX file, this is not "
                    "supported"), fileName);
        return NULL;
    } else {
        /* Found single file name referencing a file inside a datastore */
        if (virAsprintf(&src, "[%s] %s/%s", data->datastoreName,
                        data->directoryName, fileName) < 0) {
            virReportOOMError();
            return NULL;
        }

        /* FIXME: Check if referenced path/file really exists */

        return src;
    }
}



static char *
esxFormatVMXFileName(const char *src, void *opaque ATTRIBUTE_UNUSED)
{
    bool success = false;
    char *datastoreName = NULL;
    char *directoryName = NULL;
    char *fileName = NULL;
    char *absolutePath = NULL;

    if (STRPREFIX(src, "[")) {
        /* Found potential datastore path */
        if (esxUtil_ParseDatastorePath(src, &datastoreName, &directoryName,
                                       &fileName) < 0) {
            goto cleanup;
        }

        if (directoryName == NULL) {
            if (virAsprintf(&absolutePath, "/vmfs/volumes/%s/%s",
                            datastoreName, fileName) < 0) {
                virReportOOMError();
                goto cleanup;
            }
        } else {
            if (virAsprintf(&absolutePath, "/vmfs/volumes/%s/%s/%s",
                            datastoreName, directoryName, fileName) < 0) {
                virReportOOMError();
                goto cleanup;
            }
        }
    } else if (STRPREFIX(src, "/")) {
        /* Found absolute path */
        absolutePath = strdup(src);

        if (absolutePath == NULL) {
            virReportOOMError();
            goto cleanup;
        }
    } else {
        /* Found relative path, this is not supported */
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Found relative path '%s' in domain XML, this is not "
                    "supported"), src);
        goto cleanup;
    }

    /* FIXME: Check if referenced path/file really exists */

    success = true;

  cleanup:
    if (! success) {
        VIR_FREE(absolutePath);
    }

    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
    VIR_FREE(fileName);

    return absolutePath;
}



static int
esxAutodetectSCSIControllerModel(virDomainDiskDefPtr def, int *model,
                                 void *opaque)
{
    int result = -1;
    esxVMX_Data *data = opaque;
    char *datastoreName = NULL;
    char *directoryName = NULL;
    char *fileName = NULL;
    char *datastorePath = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *datastore = NULL;
    esxVI_ManagedObjectReference *hostDatastoreBrowser = NULL;
    esxVI_HostDatastoreBrowserSearchSpec *searchSpec = NULL;
    esxVI_VmDiskFileQuery *vmDiskFileQuery = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
    esxVI_TaskInfo *taskInfo = NULL;
    esxVI_HostDatastoreBrowserSearchResults *searchResults = NULL;
    esxVI_VmDiskFileInfo *vmDiskFileInfo = NULL;

    if (def->device != VIR_DOMAIN_DISK_DEVICE_DISK ||
        def->bus != VIR_DOMAIN_DISK_BUS_SCSI ||
        def->type != VIR_DOMAIN_DISK_TYPE_FILE ||
        def->src == NULL ||
        ! STRPREFIX(def->src, "[")) {
        /*
         * This isn't a file-based SCSI disk device with a datastore related
         * source path => do nothing.
         */
        return 0;
    }

    if (esxUtil_ParseDatastorePath(def->src, &datastoreName, &directoryName,
                                   &fileName) < 0) {
        goto cleanup;
    }

    if (directoryName == NULL) {
        if (virAsprintf(&datastorePath, "[%s]", datastoreName) < 0) {
            virReportOOMError();
            goto cleanup;
        }
    } else {
        if (virAsprintf(&datastorePath, "[%s] %s", datastoreName,
                        directoryName) < 0) {
            virReportOOMError();
            goto cleanup;
        }
    }

    /* Lookup HostDatastoreBrowser */
    if (esxVI_String_AppendValueToList(&propertyNameList, "browser") < 0 ||
        esxVI_LookupDatastoreByName(data->ctx, datastoreName, propertyNameList,
                                    &datastore,
                                    esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_GetManagedObjectReference(datastore, "browser",
                                        &hostDatastoreBrowser,
                                        esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    /* Build HostDatastoreBrowserSearchSpec */
    if (esxVI_HostDatastoreBrowserSearchSpec_Alloc(&searchSpec) < 0 ||
        esxVI_FileQueryFlags_Alloc(&searchSpec->details) < 0) {
        goto cleanup;
    }

    searchSpec->details->fileType = esxVI_Boolean_True;
    searchSpec->details->fileSize = esxVI_Boolean_False;
    searchSpec->details->modification = esxVI_Boolean_False;

    if (esxVI_VmDiskFileQuery_Alloc(&vmDiskFileQuery) < 0 ||
        esxVI_VmDiskFileQueryFlags_Alloc(&vmDiskFileQuery->details) < 0 ||
        esxVI_FileQuery_AppendToList
          (&searchSpec->query,
           esxVI_FileQuery_DynamicCast(vmDiskFileQuery)) < 0) {
        goto cleanup;
    }

    vmDiskFileQuery->details->diskType = esxVI_Boolean_False;
    vmDiskFileQuery->details->capacityKb = esxVI_Boolean_False;
    vmDiskFileQuery->details->hardwareVersion = esxVI_Boolean_False;
    vmDiskFileQuery->details->controllerType = esxVI_Boolean_True;
    vmDiskFileQuery->details->diskExtents = esxVI_Boolean_False;

    if (esxVI_String_Alloc(&searchSpec->matchPattern) < 0) {
        goto cleanup;
    }

    searchSpec->matchPattern->value = fileName;

    /* Search datastore for file */
    if (esxVI_SearchDatastore_Task(data->ctx, hostDatastoreBrowser,
                                   datastorePath, searchSpec, &task) < 0 ||
        esxVI_WaitForTaskCompletion(data->ctx, task, NULL, esxVI_Occurrence_None,
                                    esxVI_Boolean_False, &taskInfoState) < 0) {
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not serach in datastore '%s'"), datastoreName);
        goto cleanup;
    }

    if (esxVI_LookupTaskInfoByTask(data->ctx, task, &taskInfo) < 0 ||
        esxVI_HostDatastoreBrowserSearchResults_CastFromAnyType
          (taskInfo->result, &searchResults) < 0) {
        goto cleanup;
    }

    /* Interpret search result */
    vmDiskFileInfo = esxVI_VmDiskFileInfo_DynamicCast(searchResults->file);

    if (vmDiskFileInfo == NULL || vmDiskFileInfo->controllerType == NULL) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not lookup controller model for '%s'"), def->src);
        goto cleanup;
    }

    if (STRCASEEQ(vmDiskFileInfo->controllerType,
                  "VirtualBusLogicController")) {
        *model = VIR_DOMAIN_CONTROLLER_MODEL_BUSLOGIC;
    } else if (STRCASEEQ(vmDiskFileInfo->controllerType,
                         "VirtualLsiLogicController")) {
        *model = VIR_DOMAIN_CONTROLLER_MODEL_LSILOGIC;
    } else if (STRCASEEQ(vmDiskFileInfo->controllerType,
                         "VirtualLsiLogicSASController")) {
        *model = VIR_DOMAIN_CONTROLLER_MODEL_LSISAS1068;
    } else if (STRCASEEQ(vmDiskFileInfo->controllerType,
                         "ParaVirtualSCSIController")) {
        *model = VIR_DOMAIN_CONTROLLER_MODEL_VMPVSCSI;
    } else {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Found unexpected controller model '%s' for disk '%s'"),
                  vmDiskFileInfo->controllerType, def->src);
        goto cleanup;
    }

    result = 0;

  cleanup:
    /* Don't double free fileName */
    if (searchSpec != NULL && searchSpec->matchPattern != NULL) {
        searchSpec->matchPattern->value = NULL;
    }

    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
    VIR_FREE(fileName);
    VIR_FREE(datastorePath);
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&datastore);
    esxVI_ManagedObjectReference_Free(&hostDatastoreBrowser);
    esxVI_HostDatastoreBrowserSearchSpec_Free(&searchSpec);
    esxVI_ManagedObjectReference_Free(&task);
    esxVI_TaskInfo_Free(&taskInfo);
    esxVI_HostDatastoreBrowserSearchResults_Free(&searchResults);

    return result;
}

416 417


418
static esxVI_Boolean
419
esxSupportsLongMode(esxPrivate *priv)
420 421 422 423 424 425
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_HostCpuIdInfo *hostCpuIdInfoList = NULL;
    esxVI_HostCpuIdInfo *hostCpuIdInfo = NULL;
426
    esxVI_ParsedHostCpuIdInfo parsedHostCpuIdInfo;
427 428 429 430 431 432
    char edxLongModeBit = '?';

    if (priv->supportsLongMode != esxVI_Boolean_Undefined) {
        return priv->supportsLongMode;
    }

433
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
434
        return esxVI_Boolean_Undefined;
435 436
    }

437
    if (esxVI_String_AppendValueToList(&propertyNameList,
438
                                       "hardware.cpuFeature") < 0 ||
439 440
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
441
        goto cleanup;
442 443 444
    }

    if (hostSystem == NULL) {
445 446
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
447
        goto cleanup;
448 449 450 451 452 453
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuFeature")) {
            if (esxVI_HostCpuIdInfo_CastListFromAnyType
454
                  (dynamicProperty->val, &hostCpuIdInfoList) < 0) {
M
Matthias Bolte 已提交
455
                goto cleanup;
456 457 458 459 460
            }

            for (hostCpuIdInfo = hostCpuIdInfoList; hostCpuIdInfo != NULL;
                 hostCpuIdInfo = hostCpuIdInfo->_next) {
                if (hostCpuIdInfo->level->value == -2147483647) { /* 0x80000001 */
461 462
                    if (esxVI_ParseHostCpuIdInfo(&parsedHostCpuIdInfo,
                                                 hostCpuIdInfo) < 0) {
M
Matthias Bolte 已提交
463
                        goto cleanup;
464 465
                    }

466
                    edxLongModeBit = parsedHostCpuIdInfo.edx[29];
467 468 469 470 471 472

                    if (edxLongModeBit == '1') {
                        priv->supportsLongMode = esxVI_Boolean_True;
                    } else if (edxLongModeBit == '0') {
                        priv->supportsLongMode = esxVI_Boolean_False;
                    } else {
473
                        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
474 475 476 477
                                  _("Bit 29 (Long Mode) of HostSystem property "
                                    "'hardware.cpuFeature[].edx' with value '%s' "
                                    "has unexpected value '%c', expecting '0' "
                                    "or '1'"), hostCpuIdInfo->edx, edxLongModeBit);
M
Matthias Bolte 已提交
478
                        goto cleanup;
479 480 481 482 483 484 485 486 487 488 489 490 491
                    }

                    break;
                }
            }

            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

  cleanup:
M
Matthias Bolte 已提交
492 493 494 495
    /*
     * If we goto cleanup in case of an error then priv->supportsLongMode
     * is still esxVI_Boolean_Undefined, therefore we don't need to set it.
     */
496 497 498 499 500 501 502 503 504
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_HostCpuIdInfo_Free(&hostCpuIdInfoList);

    return priv->supportsLongMode;
}



505 506 507 508 509 510 511 512
static int
esxLookupHostSystemBiosUuid(esxPrivate *priv, unsigned char *uuid)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

513
    if (esxVI_EnsureSession(priv->primary) < 0) {
514 515 516 517 518
        return -1;
    }

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "hardware.systemInfo.uuid") < 0 ||
519 520
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
        goto cleanup;
    }

    if (hostSystem == NULL) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
        goto cleanup;
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.systemInfo.uuid")) {
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
                                         esxVI_Type_String) < 0) {
                goto cleanup;
            }

            if (strlen(dynamicProperty->val->string) > 0) {
                if (virUUIDParse(dynamicProperty->val->string, uuid) < 0) {
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                              _("Could not parse UUID from string '%s'"),
                              dynamicProperty->val->string);
                    goto cleanup;
                }
            } else {
                /* HostSystem has an empty UUID */
                memset(uuid, 0, VIR_UUID_BUFLEN);
            }

            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    result = 0;

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



567
static virCapsPtr
568
esxCapsInit(esxPrivate *priv)
569
{
570
    esxVI_Boolean supportsLongMode = esxSupportsLongMode(priv);
571 572 573
    virCapsPtr caps = NULL;
    virCapsGuestPtr guest = NULL;

574 575 576 577 578 579 580 581 582
    if (supportsLongMode == esxVI_Boolean_Undefined) {
        return NULL;
    }

    if (supportsLongMode == esxVI_Boolean_True) {
        caps = virCapabilitiesNew("x86_64", 1, 1);
    } else {
        caps = virCapabilitiesNew("i686", 1, 1);
    }
583 584

    if (caps == NULL) {
585
        virReportOOMError();
586 587 588
        return NULL;
    }

589
    virCapabilitiesSetMacPrefix(caps, (unsigned char[]){ 0x00, 0x0c, 0x29 });
590
    virCapabilitiesAddHostMigrateTransport(caps, "vpxmigr");
591

592 593
    caps->hasWideScsiBus = true;

594 595 596 597
    if (esxLookupHostSystemBiosUuid(priv, caps->host.host_uuid) < 0) {
        goto failure;
    }

598 599 600
    /* i686 */
    guest = virCapabilitiesAddGuest(caps, "hvm", "i686", 32, NULL, NULL, 0,
                                    NULL);
601 602 603 604 605 606 607 608 609 610 611 612 613 614

    if (guest == NULL) {
        goto failure;
    }

    /*
     * FIXME: Maybe distinguish betwen ESX and GSX here, see
     * esxVMX_ParseConfig() and VIR_DOMAIN_VIRT_VMWARE
     */
    if (virCapabilitiesAddGuestDomain(guest, "vmware", NULL, NULL, 0,
                                      NULL) == NULL) {
        goto failure;
    }

615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
    /* x86_64 */
    if (supportsLongMode == esxVI_Boolean_True) {
        guest = virCapabilitiesAddGuest(caps, "hvm", "x86_64", 64, NULL, NULL,
                                        0, NULL);

        if (guest == NULL) {
            goto failure;
        }

        /*
         * FIXME: Maybe distinguish betwen ESX and GSX here, see
         * esxVMX_ParseConfig() and VIR_DOMAIN_VIRT_VMWARE
         */
        if (virCapabilitiesAddGuestDomain(guest, "vmware", NULL, NULL, 0,
                                          NULL) == NULL) {
            goto failure;
        }
    }

634 635 636 637 638 639 640 641 642 643
    return caps;

  failure:
    virCapabilitiesFree(caps);

    return NULL;
}



644 645 646 647
static int
esxConnectToHost(esxPrivate *priv, virConnectAuthPtr auth,
                 const char *hostname, int port,
                 const char *predefinedUsername,
M
Matthias Bolte 已提交
648
                 esxUtil_ParsedUri *parsedUri,
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
                 esxVI_ProductVersion expectedProductVersion,
                 char **vCenterIpAddress)
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
    char *password = NULL;
    char *url = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_Boolean inMaintenanceMode = esxVI_Boolean_Undefined;

    if (vCenterIpAddress == NULL || *vCenterIpAddress != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    if (esxUtil_ResolveHostname(hostname, ipAddress, NI_MAXHOST) < 0) {
        return -1;
    }

    if (predefinedUsername != NULL) {
        username = strdup(predefinedUsername);

        if (username == NULL) {
            virReportOOMError();
            goto cleanup;
        }
    } else {
        username = virRequestUsername(auth, "root", hostname);

        if (username == NULL) {
            ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Username request failed"));
            goto cleanup;
        }
    }

    password = virRequestPassword(auth, username, hostname);

    if (password == NULL) {
        ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
        goto cleanup;
    }

    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->transport, hostname,
                    port) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    if (esxVI_Context_Alloc(&priv->host) < 0 ||
        esxVI_Context_Connect(priv->host, url, ipAddress, username, password,
701 702
                              parsedUri) < 0 ||
        esxVI_Context_LookupObjectsByPath(priv->host, parsedUri) < 0) {
703 704 705 706 707
        goto cleanup;
    }

    if (expectedProductVersion == esxVI_ProductVersion_ESX) {
        if (priv->host->productVersion != esxVI_ProductVersion_ESX35 &&
M
Matthias Bolte 已提交
708 709 710
            priv->host->productVersion != esxVI_ProductVersion_ESX40 &&
            priv->host->productVersion != esxVI_ProductVersion_ESX41 &&
            priv->host->productVersion != esxVI_ProductVersion_ESX4x) {
711
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
M
Matthias Bolte 已提交
712
                      _("%s is neither an ESX 3.5 host nor an ESX 4.x host"),
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
                      hostname);
            goto cleanup;
        }
    } else { /* GSX */
        if (priv->host->productVersion != esxVI_ProductVersion_GSX20) {
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                      _("%s isn't a GSX 2.0 host"), hostname);
            goto cleanup;
        }
    }

    /* Query the host for maintenance mode and vCenter IP address */
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "runtime.inMaintenanceMode\0"
                                           "summary.managementServerIp\0") < 0 ||
728 729
        esxVI_LookupHostSystemProperties(priv->host, propertyNameList,
                                         &hostSystem) < 0 ||
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
        esxVI_GetBoolean(hostSystem, "runtime.inMaintenanceMode",
                         &inMaintenanceMode,
                         esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_GetStringValue(hostSystem, "summary.managementServerIp",
                             vCenterIpAddress,
                             esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
    }

    /* Warn if host is in maintenance mode */
    if (inMaintenanceMode == esxVI_Boolean_True) {
        VIR_WARN0("The server is in maintenance mode");
    }

    if (*vCenterIpAddress != NULL) {
        *vCenterIpAddress = strdup(*vCenterIpAddress);

        if (*vCenterIpAddress == NULL) {
            virReportOOMError();
            goto cleanup;
        }
    }

    result = 0;

  cleanup:
    VIR_FREE(password);
    VIR_FREE(username);
    VIR_FREE(url);
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



static int
esxConnectToVCenter(esxPrivate *priv, virConnectAuthPtr auth,
                    const char *hostname, int port,
                    const char *predefinedUsername,
771
                    const char *hostSystemIpAddress,
M
Matthias Bolte 已提交
772
                    esxUtil_ParsedUri *parsedUri)
773 774 775 776 777 778 779
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
    char *password = NULL;
    char *url = NULL;

780 781 782 783 784 785 786 787
    if (hostSystemIpAddress == NULL &&
        (parsedUri->path_datacenter == NULL ||
         parsedUri->path_computeResource == NULL)) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Path has to specify the datacenter and compute resource"));
        return -1;
    }

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
    if (esxUtil_ResolveHostname(hostname, ipAddress, NI_MAXHOST) < 0) {
        return -1;
    }

    if (predefinedUsername != NULL) {
        username = strdup(predefinedUsername);

        if (username == NULL) {
            virReportOOMError();
            goto cleanup;
        }
    } else {
        username = virRequestUsername(auth, "administrator", hostname);

        if (username == NULL) {
            ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Username request failed"));
            goto cleanup;
        }
    }

    password = virRequestPassword(auth, username, hostname);

    if (password == NULL) {
        ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
        goto cleanup;
    }

    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->transport, hostname,
                    port) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    if (esxVI_Context_Alloc(&priv->vCenter) < 0 ||
        esxVI_Context_Connect(priv->vCenter, url, ipAddress, username,
M
Matthias Bolte 已提交
823
                              password, parsedUri) < 0) {
824 825 826 827
        goto cleanup;
    }

    if (priv->vCenter->productVersion != esxVI_ProductVersion_VPX25 &&
M
Matthias Bolte 已提交
828 829 830
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX40 &&
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX41 &&
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX4x) {
831 832
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("%s is neither a vCenter 2.5 server nor a vCenter "
M
Matthias Bolte 已提交
833
                    "4.x server"), hostname);
834 835 836
        goto cleanup;
    }

837 838 839 840 841 842 843 844 845 846 847
    if (hostSystemIpAddress != NULL) {
        if (esxVI_Context_LookupObjectsByHostSystemIp(priv->vCenter,
                                                      hostSystemIpAddress) < 0) {
            goto cleanup;
        }
    } else {
        if (esxVI_Context_LookupObjectsByPath(priv->vCenter, parsedUri) < 0) {
            goto cleanup;
        }
    }

848 849 850 851 852 853 854 855 856 857 858 859
    result = 0;

  cleanup:
    VIR_FREE(password);
    VIR_FREE(username);
    VIR_FREE(url);

    return result;
}



860
/*
861 862
 * URI format: {vpx|esx|gsx}://[<username>@]<hostname>[:<port>]/[<path>][?<query parameter> ...]
 *             <path> = <datacenter>/<computeresource>[/<hostsystem>]
863
 *
864 865
 * If no port is specified the default port is set dependent on the scheme and
 * transport parameter:
866 867
 * - vpx+http  80
 * - vpx+https 443
868
 * - esx+http  80
869
 * - esx+https 443
870 871 872
 * - gsx+http  8222
 * - gsx+https 8333
 *
873 874 875 876 877
 * For a vpx:// connection <path> references a host managed by the vCenter.
 * In case the host is part of a cluster then <computeresource> is the cluster
 * name. Otherwise <computeresource> and <hostsystem> are equal and the later
 * can be omitted.
 *
878 879
 * Optional query parameters:
 * - transport={http|https}
880
 * - vcenter={<vcenter>|*}             only useful for an esx:// connection
881 882
 * - no_verify={0|1}
 * - auto_answer={0|1}
M
Matthias Bolte 已提交
883
 * - proxy=[{http|socks|socks4|socks4a|socks5}://]<hostname>[:<port>]
884
 *
885 886 887
 * If no transport parameter is specified https is used.
 *
 * The vcenter parameter is only necessary for migration, because the vCenter
888
 * server is in charge to initiate a migration between two ESX hosts. The
889
 * vcenter parameter can be set to an explicitly hostname or to *. If set to *,
890 891
 * the driver will check if the ESX host is managed by a vCenter and connect to
 * it. If the ESX host is not managed by a vCenter an error is reported.
892 893
 *
 * If the no_verify parameter is set to 1, this disables libcurl client checks
894
 * of the server's certificate. The default value it 0.
895 896 897 898
 *
 * If the auto_answer parameter is set to 1, the driver will respond to all
 * virtual machine questions with the default answer, otherwise virtual machine
 * questions will be reported as errors. The default value it 0.
M
Matthias Bolte 已提交
899 900 901 902
 *
 * The proxy parameter allows to specify a proxy for to be used by libcurl.
 * The default for the optional <type> part is http and socks is synonymous for
 * socks5. The optional <port> part allows to override the default port 1080.
903 904 905 906
 */
static virDrvOpenStatus
esxOpen(virConnectPtr conn, virConnectAuthPtr auth, int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
907
    virDrvOpenStatus result = VIR_DRV_OPEN_ERROR;
908
    esxPrivate *priv = NULL;
M
Matthias Bolte 已提交
909
    esxUtil_ParsedUri *parsedUri = NULL;
910
    char *potentialVCenterIpAddress = NULL;
M
Matthias Bolte 已提交
911
    char vCenterIpAddress[NI_MAXHOST] = "";
912

913
    /* Decline if the URI is NULL or the scheme is not one of {vpx|esx|gsx} */
914
    if (conn->uri == NULL || conn->uri->scheme == NULL ||
915 916
        (STRCASENEQ(conn->uri->scheme, "vpx") &&
         STRCASENEQ(conn->uri->scheme, "esx") &&
917
         STRCASENEQ(conn->uri->scheme, "gsx"))) {
918 919 920
        return VIR_DRV_OPEN_DECLINED;
    }

M
Matthias Bolte 已提交
921 922 923
    /* Decline URIs without server part, or missing auth */
    if (conn->uri->server == NULL || auth == NULL || auth->cb == NULL) {
        return VIR_DRV_OPEN_DECLINED;
924 925 926 927
    }

    /* Allocate per-connection private data */
    if (VIR_ALLOC(priv) < 0) {
928
        virReportOOMError();
M
Matthias Bolte 已提交
929
        goto cleanup;
930 931
    }

M
Matthias Bolte 已提交
932
    if (esxUtil_ParseUri(&parsedUri, conn->uri) < 0) {
933 934 935
        goto cleanup;
    }

M
Matthias Bolte 已提交
936 937
    priv->transport = parsedUri->transport;
    parsedUri->transport = NULL;
938

M
Matthias Bolte 已提交
939 940
    priv->maxVcpus = -1;
    priv->supportsVMotion = esxVI_Boolean_Undefined;
941
    priv->supportsLongMode = esxVI_Boolean_Undefined;
M
Matthias Bolte 已提交
942 943
    priv->autoAnswer = parsedUri->autoAnswer ? esxVI_Boolean_True
                                             : esxVI_Boolean_False;
944 945
    priv->usedCpuTimeCounterId = -1;

M
Matthias Bolte 已提交
946 947 948 949 950 951 952
    /*
     * Set the port dependent on the transport protocol if no port is
     * specified. This allows us to rely on the port parameter being
     * correctly set when building URIs later on, without the need to
     * distinguish between the situations port == 0 and port != 0
     */
    if (conn->uri->port == 0) {
953 954
        if (STRCASEEQ(conn->uri->scheme, "vpx") ||
            STRCASEEQ(conn->uri->scheme, "esx")) {
M
Matthias Bolte 已提交
955 956 957 958 959 960 961 962 963 964 965
            if (STRCASEEQ(priv->transport, "https")) {
                conn->uri->port = 443;
            } else {
                conn->uri->port = 80;
            }
        } else { /* GSX */
            if (STRCASEEQ(priv->transport, "https")) {
                conn->uri->port = 8333;
            } else {
                conn->uri->port = 8222;
            }
966
        }
M
Matthias Bolte 已提交
967
    }
968

969 970 971 972
    if (STRCASEEQ(conn->uri->scheme, "esx") ||
        STRCASEEQ(conn->uri->scheme, "gsx")) {
        /* Connect to host */
        if (esxConnectToHost(priv, auth, conn->uri->server, conn->uri->port,
M
Matthias Bolte 已提交
973
                             conn->uri->user, parsedUri,
974 975 976 977
                             STRCASEEQ(conn->uri->scheme, "esx")
                               ? esxVI_ProductVersion_ESX
                               : esxVI_ProductVersion_GSX,
                             &potentialVCenterIpAddress) < 0) {
M
Matthias Bolte 已提交
978
            goto cleanup;
979
        }
980

981
        /* Connect to vCenter */
M
Matthias Bolte 已提交
982 983
        if (parsedUri->vCenter != NULL) {
            if (STREQ(parsedUri->vCenter, "*")) {
984 985 986
                if (potentialVCenterIpAddress == NULL) {
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                              _("This host is not managed by a vCenter"));
M
Matthias Bolte 已提交
987
                    goto cleanup;
988 989
                }

990 991 992 993 994 995 996 997
                if (virStrcpyStatic(vCenterIpAddress,
                                    potentialVCenterIpAddress) == NULL) {
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                              _("vCenter IP address %s too big for destination"),
                              potentialVCenterIpAddress);
                    goto cleanup;
                }
            } else {
M
Matthias Bolte 已提交
998
                if (esxUtil_ResolveHostname(parsedUri->vCenter,
999 1000 1001
                                            vCenterIpAddress, NI_MAXHOST) < 0) {
                    goto cleanup;
                }
1002

1003 1004
                if (potentialVCenterIpAddress != NULL &&
                    STRNEQ(vCenterIpAddress, potentialVCenterIpAddress)) {
1005
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1006 1007 1008
                              _("This host is managed by a vCenter with IP "
                                "address %s, but a mismachting vCenter '%s' "
                                "(%s) has been specified"),
M
Matthias Bolte 已提交
1009
                              potentialVCenterIpAddress, parsedUri->vCenter,
1010
                              vCenterIpAddress);
M
Matthias Bolte 已提交
1011
                    goto cleanup;
1012 1013
                }
            }
1014

1015
            if (esxConnectToVCenter(priv, auth, vCenterIpAddress,
1016 1017
                                    conn->uri->port, NULL,
                                    priv->host->ipAddress, parsedUri) < 0) {
1018 1019
                goto cleanup;
            }
1020 1021
        }

1022 1023 1024 1025
        priv->primary = priv->host;
    } else { /* VPX */
        /* Connect to vCenter */
        if (esxConnectToVCenter(priv, auth, conn->uri->server, conn->uri->port,
1026
                                conn->uri->user, NULL, parsedUri) < 0) {
M
Matthias Bolte 已提交
1027
            goto cleanup;
1028 1029
        }

1030
        priv->primary = priv->vCenter;
1031 1032 1033
    }

    conn->privateData = priv;
1034

M
Matthias Bolte 已提交
1035
    /* Setup capabilities */
1036
    priv->caps = esxCapsInit(priv);
1037

M
Matthias Bolte 已提交
1038
    if (priv->caps == NULL) {
M
Matthias Bolte 已提交
1039
        goto cleanup;
1040 1041
    }

M
Matthias Bolte 已提交
1042
    result = VIR_DRV_OPEN_SUCCESS;
1043

M
Matthias Bolte 已提交
1044 1045
  cleanup:
    if (result == VIR_DRV_OPEN_ERROR && priv != NULL) {
1046
        esxVI_Context_Free(&priv->host);
M
Matthias Bolte 已提交
1047
        esxVI_Context_Free(&priv->vCenter);
1048

1049 1050
        virCapabilitiesFree(priv->caps);

M
Matthias Bolte 已提交
1051
        VIR_FREE(priv->transport);
1052 1053 1054
        VIR_FREE(priv);
    }

M
Matthias Bolte 已提交
1055
    esxUtil_FreeParsedUri(&parsedUri);
1056
    VIR_FREE(potentialVCenterIpAddress);
1057

M
Matthias Bolte 已提交
1058
    return result;
1059 1060 1061 1062 1063 1064 1065
}



static int
esxClose(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1066
    esxPrivate *priv = conn->privateData;
E
Eric Blake 已提交
1067
    int result = 0;
1068

1069 1070 1071 1072 1073
    if (priv->host != NULL) {
        if (esxVI_EnsureSession(priv->host) < 0 ||
            esxVI_Logout(priv->host) < 0) {
            result = -1;
        }
1074

1075 1076
        esxVI_Context_Free(&priv->host);
    }
1077

M
Matthias Bolte 已提交
1078
    if (priv->vCenter != NULL) {
E
Eric Blake 已提交
1079 1080 1081 1082
        if (esxVI_EnsureSession(priv->vCenter) < 0 ||
            esxVI_Logout(priv->vCenter) < 0) {
            result = -1;
        }
1083

M
Matthias Bolte 已提交
1084
        esxVI_Context_Free(&priv->vCenter);
1085 1086
    }

1087 1088
    virCapabilitiesFree(priv->caps);

1089 1090 1091 1092 1093
    VIR_FREE(priv->transport);
    VIR_FREE(priv);

    conn->privateData = NULL;

E
Eric Blake 已提交
1094
    return result;
1095 1096 1097 1098 1099
}



static esxVI_Boolean
1100
esxSupportsVMotion(esxPrivate *priv)
1101 1102 1103 1104
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;

M
Matthias Bolte 已提交
1105 1106
    if (priv->supportsVMotion != esxVI_Boolean_Undefined) {
        return priv->supportsVMotion;
1107 1108
    }

1109
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1110
        return esxVI_Boolean_Undefined;
1111 1112
    }

1113
    if (esxVI_String_AppendValueToList(&propertyNameList,
1114
                                       "capability.vmotionSupported") < 0 ||
1115 1116
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1117
        goto cleanup;
1118 1119 1120
    }

    if (hostSystem == NULL) {
1121 1122
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
1123
        goto cleanup;
1124 1125
    }

1126 1127 1128 1129
    if (esxVI_GetBoolean(hostSystem, "capability.vmotionSupported",
                         &priv->supportsVMotion,
                         esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
1130 1131 1132
    }

  cleanup:
M
Matthias Bolte 已提交
1133 1134 1135 1136
    /*
     * If we goto cleanup in case of an error then priv->supportsVMotion is
     * still esxVI_Boolean_Undefined, therefore we don't need to set it.
     */
1137 1138 1139
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
1140
    return priv->supportsVMotion;
1141 1142 1143 1144 1145 1146 1147
}



static int
esxSupportsFeature(virConnectPtr conn, int feature)
{
M
Matthias Bolte 已提交
1148
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1149
    esxVI_Boolean supportsVMotion = esxVI_Boolean_Undefined;
1150 1151 1152

    switch (feature) {
      case VIR_DRV_FEATURE_MIGRATION_V1:
1153
        supportsVMotion = esxSupportsVMotion(priv);
1154

M
Matthias Bolte 已提交
1155
        if (supportsVMotion == esxVI_Boolean_Undefined) {
1156 1157 1158
            return -1;
        }

M
Matthias Bolte 已提交
1159 1160 1161
        /* Migration is only possible via a vCenter and if VMotion is enabled */
        return priv->vCenter != NULL &&
               supportsVMotion == esxVI_Boolean_True ? 1 : 0;
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180

      default:
        return 0;
    }
}



static const char *
esxGetType(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    return "ESX";
}



static int
esxGetVersion(virConnectPtr conn, unsigned long *version)
{
M
Matthias Bolte 已提交
1181
    esxPrivate *priv = conn->privateData;
1182

1183
    if (virParseVersionString(priv->primary->service->about->version,
1184 1185
                              version) < 0) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1186
                  _("Could not parse version number from '%s'"),
1187
                  priv->primary->service->about->version);
1188

1189
        return -1;
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
    }

    return 0;
}



static char *
esxGetHostname(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1200
    esxPrivate *priv = conn->privateData;
1201 1202 1203 1204 1205 1206 1207
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    const char *hostName = NULL;
    const char *domainName = NULL;
    char *complete = NULL;

1208
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1209
        return NULL;
1210 1211 1212
    }

    if (esxVI_String_AppendValueListToList
1213
          (&propertyNameList,
1214 1215
           "config.network.dnsConfig.hostName\0"
           "config.network.dnsConfig.domainName\0") < 0 ||
1216 1217
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1218
        goto cleanup;
1219 1220 1221
    }

    if (hostSystem == NULL) {
1222 1223
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
1224
        goto cleanup;
1225 1226 1227 1228 1229 1230
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name,
                  "config.network.dnsConfig.hostName")) {
1231
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1232
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1233
                goto cleanup;
1234 1235 1236 1237 1238
            }

            hostName = dynamicProperty->val->string;
        } else if (STREQ(dynamicProperty->name,
                         "config.network.dnsConfig.domainName")) {
1239
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1240
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1241
                goto cleanup;
1242 1243 1244 1245 1246 1247 1248 1249
            }

            domainName = dynamicProperty->val->string;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

M
Matthias Bolte 已提交
1250
    if (hostName == NULL || strlen(hostName) < 1) {
1251 1252
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Missing or empty 'hostName' property"));
M
Matthias Bolte 已提交
1253
        goto cleanup;
1254 1255
    }

M
Matthias Bolte 已提交
1256
    if (domainName == NULL || strlen(domainName) < 1) {
1257
        complete = strdup(hostName);
1258

1259
        if (complete == NULL) {
1260
            virReportOOMError();
M
Matthias Bolte 已提交
1261
            goto cleanup;
1262 1263 1264
        }
    } else {
        if (virAsprintf(&complete, "%s.%s", hostName, domainName) < 0) {
1265
            virReportOOMError();
M
Matthias Bolte 已提交
1266
            goto cleanup;
1267
        }
1268 1269 1270
    }

  cleanup:
M
Matthias Bolte 已提交
1271 1272 1273 1274 1275
    /*
     * If we goto cleanup in case of an error then complete is still NULL,
     * either strdup returned NULL or virAsprintf failed. When virAsprintf
     * fails it guarantees setting complete to NULL
     */
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return complete;
}



static int
esxNodeGetInfo(virConnectPtr conn, virNodeInfoPtr nodeinfo)
{
M
Matthias Bolte 已提交
1287
    int result = -1;
M
Matthias Bolte 已提交
1288
    esxPrivate *priv = conn->privateData;
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    int64_t cpuInfo_hz = 0;
    int16_t cpuInfo_numCpuCores = 0;
    int16_t cpuInfo_numCpuPackages = 0;
    int16_t cpuInfo_numCpuThreads = 0;
    int64_t memorySize = 0;
    int32_t numaInfo_numNodes = 0;
    char *ptr = NULL;

M
Matthias Bolte 已提交
1300
    memset(nodeinfo, 0, sizeof (*nodeinfo));
1301

1302
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1303
        return -1;
1304 1305
    }

1306
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1307 1308 1309 1310 1311 1312 1313
                                           "hardware.cpuInfo.hz\0"
                                           "hardware.cpuInfo.numCpuCores\0"
                                           "hardware.cpuInfo.numCpuPackages\0"
                                           "hardware.cpuInfo.numCpuThreads\0"
                                           "hardware.memorySize\0"
                                           "hardware.numaInfo.numNodes\0"
                                           "summary.hardware.cpuModel\0") < 0 ||
1314 1315
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1316
        goto cleanup;
1317 1318 1319
    }

    if (hostSystem == NULL) {
1320 1321
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
1322
        goto cleanup;
1323 1324 1325 1326 1327
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuInfo.hz")) {
1328
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1329
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1330
                goto cleanup;
1331 1332 1333 1334 1335
            }

            cpuInfo_hz = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuCores")) {
1336
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1337
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1338
                goto cleanup;
1339 1340 1341 1342 1343
            }

            cpuInfo_numCpuCores = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuPackages")) {
1344
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1345
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1346
                goto cleanup;
1347 1348 1349 1350 1351
            }

            cpuInfo_numCpuPackages = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuThreads")) {
1352
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1353
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1354
                goto cleanup;
1355 1356 1357 1358
            }

            cpuInfo_numCpuThreads = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name, "hardware.memorySize")) {
1359
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1360
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1361
                goto cleanup;
1362 1363 1364 1365 1366
            }

            memorySize = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.numaInfo.numNodes")) {
1367
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1368
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1369
                goto cleanup;
1370 1371 1372 1373 1374
            }

            numaInfo_numNodes = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "summary.hardware.cpuModel")) {
1375
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1376
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1377
                goto cleanup;
1378 1379 1380 1381 1382 1383
            }

            ptr = dynamicProperty->val->string;

            /* Strip the string to fit more relevant information in 32 chars */
            while (*ptr != '\0') {
M
Matthias Bolte 已提交
1384 1385
                if (STRPREFIX(ptr, "  ")) {
                    memmove(ptr, ptr + 1, strlen(ptr + 1) + 1);
1386
                    continue;
1387
                } else if (STRPREFIX(ptr, "(R)") || STRPREFIX(ptr, "(C)")) {
M
Matthias Bolte 已提交
1388
                    memmove(ptr, ptr + 3, strlen(ptr + 3) + 1);
1389
                    continue;
1390 1391 1392
                } else if (STRPREFIX(ptr, "(TM)")) {
                    memmove(ptr, ptr + 4, strlen(ptr + 4) + 1);
                    continue;
1393 1394 1395 1396 1397
                }

                ++ptr;
            }

C
Chris Lalancette 已提交
1398 1399 1400
            if (virStrncpy(nodeinfo->model, dynamicProperty->val->string,
                           sizeof(nodeinfo->model) - 1,
                           sizeof(nodeinfo->model)) == NULL) {
1401
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1402
                          _("CPU Model %s too long for destination"),
C
Chris Lalancette 已提交
1403
                          dynamicProperty->val->string);
M
Matthias Bolte 已提交
1404
                goto cleanup;
C
Chris Lalancette 已提交
1405
            }
1406 1407 1408 1409 1410 1411 1412
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    nodeinfo->memory = memorySize / 1024; /* Scale from bytes to kilobytes */
    nodeinfo->cpus = cpuInfo_numCpuCores;
1413
    nodeinfo->mhz = cpuInfo_hz / (1000 * 1000); /* Scale from hz to mhz */
1414 1415 1416 1417 1418 1419 1420 1421 1422
    nodeinfo->nodes = numaInfo_numNodes;
    nodeinfo->sockets = cpuInfo_numCpuPackages;
    nodeinfo->cores = cpuInfo_numCpuPackages > 0
                        ? cpuInfo_numCpuCores / cpuInfo_numCpuPackages
                        : 0;
    nodeinfo->threads = cpuInfo_numCpuCores > 0
                          ? cpuInfo_numCpuThreads / cpuInfo_numCpuCores
                          : 0;

M
Matthias Bolte 已提交
1423 1424
    result = 0;

1425 1426 1427 1428 1429 1430 1431 1432 1433
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



1434 1435 1436
static char *
esxGetCapabilities(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1437
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1438
    char *xml = virCapabilitiesFormatXML(priv->caps);
1439 1440

    if (xml == NULL) {
1441
        virReportOOMError();
1442 1443 1444 1445 1446 1447 1448 1449
        return NULL;
    }

    return xml;
}



1450 1451 1452
static int
esxListDomains(virConnectPtr conn, int *ids, int maxids)
{
M
Matthias Bolte 已提交
1453
    bool success = false;
M
Matthias Bolte 已提交
1454
    esxPrivate *priv = conn->privateData;
1455 1456 1457 1458 1459 1460 1461
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;

    if (ids == NULL || maxids < 0) {
1462 1463
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
1464 1465 1466 1467 1468 1469
    }

    if (maxids == 0) {
        return 0;
    }

1470
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1471
        return -1;
1472 1473
    }

1474
    if (esxVI_String_AppendValueToList(&propertyNameList,
1475
                                       "runtime.powerState") < 0 ||
1476 1477
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1478
        goto cleanup;
1479 1480 1481 1482
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
1483
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1484
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1485
            goto cleanup;
1486 1487 1488 1489 1490 1491 1492 1493 1494
        }

        if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

        if (esxUtil_ParseVirtualMachineIDString(virtualMachine->obj->value,
                                                &ids[count]) < 0 ||
            ids[count] <= 0) {
1495
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1496
                      _("Failed to parse positive integer from '%s'"),
1497
                      virtualMachine->obj->value);
M
Matthias Bolte 已提交
1498
            goto cleanup;
1499 1500 1501 1502 1503 1504 1505 1506 1507
        }

        count++;

        if (count >= maxids) {
            break;
        }
    }

M
Matthias Bolte 已提交
1508 1509
    success = true;

1510 1511 1512 1513
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
1514
    return success ? count : -1;
1515 1516 1517 1518 1519 1520 1521
}



static int
esxNumberOfDomains(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1522
    esxPrivate *priv = conn->privateData;
1523

1524
    if (esxVI_EnsureSession(priv->primary) < 0) {
1525 1526 1527
        return -1;
    }

1528
    return esxVI_LookupNumberOfDomainsByPowerState
1529
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn,
1530 1531 1532 1533 1534 1535 1536 1537
              esxVI_Boolean_False);
}



static virDomainPtr
esxDomainLookupByID(virConnectPtr conn, int id)
{
M
Matthias Bolte 已提交
1538
    esxPrivate *priv = conn->privateData;
1539 1540 1541 1542
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
M
Matthias Bolte 已提交
1543 1544 1545
    int id_candidate = -1;
    char *name_candidate = NULL;
    unsigned char uuid_candidate[VIR_UUID_BUFLEN];
1546 1547
    virDomainPtr domain = NULL;

1548
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1549
        return NULL;
1550 1551
    }

1552
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1553
                                           "configStatus\0"
1554 1555
                                           "name\0"
                                           "runtime.powerState\0"
1556
                                           "config.uuid\0") < 0 ||
1557 1558
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1559
        goto cleanup;
1560 1561 1562 1563
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
1564
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1565
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1566
            goto cleanup;
1567 1568 1569 1570 1571 1572 1573
        }

        /* Only running/suspended domains have an ID != -1 */
        if (powerState == esxVI_VirtualMachinePowerState_PoweredOff) {
            continue;
        }

M
Matthias Bolte 已提交
1574
        VIR_FREE(name_candidate);
1575

1576
        if (esxVI_GetVirtualMachineIdentity(virtualMachine,
M
Matthias Bolte 已提交
1577 1578
                                            &id_candidate, &name_candidate,
                                            uuid_candidate) < 0) {
M
Matthias Bolte 已提交
1579
            goto cleanup;
1580 1581
        }

M
Matthias Bolte 已提交
1582
        if (id != id_candidate) {
1583 1584 1585
            continue;
        }

M
Matthias Bolte 已提交
1586
        domain = virGetDomain(conn, name_candidate, uuid_candidate);
1587 1588

        if (domain == NULL) {
M
Matthias Bolte 已提交
1589
            goto cleanup;
1590 1591 1592 1593 1594 1595 1596 1597
        }

        domain->id = id;

        break;
    }

    if (domain == NULL) {
1598
        ESX_ERROR(VIR_ERR_NO_DOMAIN, _("No domain with ID %d"), id);
1599 1600 1601 1602 1603
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
M
Matthias Bolte 已提交
1604
    VIR_FREE(name_candidate);
1605 1606 1607 1608 1609 1610 1611 1612 1613

    return domain;
}



static virDomainPtr
esxDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
M
Matthias Bolte 已提交
1614
    esxPrivate *priv = conn->privateData;
1615 1616 1617
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1618 1619
    int id = -1;
    char *name = NULL;
1620 1621
    virDomainPtr domain = NULL;

1622
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1623
        return NULL;
1624 1625
    }

1626
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1627
                                           "name\0"
1628
                                           "runtime.powerState\0") < 0 ||
1629
        esxVI_LookupVirtualMachineByUuid(priv->primary, uuid, propertyNameList,
1630
                                         &virtualMachine,
M
Matthias Bolte 已提交
1631
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1632 1633
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, &name, NULL) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1634
        goto cleanup;
1635 1636
    }

1637
    domain = virGetDomain(conn, name, uuid);
1638 1639

    if (domain == NULL) {
M
Matthias Bolte 已提交
1640
        goto cleanup;
1641
    }
1642

1643 1644 1645 1646 1647
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1648 1649 1650 1651
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1652 1653
    esxVI_ObjectContent_Free(&virtualMachine);
    VIR_FREE(name);
1654 1655 1656 1657 1658 1659 1660 1661 1662

    return domain;
}



static virDomainPtr
esxDomainLookupByName(virConnectPtr conn, const char *name)
{
M
Matthias Bolte 已提交
1663
    esxPrivate *priv = conn->privateData;
1664 1665 1666
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1667 1668
    int id = -1;
    unsigned char uuid[VIR_UUID_BUFLEN];
1669 1670
    virDomainPtr domain = NULL;

1671
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1672
        return NULL;
1673 1674
    }

1675
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1676
                                           "configStatus\0"
1677
                                           "runtime.powerState\0"
1678
                                           "config.uuid\0") < 0 ||
1679
        esxVI_LookupVirtualMachineByName(priv->primary, name, propertyNameList,
1680 1681
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
1682
        goto cleanup;
1683 1684
    }

1685
    if (virtualMachine == NULL) {
1686
        ESX_ERROR(VIR_ERR_NO_DOMAIN, _("No domain with name '%s'"), name);
M
Matthias Bolte 已提交
1687
        goto cleanup;
1688
    }
1689 1690


M
Matthias Bolte 已提交
1691 1692 1693
    if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, uuid) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
1694
    }
1695

1696
    domain = virGetDomain(conn, name, uuid);
1697

1698
    if (domain == NULL) {
M
Matthias Bolte 已提交
1699
        goto cleanup;
1700 1701
    }

1702 1703 1704 1705 1706
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1707 1708 1709 1710
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1711
    esxVI_ObjectContent_Free(&virtualMachine);
1712 1713 1714 1715 1716 1717 1718 1719 1720

    return domain;
}



static int
esxDomainSuspend(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1721
    int result = -1;
M
Matthias Bolte 已提交
1722
    esxPrivate *priv = domain->conn->privateData;
1723 1724 1725 1726 1727 1728
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1729
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1730
        return -1;
1731 1732
    }

1733
    if (esxVI_String_AppendValueToList(&propertyNameList,
1734
                                       "runtime.powerState") < 0 ||
1735
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1736
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1737 1738
           priv->autoAnswer) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1739
        goto cleanup;
1740 1741 1742
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1743 1744
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1745
        goto cleanup;
1746 1747
    }

1748 1749
    if (esxVI_SuspendVM_Task(priv->primary, virtualMachine->obj, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1750
                                    esxVI_Occurrence_RequiredItem,
1751
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
1752
        goto cleanup;
1753 1754 1755
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1756
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not suspend domain"));
M
Matthias Bolte 已提交
1757
        goto cleanup;
1758 1759
    }

M
Matthias Bolte 已提交
1760 1761
    result = 0;

1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainResume(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1775
    int result = -1;
M
Matthias Bolte 已提交
1776
    esxPrivate *priv = domain->conn->privateData;
1777 1778 1779 1780 1781 1782
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1783
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1784
        return -1;
1785 1786
    }

1787
    if (esxVI_String_AppendValueToList(&propertyNameList,
1788
                                       "runtime.powerState") < 0 ||
1789
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1790
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1791 1792
           priv->autoAnswer) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1793
        goto cleanup;
1794 1795 1796
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended) {
1797
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not suspended"));
M
Matthias Bolte 已提交
1798
        goto cleanup;
1799 1800
    }

1801
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
1802
                             &task) < 0 ||
1803
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1804
                                    esxVI_Occurrence_RequiredItem,
1805
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
1806
        goto cleanup;
1807 1808 1809
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1810
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not resume domain"));
M
Matthias Bolte 已提交
1811
        goto cleanup;
1812 1813
    }

M
Matthias Bolte 已提交
1814 1815
    result = 0;

1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainShutdown(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1829
    int result = -1;
M
Matthias Bolte 已提交
1830
    esxPrivate *priv = domain->conn->privateData;
1831 1832 1833 1834
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1835
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1836
        return -1;
1837 1838
    }

1839
    if (esxVI_String_AppendValueToList(&propertyNameList,
1840
                                       "runtime.powerState") < 0 ||
1841
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1842
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1843
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1844
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1845
        goto cleanup;
1846 1847 1848
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1849 1850
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1851
        goto cleanup;
1852 1853
    }

1854
    if (esxVI_ShutdownGuest(priv->primary, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1855
        goto cleanup;
1856 1857
    }

M
Matthias Bolte 已提交
1858 1859
    result = 0;

1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
esxDomainReboot(virDomainPtr domain, unsigned int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
1872
    int result = -1;
M
Matthias Bolte 已提交
1873
    esxPrivate *priv = domain->conn->privateData;
1874 1875 1876 1877
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1878
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1879
        return -1;
1880 1881
    }

1882
    if (esxVI_String_AppendValueToList(&propertyNameList,
1883
                                       "runtime.powerState") < 0 ||
1884
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1885
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1886
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1887
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1888
        goto cleanup;
1889 1890 1891
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1892 1893
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1894
        goto cleanup;
1895 1896
    }

1897
    if (esxVI_RebootGuest(priv->primary, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1898
        goto cleanup;
1899 1900
    }

M
Matthias Bolte 已提交
1901 1902
    result = 0;

1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
esxDomainDestroy(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1915
    int result = -1;
M
Matthias Bolte 已提交
1916
    esxPrivate *priv = domain->conn->privateData;
1917
    esxVI_Context *ctx = NULL;
1918 1919 1920 1921 1922 1923
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1924 1925 1926 1927 1928 1929
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

1930
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
1931
        return -1;
1932 1933
    }

1934
    if (esxVI_String_AppendValueToList(&propertyNameList,
1935
                                       "runtime.powerState") < 0 ||
1936
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1937
          (ctx, domain->uuid, propertyNameList, &virtualMachine,
1938
           priv->autoAnswer) < 0 ||
1939
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1940
        goto cleanup;
1941 1942 1943
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1944 1945
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1946
        goto cleanup;
1947 1948
    }

1949
    if (esxVI_PowerOffVM_Task(ctx, virtualMachine->obj, &task) < 0 ||
1950 1951 1952
        esxVI_WaitForTaskCompletion(ctx, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
1953
        goto cleanup;
1954 1955 1956
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1957
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not destroy domain"));
M
Matthias Bolte 已提交
1958
        goto cleanup;
1959 1960
    }

1961
    domain->id = -1;
M
Matthias Bolte 已提交
1962 1963
    result = 0;

1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static char *
1975
esxDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED)
1976
{
1977 1978 1979
    char *osType = strdup("hvm");

    if (osType == NULL) {
1980
        virReportOOMError();
1981 1982 1983 1984
        return NULL;
    }

    return osType;
1985 1986 1987 1988 1989 1990 1991
}



static unsigned long
esxDomainGetMaxMemory(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1992
    esxPrivate *priv = domain->conn->privateData;
1993 1994 1995 1996 1997
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    unsigned long memoryMB = 0;

1998
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1999
        return 0;
2000 2001
    }

2002
    if (esxVI_String_AppendValueToList(&propertyNameList,
2003
                                       "config.hardware.memoryMB") < 0 ||
2004
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2005
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2006
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2007
        goto cleanup;
2008 2009 2010 2011 2012
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2013
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2014
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2015
                goto cleanup;
2016 2017 2018
            }

            if (dynamicProperty->val->int32 < 0) {
2019 2020
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                          _("Got invalid memory size %d"),
2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043
                          dynamicProperty->val->int32);
            } else {
                memoryMB = dynamicProperty->val->int32;
            }

            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);

    return memoryMB * 1024; /* Scale from megabyte to kilobyte */
}



static int
esxDomainSetMaxMemory(virDomainPtr domain, unsigned long memory)
{
M
Matthias Bolte 已提交
2044
    int result = -1;
M
Matthias Bolte 已提交
2045
    esxPrivate *priv = domain->conn->privateData;
2046 2047 2048 2049 2050
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

2051
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2052
        return -1;
2053 2054
    }

2055
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2056
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2057
           priv->autoAnswer) < 0 ||
2058 2059
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Long_Alloc(&spec->memoryMB) < 0) {
M
Matthias Bolte 已提交
2060
        goto cleanup;
2061 2062 2063 2064 2065
    }

    spec->memoryMB->value =
      memory / 1024; /* Scale from kilobytes to megabytes */

2066
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2067
                              &task) < 0 ||
2068
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2069
                                    esxVI_Occurrence_RequiredItem,
2070
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2071
        goto cleanup;
2072 2073 2074
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2075
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2076
                  _("Could not set max-memory to %lu kilobytes"), memory);
M
Matthias Bolte 已提交
2077
        goto cleanup;
2078 2079
    }

M
Matthias Bolte 已提交
2080 2081
    result = 0;

2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainSetMemory(virDomainPtr domain, unsigned long memory)
{
M
Matthias Bolte 已提交
2095
    int result = -1;
M
Matthias Bolte 已提交
2096
    esxPrivate *priv = domain->conn->privateData;
2097 2098 2099 2100 2101
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

2102
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2103
        return -1;
2104 2105
    }

2106
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2107
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2108
           priv->autoAnswer) < 0 ||
2109 2110 2111
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0 ||
        esxVI_Long_Alloc(&spec->memoryAllocation->limit) < 0) {
M
Matthias Bolte 已提交
2112
        goto cleanup;
2113 2114 2115 2116 2117
    }

    spec->memoryAllocation->limit->value =
      memory / 1024; /* Scale from kilobytes to megabytes */

2118
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2119
                              &task) < 0 ||
2120
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2121
                                    esxVI_Occurrence_RequiredItem,
2122
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2123
        goto cleanup;
2124 2125 2126
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2127
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2128
                  _("Could not set memory to %lu kilobytes"), memory);
M
Matthias Bolte 已提交
2129
        goto cleanup;
2130 2131
    }

M
Matthias Bolte 已提交
2132 2133
    result = 0;

2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info)
{
M
Matthias Bolte 已提交
2147
    int result = -1;
M
Matthias Bolte 已提交
2148
    esxPrivate *priv = domain->conn->privateData;
2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int64_t memory_limit = -1;
    esxVI_PerfMetricId *perfMetricId = NULL;
    esxVI_PerfMetricId *perfMetricIdList = NULL;
    esxVI_Int *counterId = NULL;
    esxVI_Int *counterIdList = NULL;
    esxVI_PerfCounterInfo *perfCounterInfo = NULL;
    esxVI_PerfCounterInfo *perfCounterInfoList = NULL;
    esxVI_PerfQuerySpec *querySpec = NULL;
2161 2162
    esxVI_PerfEntityMetricBase *perfEntityMetricBase = NULL;
    esxVI_PerfEntityMetricBase *perfEntityMetricBaseList = NULL;
2163 2164 2165 2166
    esxVI_PerfEntityMetric *perfEntityMetric = NULL;
    esxVI_PerfMetricIntSeries *perfMetricIntSeries = NULL;
    esxVI_Long *value = NULL;

M
Matthias Bolte 已提交
2167 2168
    memset(info, 0, sizeof (*info));

2169
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2170
        return -1;
2171 2172
    }

2173
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2174 2175 2176 2177
                                           "runtime.powerState\0"
                                           "config.hardware.memoryMB\0"
                                           "config.hardware.numCPU\0"
                                           "config.memoryAllocation.limit\0") < 0 ||
2178
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2179
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2180
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2181
        goto cleanup;
2182 2183 2184 2185 2186 2187 2188 2189
    }

    info->state = VIR_DOMAIN_NOSTATE;

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.powerState")) {
            if (esxVI_VirtualMachinePowerState_CastFromAnyType
2190
                  (dynamicProperty->val, &powerState) < 0) {
M
Matthias Bolte 已提交
2191
                goto cleanup;
2192 2193
            }

2194 2195
            info->state = esxVI_VirtualMachinePowerState_ConvertToLibvirt
                            (powerState);
2196
        } else if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2197
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2198
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2199
                goto cleanup;
2200 2201 2202 2203
            }

            info->maxMem = dynamicProperty->val->int32 * 1024; /* Scale from megabyte to kilobyte */
        } else if (STREQ(dynamicProperty->name, "config.hardware.numCPU")) {
2204
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2205
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2206
                goto cleanup;
2207 2208 2209 2210 2211
            }

            info->nrVirtCpu = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "config.memoryAllocation.limit")) {
2212
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2213
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
2214
                goto cleanup;
2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230
            }

            memory_limit = dynamicProperty->val->int64;

            if (memory_limit > 0) {
                memory_limit *= 1024; /* Scale from megabyte to kilobyte */
            }
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    /* memory_limit < 0 means no memory limit is set */
    info->memory = memory_limit < 0 ? info->maxMem : memory_limit;

    /* Verify the cached 'used CPU time' performance counter ID */
2231 2232 2233 2234 2235 2236
    /* FIXME: Currently no host for a vpx:// connection */
    if (priv->host != NULL) {
        if (info->state == VIR_DOMAIN_RUNNING && priv->usedCpuTimeCounterId >= 0) {
            if (esxVI_Int_Alloc(&counterId) < 0) {
                goto cleanup;
            }
2237

2238
            counterId->value = priv->usedCpuTimeCounterId;
2239

2240 2241 2242
            if (esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                goto cleanup;
            }
2243

2244 2245 2246 2247
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfo) < 0) {
                goto cleanup;
            }
2248

2249 2250 2251 2252 2253
            if (STRNEQ(perfCounterInfo->groupInfo->key, "cpu") ||
                STRNEQ(perfCounterInfo->nameInfo->key, "used") ||
                STRNEQ(perfCounterInfo->unitInfo->key, "millisecond")) {
                VIR_DEBUG("Cached usedCpuTimeCounterId %d is invalid",
                          priv->usedCpuTimeCounterId);
2254

2255 2256 2257 2258 2259
                priv->usedCpuTimeCounterId = -1;
            }

            esxVI_Int_Free(&counterIdList);
            esxVI_PerfCounterInfo_Free(&perfCounterInfo);
2260 2261
        }

2262 2263 2264 2265 2266 2267 2268 2269 2270 2271
        /*
         * Query the PerformanceManager for the 'used CPU time' performance
         * counter ID and cache it, if it's not already cached.
         */
        if (info->state == VIR_DOMAIN_RUNNING && priv->usedCpuTimeCounterId < 0) {
            if (esxVI_QueryAvailablePerfMetric(priv->host, virtualMachine->obj,
                                               NULL, NULL, NULL,
                                               &perfMetricIdList) < 0) {
                goto cleanup;
            }
2272

2273 2274 2275 2276
            for (perfMetricId = perfMetricIdList; perfMetricId != NULL;
                 perfMetricId = perfMetricId->_next) {
                VIR_DEBUG("perfMetricId counterId %d, instance '%s'",
                          perfMetricId->counterId->value, perfMetricId->instance);
2277

2278
                counterId = NULL;
2279

2280 2281 2282 2283 2284
                if (esxVI_Int_DeepCopy(&counterId, perfMetricId->counterId) < 0 ||
                    esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                    goto cleanup;
                }
            }
2285

2286 2287
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfoList) < 0) {
M
Matthias Bolte 已提交
2288
                goto cleanup;
2289 2290
            }

2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307
            for (perfCounterInfo = perfCounterInfoList; perfCounterInfo != NULL;
                 perfCounterInfo = perfCounterInfo->_next) {
                VIR_DEBUG("perfCounterInfo key %d, nameInfo '%s', groupInfo '%s', "
                          "unitInfo '%s', rollupType %d, statsType %d",
                          perfCounterInfo->key->value,
                          perfCounterInfo->nameInfo->key,
                          perfCounterInfo->groupInfo->key,
                          perfCounterInfo->unitInfo->key,
                          perfCounterInfo->rollupType,
                          perfCounterInfo->statsType);

                if (STREQ(perfCounterInfo->groupInfo->key, "cpu") &&
                    STREQ(perfCounterInfo->nameInfo->key, "used") &&
                    STREQ(perfCounterInfo->unitInfo->key, "millisecond")) {
                    priv->usedCpuTimeCounterId = perfCounterInfo->key->value;
                    break;
                }
2308 2309
            }

2310 2311 2312
            if (priv->usedCpuTimeCounterId < 0) {
                VIR_WARN0("Could not find 'used CPU time' performance counter");
            }
2313 2314
        }

2315 2316 2317 2318 2319 2320
        /*
         * Query the PerformanceManager for the 'used CPU time' performance
         * counter value.
         */
        if (info->state == VIR_DOMAIN_RUNNING && priv->usedCpuTimeCounterId >= 0) {
            VIR_DEBUG("usedCpuTimeCounterId %d BEGIN", priv->usedCpuTimeCounterId);
2321

2322 2323 2324 2325 2326 2327
            if (esxVI_PerfQuerySpec_Alloc(&querySpec) < 0 ||
                esxVI_Int_Alloc(&querySpec->maxSample) < 0 ||
                esxVI_PerfMetricId_Alloc(&querySpec->metricId) < 0 ||
                esxVI_Int_Alloc(&querySpec->metricId->counterId) < 0) {
                goto cleanup;
            }
2328

2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341
            querySpec->entity = virtualMachine->obj;
            querySpec->maxSample->value = 1;
            querySpec->metricId->counterId->value = priv->usedCpuTimeCounterId;
            querySpec->metricId->instance = (char *)"";
            querySpec->format = (char *)"normal";

            if (esxVI_QueryPerf(priv->host, querySpec,
                                &perfEntityMetricBaseList) < 0) {
                querySpec->entity = NULL;
                querySpec->metricId->instance = NULL;
                querySpec->format = NULL;
                goto cleanup;
            }
2342

2343 2344 2345 2346
            for (perfEntityMetricBase = perfEntityMetricBaseList;
                 perfEntityMetricBase != NULL;
                 perfEntityMetricBase = perfEntityMetricBase->_next) {
                VIR_DEBUG0("perfEntityMetric ...");
2347

2348 2349
                perfEntityMetric =
                  esxVI_PerfEntityMetric_DynamicCast(perfEntityMetricBase);
2350

2351 2352 2353
                if (perfMetricIntSeries == NULL) {
                    VIR_ERROR0(_("QueryPerf returned object with unexpected type"));
                }
2354

2355 2356
                perfMetricIntSeries =
                  esxVI_PerfMetricIntSeries_DynamicCast(perfEntityMetric->value);
2357

2358 2359 2360
                if (perfMetricIntSeries == NULL) {
                    VIR_ERROR0(_("QueryPerf returned object with unexpected type"));
                }
2361

2362 2363 2364
                for (; perfMetricIntSeries != NULL;
                     perfMetricIntSeries = perfMetricIntSeries->_next) {
                    VIR_DEBUG0("perfMetricIntSeries ...");
2365

2366 2367 2368 2369 2370
                    for (value = perfMetricIntSeries->value;
                         value != NULL;
                         value = value->_next) {
                        VIR_DEBUG("value %lld", (long long int)value->value);
                    }
2371 2372 2373
                }
            }

2374 2375 2376
            querySpec->entity = NULL;
            querySpec->metricId->instance = NULL;
            querySpec->format = NULL;
2377

2378
            VIR_DEBUG("usedCpuTimeCounterId %d END", priv->usedCpuTimeCounterId);
M
Matthias Bolte 已提交
2379

2380 2381 2382 2383 2384
            /*
             * FIXME: Cannot map between realtive used-cpu-time and absolute
             *        info->cpuTime
             */
        }
2385 2386
    }

M
Matthias Bolte 已提交
2387 2388
    result = 0;

2389 2390 2391 2392 2393 2394 2395
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_PerfMetricId_Free(&perfMetricIdList);
    esxVI_Int_Free(&counterIdList);
    esxVI_PerfCounterInfo_Free(&perfCounterInfoList);
    esxVI_PerfQuerySpec_Free(&querySpec);
2396
    esxVI_PerfEntityMetricBase_Free(&perfEntityMetricBaseList);
2397 2398 2399 2400 2401 2402 2403 2404 2405

    return result;
}



static int
esxDomainSetVcpus(virDomainPtr domain, unsigned int nvcpus)
{
M
Matthias Bolte 已提交
2406
    int result = -1;
M
Matthias Bolte 已提交
2407
    esxPrivate *priv = domain->conn->privateData;
M
Matthias Bolte 已提交
2408
    int maxVcpus;
2409 2410 2411 2412 2413 2414
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

    if (nvcpus < 1) {
2415 2416
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Requested number of virtual CPUs must at least be 1"));
M
Matthias Bolte 已提交
2417
        return -1;
2418 2419
    }

2420
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2421
        return -1;
2422 2423
    }

M
Matthias Bolte 已提交
2424
    maxVcpus = esxDomainGetMaxVcpus(domain);
2425

M
Matthias Bolte 已提交
2426
    if (maxVcpus < 0) {
M
Matthias Bolte 已提交
2427
        return -1;
2428 2429
    }

M
Matthias Bolte 已提交
2430
    if (nvcpus > maxVcpus) {
2431
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2432 2433
                  _("Requested number of virtual CPUs is greater than max "
                    "allowable number of virtual CPUs for the domain: %d > %d"),
M
Matthias Bolte 已提交
2434
                  nvcpus, maxVcpus);
M
Matthias Bolte 已提交
2435
        return -1;
2436 2437
    }

2438
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2439
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2440
           priv->autoAnswer) < 0 ||
2441 2442
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Int_Alloc(&spec->numCPUs) < 0) {
M
Matthias Bolte 已提交
2443
        goto cleanup;
2444 2445 2446 2447
    }

    spec->numCPUs->value = nvcpus;

2448
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2449
                              &task) < 0 ||
2450
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2451
                                    esxVI_Occurrence_RequiredItem,
2452
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2453
        goto cleanup;
2454 2455 2456
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2457
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2458
                  _("Could not set number of virtual CPUs to %d"), nvcpus);
M
Matthias Bolte 已提交
2459
        goto cleanup;
2460 2461
    }

M
Matthias Bolte 已提交
2462 2463
    result = 0;

2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainGetMaxVcpus(virDomainPtr domain)
{
M
Matthias Bolte 已提交
2477
    esxPrivate *priv = domain->conn->privateData;
2478 2479 2480 2481
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

M
Matthias Bolte 已提交
2482 2483
    if (priv->maxVcpus > 0) {
        return priv->maxVcpus;
2484 2485
    }

M
Matthias Bolte 已提交
2486 2487
    priv->maxVcpus = -1;

2488
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2489
        return -1;
2490 2491
    }

2492
    if (esxVI_String_AppendValueToList(&propertyNameList,
2493
                                       "capability.maxSupportedVcpus") < 0 ||
2494 2495
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
2496
        goto cleanup;
2497 2498 2499
    }

    if (hostSystem == NULL) {
2500 2501
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
2502
        goto cleanup;
2503 2504 2505 2506 2507
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "capability.maxSupportedVcpus")) {
2508
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2509
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2510
                goto cleanup;
2511 2512
            }

M
Matthias Bolte 已提交
2513
            priv->maxVcpus = dynamicProperty->val->int32;
2514 2515 2516 2517 2518 2519 2520 2521 2522 2523
            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
2524
    return priv->maxVcpus;
2525 2526 2527 2528 2529 2530 2531
}



static char *
esxDomainDumpXML(virDomainPtr domain, int flags)
{
M
Matthias Bolte 已提交
2532
    esxPrivate *priv = domain->conn->privateData;
2533 2534
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
2535
    char *vmPathName = NULL;
2536
    char *datastoreName = NULL;
M
Matthias Bolte 已提交
2537 2538
    char *directoryName = NULL;
    char *fileName = NULL;
2539
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
2540 2541
    char *url = NULL;
    char *vmx = NULL;
2542 2543
    esxVMX_Context ctx;
    esxVMX_Data data;
2544 2545 2546
    virDomainDefPtr def = NULL;
    char *xml = NULL;

2547
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2548
        return NULL;
2549 2550
    }

2551
    if (esxVI_String_AppendValueToList(&propertyNameList,
2552
                                       "config.files.vmPathName") < 0 ||
2553
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2554
                                         propertyNameList, &virtualMachine,
2555 2556 2557
                                         esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_GetStringValue(virtualMachine, "config.files.vmPathName",
                             &vmPathName, esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2558
        goto cleanup;
2559 2560
    }

2561 2562
    if (esxUtil_ParseDatastorePath(vmPathName, &datastoreName, &directoryName,
                                   &fileName) < 0) {
M
Matthias Bolte 已提交
2563
        goto cleanup;
2564 2565
    }

2566 2567
    virBufferVSprintf(&buffer, "%s://%s:%d/folder/", priv->transport,
                      domain->conn->uri->server, domain->conn->uri->port);
M
Matthias Bolte 已提交
2568 2569 2570 2571 2572 2573 2574

    if (directoryName != NULL) {
        virBufferURIEncodeString(&buffer, directoryName);
        virBufferAddChar(&buffer, '/');
    }

    virBufferURIEncodeString(&buffer, fileName);
2575
    virBufferAddLit(&buffer, "?dcPath=");
2576
    virBufferURIEncodeString(&buffer, priv->primary->datacenter->name);
2577 2578 2579 2580
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
2581
        virReportOOMError();
M
Matthias Bolte 已提交
2582
        goto cleanup;
2583 2584
    }

2585 2586
    url = virBufferContentAndReset(&buffer);

2587
    if (esxVI_Context_DownloadFile(priv->primary, url, &vmx) < 0) {
M
Matthias Bolte 已提交
2588
        goto cleanup;
2589 2590
    }

2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601
    data.ctx = priv->primary;
    data.datastoreName = datastoreName;
    data.directoryName = directoryName;

    ctx.opaque = &data;
    ctx.parseFileName = esxParseVMXFileName;
    ctx.formatFileName = NULL;
    ctx.autodetectSCSIControllerModel = NULL;

    def = esxVMX_ParseConfig(&ctx, priv->caps, vmx,
                             priv->primary->productVersion);
2602 2603

    if (def != NULL) {
2604
        xml = virDomainDefFormat(def, flags);
2605 2606 2607
    }

  cleanup:
M
Matthias Bolte 已提交
2608 2609 2610 2611
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

2612 2613
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2614
    VIR_FREE(datastoreName);
M
Matthias Bolte 已提交
2615 2616
    VIR_FREE(directoryName);
    VIR_FREE(fileName);
2617 2618
    VIR_FREE(url);
    VIR_FREE(vmx);
2619
    virDomainDefFree(def);
2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630

    return xml;
}



static char *
esxDomainXMLFromNative(virConnectPtr conn, const char *nativeFormat,
                       const char *nativeConfig,
                       unsigned int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2631
    esxPrivate *priv = conn->privateData;
2632 2633
    esxVMX_Context ctx;
    esxVMX_Data data;
2634 2635 2636 2637
    virDomainDefPtr def = NULL;
    char *xml = NULL;

    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2638
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2639
                  _("Unsupported config format '%s'"), nativeFormat);
2640
        return NULL;
2641 2642
    }

2643 2644 2645 2646 2647 2648 2649 2650 2651 2652
    data.ctx = priv->primary;
    data.datastoreName = "?";
    data.directoryName = "?";

    ctx.opaque = &data;
    ctx.parseFileName = esxParseVMXFileName;
    ctx.formatFileName = NULL;
    ctx.autodetectSCSIControllerModel = NULL;

    def = esxVMX_ParseConfig(&ctx, priv->caps, nativeConfig,
2653
                             priv->primary->productVersion);
2654 2655

    if (def != NULL) {
2656
        xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
2657 2658 2659 2660 2661 2662 2663 2664 2665
    }

    virDomainDefFree(def);

    return xml;
}



M
Matthias Bolte 已提交
2666 2667 2668 2669 2670
static char *
esxDomainXMLToNative(virConnectPtr conn, const char *nativeFormat,
                     const char *domainXml,
                     unsigned int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2671
    esxPrivate *priv = conn->privateData;
2672 2673
    esxVMX_Context ctx;
    esxVMX_Data data;
M
Matthias Bolte 已提交
2674 2675 2676 2677
    virDomainDefPtr def = NULL;
    char *vmx = NULL;

    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2678
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2679
                  _("Unsupported config format '%s'"), nativeFormat);
M
Matthias Bolte 已提交
2680 2681 2682
        return NULL;
    }

2683
    def = virDomainDefParseString(priv->caps, domainXml, 0);
M
Matthias Bolte 已提交
2684 2685 2686 2687 2688

    if (def == NULL) {
        return NULL;
    }

2689 2690 2691 2692 2693 2694 2695 2696 2697 2698
    data.ctx = priv->primary;
    data.datastoreName = NULL;
    data.directoryName = NULL;

    ctx.opaque = &data;
    ctx.parseFileName = NULL;
    ctx.formatFileName = esxFormatVMXFileName;
    ctx.autodetectSCSIControllerModel = esxAutodetectSCSIControllerModel;

    vmx = esxVMX_FormatConfig(&ctx, priv->caps, def,
2699
                              priv->primary->productVersion);
M
Matthias Bolte 已提交
2700 2701 2702 2703 2704 2705 2706 2707

    virDomainDefFree(def);

    return vmx;
}



2708 2709 2710
static int
esxListDefinedDomains(virConnectPtr conn, char **const names, int maxnames)
{
M
Matthias Bolte 已提交
2711
    bool success = false;
M
Matthias Bolte 已提交
2712
    esxPrivate *priv = conn->privateData;
2713 2714 2715 2716 2717 2718
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;
2719
    int i;
2720 2721

    if (names == NULL || maxnames < 0) {
2722 2723
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
2724 2725 2726 2727 2728 2729
    }

    if (maxnames == 0) {
        return 0;
    }

2730
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2731
        return -1;
2732 2733
    }

2734
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2735 2736
                                           "name\0"
                                           "runtime.powerState\0") < 0 ||
2737 2738
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2739
        goto cleanup;
2740 2741 2742 2743
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
2744
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
2745
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
2746
            goto cleanup;
2747 2748 2749 2750 2751 2752 2753 2754 2755 2756
        }

        if (powerState == esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

        for (dynamicProperty = virtualMachine->propSet;
             dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "name")) {
2757
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2758
                                             esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
2759
                    goto cleanup;
2760 2761 2762 2763 2764
                }

                names[count] = strdup(dynamicProperty->val->string);

                if (names[count] == NULL) {
2765
                    virReportOOMError();
M
Matthias Bolte 已提交
2766
                    goto cleanup;
2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778
                }

                count++;
                break;
            }
        }

        if (count >= maxnames) {
            break;
        }
    }

M
Matthias Bolte 已提交
2779
    success = true;
2780

M
Matthias Bolte 已提交
2781 2782 2783 2784 2785
  cleanup:
    if (! success) {
        for (i = 0; i < count; ++i) {
            VIR_FREE(names[i]);
        }
2786

M
Matthias Bolte 已提交
2787
        count = -1;
2788 2789
    }

M
Matthias Bolte 已提交
2790 2791
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
2792

M
Matthias Bolte 已提交
2793
    return count;
2794 2795 2796 2797 2798 2799 2800
}



static int
esxNumberOfDefinedDomains(virConnectPtr conn)
{
M
Matthias Bolte 已提交
2801
    esxPrivate *priv = conn->privateData;
2802

2803
    if (esxVI_EnsureSession(priv->primary) < 0) {
2804 2805 2806
        return -1;
    }

2807
    return esxVI_LookupNumberOfDomainsByPowerState
2808
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn,
2809 2810 2811 2812 2813 2814
              esxVI_Boolean_True);
}



static int
2815
esxDomainCreateWithFlags(virDomainPtr domain, unsigned int flags)
2816
{
M
Matthias Bolte 已提交
2817
    int result = -1;
M
Matthias Bolte 已提交
2818
    esxPrivate *priv = domain->conn->privateData;
2819 2820 2821
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
2822
    int id = -1;
2823 2824 2825
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

2826 2827
    virCheckFlags(0, -1);

2828
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2829
        return -1;
2830 2831
    }

2832
    if (esxVI_String_AppendValueToList(&propertyNameList,
2833
                                       "runtime.powerState") < 0 ||
2834
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2835
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
2836
           priv->autoAnswer) < 0 ||
2837 2838
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0) {
M
Matthias Bolte 已提交
2839
        goto cleanup;
2840 2841 2842
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2843 2844
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered off"));
M
Matthias Bolte 已提交
2845
        goto cleanup;
2846 2847
    }

2848
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
2849
                             &task) < 0 ||
2850
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2851
                                    esxVI_Occurrence_RequiredItem,
2852
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2853
        goto cleanup;
2854 2855 2856
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2857
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not start domain"));
M
Matthias Bolte 已提交
2858
        goto cleanup;
2859 2860
    }

2861
    domain->id = id;
M
Matthias Bolte 已提交
2862 2863
    result = 0;

2864 2865 2866 2867 2868 2869 2870 2871
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}

2872 2873 2874 2875 2876
static int
esxDomainCreate(virDomainPtr domain)
{
    return esxDomainCreateWithFlags(domain, 0);
}
2877

M
Matthias Bolte 已提交
2878 2879 2880
static virDomainPtr
esxDomainDefineXML(virConnectPtr conn, const char *xml ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2881
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
2882 2883
    virDomainDefPtr def = NULL;
    char *vmx = NULL;
2884 2885
    int i;
    virDomainDiskDefPtr disk = NULL;
M
Matthias Bolte 已提交
2886
    esxVI_ObjectContent *virtualMachine = NULL;
2887 2888
    esxVMX_Context ctx;
    esxVMX_Data data;
M
Matthias Bolte 已提交
2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901
    char *datastoreName = NULL;
    char *directoryName = NULL;
    char *fileName = NULL;
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    char *url = NULL;
    char *datastoreRelatedPath = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_ManagedObjectReference *resourcePool = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
    virDomainPtr domain = NULL;

2902
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2903
        return NULL;
M
Matthias Bolte 已提交
2904 2905 2906
    }

    /* Parse domain XML */
2907
    def = virDomainDefParseString(priv->caps, xml,
M
Matthias Bolte 已提交
2908 2909 2910
                                  VIR_DOMAIN_XML_INACTIVE);

    if (def == NULL) {
M
Matthias Bolte 已提交
2911
        return NULL;
M
Matthias Bolte 已提交
2912 2913 2914
    }

    /* Check if an existing domain should be edited */
2915
    if (esxVI_LookupVirtualMachineByUuid(priv->primary, def->uuid, NULL,
M
Matthias Bolte 已提交
2916
                                         &virtualMachine,
M
Matthias Bolte 已提交
2917
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
2918
        goto cleanup;
M
Matthias Bolte 已提交
2919 2920 2921 2922
    }

    if (virtualMachine != NULL) {
        /* FIXME */
2923 2924 2925
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Domain already exists, editing existing domains is not "
                    "supported yet"));
M
Matthias Bolte 已提交
2926
        goto cleanup;
M
Matthias Bolte 已提交
2927 2928 2929
    }

    /* Build VMX from domain XML */
2930 2931 2932 2933 2934 2935 2936 2937 2938 2939
    data.ctx = priv->primary;
    data.datastoreName = NULL;
    data.directoryName = NULL;

    ctx.opaque = &data;
    ctx.parseFileName = NULL;
    ctx.formatFileName = esxFormatVMXFileName;
    ctx.autodetectSCSIControllerModel = esxAutodetectSCSIControllerModel;

    vmx = esxVMX_FormatConfig(&ctx, priv->caps, def,
2940
                              priv->primary->productVersion);
M
Matthias Bolte 已提交
2941 2942

    if (vmx == NULL) {
M
Matthias Bolte 已提交
2943
        goto cleanup;
M
Matthias Bolte 已提交
2944 2945
    }

2946 2947 2948 2949 2950 2951 2952
    /*
     * Build VMX datastore URL. Use the source of the first file-based harddisk
     * to deduce the datastore and path for the VMX file. Don't just use the
     * first disk, because it may be CDROM disk and ISO images are normaly not
     * located in the virtual machine's directory. This approach to deduce the
     * datastore isn't perfect but should work in the majority of cases.
     */
M
Matthias Bolte 已提交
2953
    if (def->ndisks < 1) {
2954 2955 2956
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Domain XML doesn't contain any disks, cannot deduce "
                    "datastore and path for VMX file"));
M
Matthias Bolte 已提交
2957
        goto cleanup;
2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968
    }

    for (i = 0; i < def->ndisks; ++i) {
        if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK &&
            def->disks[i]->type == VIR_DOMAIN_DISK_TYPE_FILE) {
            disk = def->disks[i];
            break;
        }
    }

    if (disk == NULL) {
2969 2970 2971
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Domain XML doesn't contain any file-based harddisks, "
                    "cannot deduce datastore and path for VMX file"));
M
Matthias Bolte 已提交
2972
        goto cleanup;
M
Matthias Bolte 已提交
2973 2974
    }

2975
    if (disk->src == NULL) {
2976 2977 2978
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("First file-based harddisk has no source, cannot deduce "
                    "datastore and path for VMX file"));
M
Matthias Bolte 已提交
2979
        goto cleanup;
M
Matthias Bolte 已提交
2980 2981
    }

2982 2983
    if (esxUtil_ParseDatastorePath(disk->src, &datastoreName, &directoryName,
                                   &fileName) < 0) {
M
Matthias Bolte 已提交
2984
        goto cleanup;
M
Matthias Bolte 已提交
2985 2986
    }

2987
    if (! virFileHasSuffix(fileName, ".vmdk")) {
2988
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2989 2990
                  _("Expecting source '%s' of first file-based harddisk to "
                    "be a VMDK image"), disk->src);
M
Matthias Bolte 已提交
2991
        goto cleanup;
M
Matthias Bolte 已提交
2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003
    }

    virBufferVSprintf(&buffer, "%s://%s:%d/folder/", priv->transport,
                      conn->uri->server, conn->uri->port);

    if (directoryName != NULL) {
        virBufferURIEncodeString(&buffer, directoryName);
        virBufferAddChar(&buffer, '/');
    }

    virBufferURIEncodeString(&buffer, def->name);
    virBufferAddLit(&buffer, ".vmx?dcPath=");
3004
    virBufferURIEncodeString(&buffer, priv->primary->datacenter->name);
M
Matthias Bolte 已提交
3005 3006 3007 3008
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
3009
        virReportOOMError();
M
Matthias Bolte 已提交
3010
        goto cleanup;
M
Matthias Bolte 已提交
3011 3012 3013 3014 3015 3016 3017
    }

    url = virBufferContentAndReset(&buffer);

    if (directoryName != NULL) {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s/%s.vmx", datastoreName,
                        directoryName, def->name) < 0) {
3018
            virReportOOMError();
M
Matthias Bolte 已提交
3019
            goto cleanup;
M
Matthias Bolte 已提交
3020 3021 3022 3023
        }
    } else {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s.vmx", datastoreName,
                        def->name) < 0) {
3024
            virReportOOMError();
M
Matthias Bolte 已提交
3025
            goto cleanup;
M
Matthias Bolte 已提交
3026 3027 3028 3029 3030 3031 3032
        }
    }

    /* Check, if VMX file already exists */
    /* FIXME */

    /* Upload VMX file */
3033
    if (esxVI_Context_UploadFile(priv->primary, url, vmx) < 0) {
M
Matthias Bolte 已提交
3034
        goto cleanup;
M
Matthias Bolte 已提交
3035 3036 3037
    }

    /* Register the domain */
3038
    if (esxVI_RegisterVM_Task(priv->primary, priv->primary->datacenter->vmFolder,
M
Matthias Bolte 已提交
3039
                              datastoreRelatedPath, NULL, esxVI_Boolean_False,
3040 3041 3042 3043
                              priv->primary->computeResource->resourcePool,
                              priv->primary->hostSystem->_reference,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, def->uuid,
3044
                                    esxVI_Occurrence_OptionalItem,
3045
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3046
        goto cleanup;
M
Matthias Bolte 已提交
3047 3048 3049
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3050
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not define domain"));
M
Matthias Bolte 已提交
3051
        goto cleanup;
M
Matthias Bolte 已提交
3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062
    }

    domain = virGetDomain(conn, def->name, def->uuid);

    if (domain != NULL) {
        domain->id = -1;
    }

    /* FIXME: Add proper rollback in case of an error */

  cleanup:
M
Matthias Bolte 已提交
3063 3064 3065 3066
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

M
Matthias Bolte 已提交
3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084
    virDomainDefFree(def);
    VIR_FREE(vmx);
    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
    VIR_FREE(fileName);
    VIR_FREE(url);
    VIR_FREE(datastoreRelatedPath);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_ManagedObjectReference_Free(&resourcePool);
    esxVI_ManagedObjectReference_Free(&task);

    return domain;
}



3085 3086 3087
static int
esxDomainUndefine(virDomainPtr domain)
{
M
Matthias Bolte 已提交
3088
    int result = -1;
M
Matthias Bolte 已提交
3089
    esxPrivate *priv = domain->conn->privateData;
3090
    esxVI_Context *ctx = NULL;
3091 3092 3093 3094
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

3095 3096 3097 3098 3099 3100
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

3101
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
3102
        return -1;
3103 3104
    }

3105
    if (esxVI_String_AppendValueToList(&propertyNameList,
3106
                                       "runtime.powerState") < 0 ||
3107 3108
        esxVI_LookupVirtualMachineByUuid(ctx, domain->uuid, propertyNameList,
                                         &virtualMachine,
M
Matthias Bolte 已提交
3109
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3110
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
3111
        goto cleanup;
3112 3113 3114 3115
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended &&
        powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
3116 3117
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not suspended or powered off"));
M
Matthias Bolte 已提交
3118
        goto cleanup;
3119 3120
    }

3121
    if (esxVI_UnregisterVM(ctx, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
3122
        goto cleanup;
3123 3124
    }

M
Matthias Bolte 已提交
3125 3126
    result = 0;

3127 3128 3129 3130 3131 3132 3133 3134 3135
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147
/*
 * The scheduler interface exposes basically the CPU ResourceAllocationInfo:
 *
 * - http://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.ResourceAllocationInfo.html
 * - http://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.SharesInfo.html
 * - http://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.SharesInfo.Level.html
 *
 *
 * Available parameters:
 *
 * - reservation (VIR_DOMAIN_SCHED_FIELD_LLONG >= 0, in megaherz)
 *
3148
 *   The amount of CPU resource that is guaranteed to be available to the domain.
3149 3150 3151 3152
 *
 *
 * - limit (VIR_DOMAIN_SCHED_FIELD_LLONG >= 0, or -1, in megaherz)
 *
3153 3154
 *   The CPU utilization of the domain will be limited to this value, even if
 *   more CPU resources are available. If the limit is set to -1, the CPU
3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165
 *   utilization of the domain is unlimited. If the limit is not set to -1, it
 *   must be greater than or equal to the reservation.
 *
 *
 * - shares (VIR_DOMAIN_SCHED_FIELD_INT >= 0, or in {-1, -2, -3}, no unit)
 *
 *   Shares are used to determine relative CPU allocation between domains. In
 *   general, a domain with more shares gets proportionally more of the CPU
 *   resource. The special values -1, -2 and -3 represent the predefined
 *   SharesLevel 'low', 'normal' and 'high'.
 */
3166
static char *
3167
esxDomainGetSchedulerType(virDomainPtr domain ATTRIBUTE_UNUSED, int *nparams)
3168 3169 3170 3171
{
    char *type = strdup("allocation");

    if (type == NULL) {
3172
        virReportOOMError();
3173
        return NULL;
3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186
    }

    *nparams = 3; /* reservation, limit, shares */

    return type;
}



static int
esxDomainGetSchedulerParameters(virDomainPtr domain,
                                virSchedParameterPtr params, int *nparams)
{
M
Matthias Bolte 已提交
3187
    int result = -1;
M
Matthias Bolte 已提交
3188
    esxPrivate *priv = domain->conn->privateData;
3189 3190 3191 3192 3193 3194 3195 3196
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    unsigned int mask = 0;
    int i = 0;

    if (*nparams < 3) {
3197 3198
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Parameter array must have space for 3 items"));
M
Matthias Bolte 已提交
3199
        return -1;
3200 3201
    }

3202
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3203
        return -1;
3204 3205
    }

3206
    if (esxVI_String_AppendValueListToList(&propertyNameList,
3207 3208 3209
                                           "config.cpuAllocation.reservation\0"
                                           "config.cpuAllocation.limit\0"
                                           "config.cpuAllocation.shares\0") < 0 ||
3210
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
3211
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3212
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3213
        goto cleanup;
3214 3215 3216 3217 3218 3219
    }

    for (dynamicProperty = virtualMachine->propSet;
         dynamicProperty != NULL && mask != 7 && i < 3;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.cpuAllocation.reservation") &&
M
Matthias Bolte 已提交
3220
            ! (mask & (1 << 0))) {
3221 3222 3223 3224 3225
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "reservation");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_LLONG;

3226
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3227
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3228
                goto cleanup;
3229 3230 3231 3232 3233 3234 3235
            }

            params[i].value.l = dynamicProperty->val->int64;
            mask |= 1 << 0;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.limit") &&
M
Matthias Bolte 已提交
3236
                   ! (mask & (1 << 1))) {
3237 3238 3239 3240 3241
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "limit");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_LLONG;

3242
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3243
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3244
                goto cleanup;
3245 3246 3247 3248 3249 3250 3251
            }

            params[i].value.l = dynamicProperty->val->int64;
            mask |= 1 << 1;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.shares") &&
M
Matthias Bolte 已提交
3252
                   ! (mask & (1 << 2))) {
3253 3254 3255 3256 3257
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "shares");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_INT;

3258
            if (esxVI_SharesInfo_CastFromAnyType(dynamicProperty->val,
3259
                                                 &sharesInfo) < 0) {
M
Matthias Bolte 已提交
3260
                goto cleanup;
3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280
            }

            switch (sharesInfo->level) {
              case esxVI_SharesLevel_Custom:
                params[i].value.i = sharesInfo->shares->value;
                break;

              case esxVI_SharesLevel_Low:
                params[i].value.i = -1;
                break;

              case esxVI_SharesLevel_Normal:
                params[i].value.i = -2;
                break;

              case esxVI_SharesLevel_High:
                params[i].value.i = -3;
                break;

              default:
3281
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3282
                          _("Shares level has unknown value %d"),
3283
                          (int)sharesInfo->level);
M
Matthias Bolte 已提交
3284
                goto cleanup;
3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296
            }

            esxVI_SharesInfo_Free(&sharesInfo);

            mask |= 1 << 2;
            ++i;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    *nparams = i;
M
Matthias Bolte 已提交
3297
    result = 0;
3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
}



static int
esxDomainSetSchedulerParameters(virDomainPtr domain,
                                virSchedParameterPtr params, int nparams)
{
M
Matthias Bolte 已提交
3312
    int result = -1;
M
Matthias Bolte 已提交
3313
    esxPrivate *priv = domain->conn->privateData;
3314 3315 3316 3317 3318 3319 3320
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
    int i;

3321
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3322
        return -1;
3323 3324
    }

3325
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3326
          (priv->primary, domain->uuid, NULL, &virtualMachine,
3327
           priv->autoAnswer) < 0 ||
3328 3329
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->cpuAllocation) < 0) {
M
Matthias Bolte 已提交
3330
        goto cleanup;
3331 3332 3333 3334 3335
    }

    for (i = 0; i < nparams; ++i) {
        if (STREQ (params[i].field, "reservation") &&
            params[i].type == VIR_DOMAIN_SCHED_FIELD_LLONG) {
3336
            if (esxVI_Long_Alloc(&spec->cpuAllocation->reservation) < 0) {
M
Matthias Bolte 已提交
3337
                goto cleanup;
3338 3339 3340
            }

            if (params[i].value.l < 0) {
3341
                ESX_ERROR(VIR_ERR_INVALID_ARG,
3342 3343
                          _("Could not set reservation to %lld MHz, expecting "
                            "positive value"), params[i].value.l);
M
Matthias Bolte 已提交
3344
                goto cleanup;
3345 3346 3347 3348 3349
            }

            spec->cpuAllocation->reservation->value = params[i].value.l;
        } else if (STREQ (params[i].field, "limit") &&
                   params[i].type == VIR_DOMAIN_SCHED_FIELD_LLONG) {
3350
            if (esxVI_Long_Alloc(&spec->cpuAllocation->limit) < 0) {
M
Matthias Bolte 已提交
3351
                goto cleanup;
3352 3353 3354
            }

            if (params[i].value.l < -1) {
3355
                ESX_ERROR(VIR_ERR_INVALID_ARG,
3356 3357
                          _("Could not set limit to %lld MHz, expecting "
                            "positive value or -1 (unlimited)"),
3358
                          params[i].value.l);
M
Matthias Bolte 已提交
3359
                goto cleanup;
3360 3361 3362 3363
            }

            spec->cpuAllocation->limit->value = params[i].value.l;
        } else if (STREQ (params[i].field, "shares") &&
3364
                   params[i].type == VIR_DOMAIN_SCHED_FIELD_INT) {
3365 3366
            if (esxVI_SharesInfo_Alloc(&sharesInfo) < 0 ||
                esxVI_Int_Alloc(&sharesInfo->shares) < 0) {
M
Matthias Bolte 已提交
3367
                goto cleanup;
3368 3369 3370 3371
            }

            spec->cpuAllocation->shares = sharesInfo;

3372
            if (params[i].value.i >= 0) {
3373
                spec->cpuAllocation->shares->level = esxVI_SharesLevel_Custom;
3374
                spec->cpuAllocation->shares->shares->value = params[i].value.i;
3375
            } else {
3376
                switch (params[i].value.i) {
3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394
                  case -1:
                    spec->cpuAllocation->shares->level = esxVI_SharesLevel_Low;
                    spec->cpuAllocation->shares->shares->value = -1;
                    break;

                  case -2:
                    spec->cpuAllocation->shares->level =
                      esxVI_SharesLevel_Normal;
                    spec->cpuAllocation->shares->shares->value = -1;
                    break;

                  case -3:
                    spec->cpuAllocation->shares->level =
                      esxVI_SharesLevel_High;
                    spec->cpuAllocation->shares->shares->value = -1;
                    break;

                  default:
3395
                    ESX_ERROR(VIR_ERR_INVALID_ARG,
3396 3397
                              _("Could not set shares to %d, expecting positive "
                                "value or -1 (low), -2 (normal) or -3 (high)"),
3398
                              params[i].value.i);
M
Matthias Bolte 已提交
3399
                    goto cleanup;
3400 3401 3402
                }
            }
        } else {
3403
            ESX_ERROR(VIR_ERR_INVALID_ARG, _("Unknown field '%s'"),
3404
                      params[i].field);
M
Matthias Bolte 已提交
3405
            goto cleanup;
3406 3407 3408
        }
    }

3409
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
3410
                              &task) < 0 ||
3411
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3412
                                    esxVI_Occurrence_RequiredItem,
3413
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3414
        goto cleanup;
3415 3416 3417
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3418 3419
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not change scheduler parameters"));
M
Matthias Bolte 已提交
3420
        goto cleanup;
3421 3422
    }

M
Matthias Bolte 已提交
3423 3424
    result = 0;

3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainMigratePrepare(virConnectPtr dconn,
                        char **cookie ATTRIBUTE_UNUSED,
                        int *cookielen ATTRIBUTE_UNUSED,
3439 3440
                        const char *uri_in ATTRIBUTE_UNUSED,
                        char **uri_out,
3441 3442 3443 3444
                        unsigned long flags ATTRIBUTE_UNUSED,
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
3445
    esxPrivate *priv = dconn->privateData;
3446 3447

    if (uri_in == NULL) {
3448 3449 3450 3451
        if (virAsprintf(uri_out, "vpxmigr://%s/%s/%s",
                        priv->vCenter->ipAddress,
                        priv->vCenter->computeResource->resourcePool->value,
                        priv->vCenter->hostSystem->_reference->value) < 0) {
3452
            virReportOOMError();
3453
            return -1;
3454 3455 3456
        }
    }

3457
    return 0;
3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470
}



static int
esxDomainMigratePerform(virDomainPtr domain,
                        const char *cookie ATTRIBUTE_UNUSED,
                        int cookielen ATTRIBUTE_UNUSED,
                        const char *uri,
                        unsigned long flags ATTRIBUTE_UNUSED,
                        const char *dname,
                        unsigned long bandwidth ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
3471
    int result = -1;
M
Matthias Bolte 已提交
3472
    esxPrivate *priv = domain->conn->privateData;
3473 3474 3475 3476
    xmlURIPtr parsedUri = NULL;
    char *saveptr;
    char *path_resourcePool;
    char *path_hostSystem;
3477
    esxVI_ObjectContent *virtualMachine = NULL;
3478 3479
    esxVI_ManagedObjectReference resourcePool;
    esxVI_ManagedObjectReference hostSystem;
3480 3481 3482 3483
    esxVI_Event *eventList = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

M
Matthias Bolte 已提交
3484
    if (priv->vCenter == NULL) {
3485 3486
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Migration not possible without a vCenter"));
M
Matthias Bolte 已提交
3487
        return -1;
3488 3489 3490
    }

    if (dname != NULL) {
3491 3492
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Renaming domains on migration not supported"));
M
Matthias Bolte 已提交
3493
        return -1;
3494 3495
    }

3496
    if (esxVI_EnsureSession(priv->vCenter) < 0) {
M
Matthias Bolte 已提交
3497
        return -1;
3498 3499
    }

3500 3501
    /* Parse migration URI */
    parsedUri = xmlParseURI(uri);
3502

3503
    if (parsedUri == NULL) {
3504
        virReportOOMError();
M
Matthias Bolte 已提交
3505
        return -1;
3506 3507
    }

3508 3509 3510
    if (parsedUri->scheme == NULL || STRCASENEQ(parsedUri->scheme, "vpxmigr")) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Only vpxmigr:// migration URIs are supported"));
M
Matthias Bolte 已提交
3511
        goto cleanup;
3512 3513
    }

3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526
    if (STRCASENEQ(priv->vCenter->ipAddress, parsedUri->server)) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Migration source and destination have to refer to "
                    "the same vCenter"));
        goto cleanup;
    }

    path_resourcePool = strtok_r(parsedUri->path, "/", &saveptr);
    path_hostSystem = strtok_r(NULL, "", &saveptr);

    if (path_resourcePool == NULL || path_hostSystem == NULL) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Migration URI has to specify resource pool and host system"));
M
Matthias Bolte 已提交
3527
        goto cleanup;
3528 3529
    }

3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543
    resourcePool._next = NULL;
    resourcePool._type = esxVI_Type_ManagedObjectReference;
    resourcePool.type = (char *)"ResourcePool";
    resourcePool.value = path_resourcePool;

    hostSystem._next = NULL;
    hostSystem._type = esxVI_Type_ManagedObjectReference;
    hostSystem.type = (char *)"HostSystem";
    hostSystem.value = path_hostSystem;

    /* Lookup VirtualMachine */
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->vCenter, domain->uuid, NULL, &virtualMachine,
           priv->autoAnswer) < 0) {
M
Matthias Bolte 已提交
3544
        goto cleanup;
3545 3546 3547
    }

    /* Validate the purposed migration */
3548
    if (esxVI_ValidateMigration(priv->vCenter, virtualMachine->obj,
3549 3550
                                esxVI_VirtualMachinePowerState_Undefined, NULL,
                                &resourcePool, &hostSystem, &eventList) < 0) {
M
Matthias Bolte 已提交
3551
        goto cleanup;
3552 3553 3554 3555 3556 3557 3558 3559
    }

    if (eventList != NULL) {
        /*
         * FIXME: Need to report the complete list of events. Limit reporting
         *        to the first event for now.
         */
        if (eventList->fullFormattedMessage != NULL) {
3560
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3561 3562
                      _("Could not migrate domain, validation reported a "
                        "problem: %s"), eventList->fullFormattedMessage);
3563
        } else {
3564 3565 3566
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                      _("Could not migrate domain, validation reported a "
                        "problem"));
3567 3568
        }

M
Matthias Bolte 已提交
3569
        goto cleanup;
3570 3571 3572
    }

    /* Perform the purposed migration */
3573 3574
    if (esxVI_MigrateVM_Task(priv->vCenter, virtualMachine->obj,
                             &resourcePool, &hostSystem,
3575 3576 3577
                             esxVI_VirtualMachineMovePriority_DefaultPriority,
                             esxVI_VirtualMachinePowerState_Undefined,
                             &task) < 0 ||
3578
        esxVI_WaitForTaskCompletion(priv->vCenter, task, domain->uuid,
3579
                                    esxVI_Occurrence_RequiredItem,
3580
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3581
        goto cleanup;
3582 3583 3584
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3585 3586 3587
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not migrate domain, migration task finished with "
                    "an error"));
M
Matthias Bolte 已提交
3588
        goto cleanup;
3589 3590
    }

M
Matthias Bolte 已提交
3591 3592
    result = 0;

3593
  cleanup:
3594
    xmlFreeURI(parsedUri);
3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Event_Free(&eventList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static virDomainPtr
esxDomainMigrateFinish(virConnectPtr dconn, const char *dname,
                       const char *cookie ATTRIBUTE_UNUSED,
                       int cookielen ATTRIBUTE_UNUSED,
                       const char *uri ATTRIBUTE_UNUSED,
                       unsigned long flags ATTRIBUTE_UNUSED)
{
    return esxDomainLookupByName(dconn, dname);
}



M
Matthias Bolte 已提交
3616 3617 3618 3619
static unsigned long long
esxNodeGetFreeMemory(virConnectPtr conn)
{
    unsigned long long result = 0;
M
Matthias Bolte 已提交
3620
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
3621 3622 3623 3624 3625
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *resourcePool = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ResourcePoolResourceUsage *resourcePoolResourceUsage = NULL;

3626
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3627
        return 0;
M
Matthias Bolte 已提交
3628 3629 3630
    }

    /* Get memory usage of resource pool */
3631
    if (esxVI_String_AppendValueToList(&propertyNameList,
M
Matthias Bolte 已提交
3632
                                       "runtime.memory") < 0 ||
3633 3634
        esxVI_LookupObjectContentByType(priv->primary,
                                        priv->primary->computeResource->resourcePool,
3635 3636 3637
                                        "ResourcePool", propertyNameList,
                                        esxVI_Boolean_False,
                                        &resourcePool) < 0) {
M
Matthias Bolte 已提交
3638
        goto cleanup;
M
Matthias Bolte 已提交
3639 3640 3641 3642 3643 3644
    }

    for (dynamicProperty = resourcePool->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.memory")) {
            if (esxVI_ResourcePoolResourceUsage_CastFromAnyType
3645
                  (dynamicProperty->val, &resourcePoolResourceUsage) < 0) {
M
Matthias Bolte 已提交
3646
                goto cleanup;
M
Matthias Bolte 已提交
3647 3648 3649 3650 3651 3652 3653 3654 3655
            }

            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    if (resourcePoolResourceUsage == NULL) {
3656 3657
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve memory usage of resource pool"));
M
Matthias Bolte 已提交
3658
        goto cleanup;
M
Matthias Bolte 已提交
3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672
    }

    result = resourcePoolResourceUsage->unreservedForVm->value;

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&resourcePool);
    esxVI_ResourcePoolResourceUsage_Free(&resourcePoolResourceUsage);

    return result;
}



3673 3674 3675
static int
esxIsEncrypted(virConnectPtr conn)
{
M
Matthias Bolte 已提交
3676
    esxPrivate *priv = conn->privateData;
3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689

    if (STRCASEEQ(priv->transport, "https")) {
        return 1;
    } else {
        return 0;
    }
}



static int
esxIsSecure(virConnectPtr conn)
{
M
Matthias Bolte 已提交
3690
    esxPrivate *priv = conn->privateData;
3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703

    if (STRCASEEQ(priv->transport, "https")) {
        return 1;
    } else {
        return 0;
    }
}



static int
esxDomainIsActive(virDomainPtr domain)
{
M
Matthias Bolte 已提交
3704
    int result = -1;
M
Matthias Bolte 已提交
3705
    esxPrivate *priv = domain->conn->privateData;
3706 3707 3708 3709
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

3710
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3711
        return -1;
3712 3713
    }

3714
    if (esxVI_String_AppendValueToList(&propertyNameList,
3715
                                       "runtime.powerState") < 0 ||
3716
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
3717
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3718
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3719
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
3720
        goto cleanup;
3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        result = 1;
    } else {
        result = 0;
    }

  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
esxDomainIsPersistent(virDomainPtr domain ATTRIBUTE_UNUSED)
{
    /* ESX has no concept of transient domains, so all of them are persistent */
    return 1;
}



3747 3748
static virDomainSnapshotPtr
esxDomainSnapshotCreateXML(virDomainPtr domain, const char *xmlDesc,
3749
                           unsigned int flags)
3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760
{
    esxPrivate *priv = domain->conn->privateData;
    virDomainSnapshotDefPtr def = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
    virDomainSnapshotPtr snapshot = NULL;

3761 3762
    virCheckFlags(0, NULL);

3763
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3764
        return NULL;
3765 3766 3767 3768 3769
    }

    def = virDomainSnapshotDefParseString(xmlDesc, 1);

    if (def == NULL) {
M
Matthias Bolte 已提交
3770
        return NULL;
3771 3772 3773
    }

    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3774
          (priv->primary, domain->uuid, NULL, &virtualMachine,
3775
           priv->autoAnswer) < 0 ||
3776
        esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
3777 3778 3779 3780
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, def->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
3781
        goto cleanup;
3782 3783 3784 3785 3786
    }

    if (snapshotTree != NULL) {
        ESX_ERROR(VIR_ERR_OPERATION_INVALID,
                  _("Snapshot '%s' already exists"), def->name);
M
Matthias Bolte 已提交
3787
        goto cleanup;
3788 3789
    }

3790
    if (esxVI_CreateSnapshot_Task(priv->primary, virtualMachine->obj,
3791 3792 3793
                                  def->name, def->description,
                                  esxVI_Boolean_True,
                                  esxVI_Boolean_False, &task) < 0 ||
3794
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3795
                                    esxVI_Occurrence_RequiredItem,
3796
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3797
        goto cleanup;
3798 3799 3800 3801
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not create snapshot"));
M
Matthias Bolte 已提交
3802
        goto cleanup;
3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819
    }

    snapshot = virGetDomainSnapshot(domain, def->name);

  cleanup:
    virDomainSnapshotDefFree(def);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);

    return snapshot;
}



static char *
esxDomainSnapshotDumpXML(virDomainSnapshotPtr snapshot,
3820
                         unsigned int flags)
3821 3822 3823 3824 3825 3826 3827 3828 3829
{
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    virDomainSnapshotDef def;
    char uuid_string[VIR_UUID_STRING_BUFLEN] = "";
    char *xml = NULL;

3830 3831
    virCheckFlags(0, NULL);

M
Matthias Bolte 已提交
3832
    memset(&def, 0, sizeof (def));
3833

3834
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3835
        return NULL;
3836 3837
    }

3838
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
3839 3840 3841 3842
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3843
        goto cleanup;
3844 3845 3846 3847 3848 3849 3850 3851
    }

    def.name = snapshot->name;
    def.description = snapshotTree->description;
    def.parent = snapshotTreeParent != NULL ? snapshotTreeParent->name : NULL;

    if (esxVI_DateTime_ConvertToCalendarTime(snapshotTree->createTime,
                                             &def.creationTime) < 0) {
M
Matthias Bolte 已提交
3852
        goto cleanup;
3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870
    }

    def.state = esxVI_VirtualMachinePowerState_ConvertToLibvirt
                  (snapshotTree->state);

    virUUIDFormat(snapshot->domain->uuid, uuid_string);

    xml = virDomainSnapshotDefFormat(uuid_string, &def, 0);

  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return xml;
}



static int
3871
esxDomainSnapshotNum(virDomainPtr domain, unsigned int flags)
3872
{
M
Matthias Bolte 已提交
3873
    int count;
3874 3875 3876
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;

3877 3878
    virCheckFlags(0, -1);

3879
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3880
        return -1;
3881 3882
    }

3883
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
3884
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
3885
        return -1;
3886 3887
    }

M
Matthias Bolte 已提交
3888
    count = esxVI_GetNumberOfSnapshotTrees(rootSnapshotTreeList);
3889 3890 3891

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

M
Matthias Bolte 已提交
3892
    return count;
3893 3894 3895 3896 3897 3898
}



static int
esxDomainSnapshotListNames(virDomainPtr domain, char **names, int nameslen,
3899
                           unsigned int flags)
3900
{
M
Matthias Bolte 已提交
3901
    int result;
3902 3903 3904
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;

3905 3906
    virCheckFlags(0, -1);

3907 3908 3909 3910 3911 3912 3913 3914 3915
    if (names == NULL || nameslen < 0) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
    }

    if (nameslen == 0) {
        return 0;
    }

3916
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3917
        return -1;
3918 3919
    }

3920
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
3921
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
3922
        return -1;
3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935
    }

    result = esxVI_GetSnapshotTreeNames(rootSnapshotTreeList, names, nameslen);

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



static virDomainSnapshotPtr
esxDomainSnapshotLookupByName(virDomainPtr domain, const char *name,
3936
                              unsigned int flags)
3937 3938 3939 3940 3941 3942 3943
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    virDomainSnapshotPtr snapshot = NULL;

3944 3945
    virCheckFlags(0, NULL);

3946
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3947
        return NULL;
3948 3949
    }

3950
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973
                                         &rootSnapshotTreeList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotTreeList, name, &snapshotTree,
                                    &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    snapshot = virGetDomainSnapshot(domain, name);

  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return snapshot;
}



static int
esxDomainHasCurrentSnapshot(virDomainPtr domain, unsigned int flags)
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *currentSnapshotTree = NULL;

3974
    virCheckFlags(0, -1);
3975

3976
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3977
        return -1;
3978 3979
    }

3980
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
3981 3982
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
3983
        return -1;
3984 3985 3986
    }

    if (currentSnapshotTree != NULL) {
M
Matthias Bolte 已提交
3987 3988
        esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);
        return 1;
3989 3990
    }

M
Matthias Bolte 已提交
3991
    return 0;
3992 3993 3994 3995 3996 3997 3998 3999 4000
}



static virDomainSnapshotPtr
esxDomainSnapshotCurrent(virDomainPtr domain, unsigned int flags)
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *currentSnapshotTree = NULL;
M
Matthias Bolte 已提交
4001
    virDomainSnapshotPtr snapshot = NULL;
4002

4003
    virCheckFlags(0, NULL);
4004

4005
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4006
        return NULL;
4007 4008
    }

4009
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4010 4011
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4012
        return NULL;
4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026
    }

    snapshot = virGetDomainSnapshot(domain, currentSnapshotTree->name);

    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return snapshot;
}



static int
esxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4027
    int result = -1;
4028 4029 4030 4031 4032 4033 4034
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

4035
    virCheckFlags(0, -1);
4036

4037
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4038
        return -1;
4039 4040
    }

4041
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4042 4043 4044 4045
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4046
        goto cleanup;
4047 4048
    }

4049
    if (esxVI_RevertToSnapshot_Task(priv->primary, snapshotTree->snapshot, NULL,
4050
                                    &task) < 0 ||
4051
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4052
                                    esxVI_Occurrence_RequiredItem,
4053
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
4054
        goto cleanup;
4055 4056 4057 4058 4059
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not revert to snapshot '%s'"), snapshot->name);
M
Matthias Bolte 已提交
4060
        goto cleanup;
4061 4062
    }

M
Matthias Bolte 已提交
4063 4064
    result = 0;

4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainSnapshotDelete(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4077
    int result = -1;
4078 4079 4080 4081 4082 4083 4084 4085
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    esxVI_Boolean removeChildren = esxVI_Boolean_False;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

4086 4087
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN, -1);

4088
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4089
        return -1;
4090 4091 4092 4093 4094 4095
    }

    if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN) {
        removeChildren = esxVI_Boolean_True;
    }

4096
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4097 4098 4099 4100
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4101
        goto cleanup;
4102 4103
    }

4104
    if (esxVI_RemoveSnapshot_Task(priv->primary, snapshotTree->snapshot,
4105
                                  removeChildren, &task) < 0 ||
4106
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4107
                                    esxVI_Occurrence_RequiredItem,
4108
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
4109
        goto cleanup;
4110 4111 4112 4113 4114
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not delete snapshot '%s'"), snapshot->name);
M
Matthias Bolte 已提交
4115
        goto cleanup;
4116 4117
    }

M
Matthias Bolte 已提交
4118 4119
    result = 0;

4120 4121 4122 4123 4124 4125 4126 4127 4128
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



4129 4130 4131 4132 4133 4134 4135 4136
static virDriver esxDriver = {
    VIR_DRV_ESX,
    "ESX",
    esxOpen,                         /* open */
    esxClose,                        /* close */
    esxSupportsFeature,              /* supports_feature */
    esxGetType,                      /* type */
    esxGetVersion,                   /* version */
4137
    NULL,                            /* libvirtVersion (impl. in libvirt.c) */
4138 4139 4140
    esxGetHostname,                  /* hostname */
    NULL,                            /* getMaxVcpus */
    esxNodeGetInfo,                  /* nodeGetInfo */
4141
    esxGetCapabilities,              /* getCapabilities */
4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167
    esxListDomains,                  /* listDomains */
    esxNumberOfDomains,              /* numOfDomains */
    NULL,                            /* domainCreateXML */
    esxDomainLookupByID,             /* domainLookupByID */
    esxDomainLookupByUUID,           /* domainLookupByUUID */
    esxDomainLookupByName,           /* domainLookupByName */
    esxDomainSuspend,                /* domainSuspend */
    esxDomainResume,                 /* domainResume */
    esxDomainShutdown,               /* domainShutdown */
    esxDomainReboot,                 /* domainReboot */
    esxDomainDestroy,                /* domainDestroy */
    esxDomainGetOSType,              /* domainGetOSType */
    esxDomainGetMaxMemory,           /* domainGetMaxMemory */
    esxDomainSetMaxMemory,           /* domainSetMaxMemory */
    esxDomainSetMemory,              /* domainSetMemory */
    esxDomainGetInfo,                /* domainGetInfo */
    NULL,                            /* domainSave */
    NULL,                            /* domainRestore */
    NULL,                            /* domainCoreDump */
    esxDomainSetVcpus,               /* domainSetVcpus */
    NULL,                            /* domainPinVcpu */
    NULL,                            /* domainGetVcpus */
    esxDomainGetMaxVcpus,            /* domainGetMaxVcpus */
    NULL,                            /* domainGetSecurityLabel */
    NULL,                            /* nodeGetSecurityModel */
    esxDomainDumpXML,                /* domainDumpXML */
4168
    esxDomainXMLFromNative,          /* domainXMLFromNative */
M
Matthias Bolte 已提交
4169
    esxDomainXMLToNative,            /* domainXMLToNative */
4170 4171 4172
    esxListDefinedDomains,           /* listDefinedDomains */
    esxNumberOfDefinedDomains,       /* numOfDefinedDomains */
    esxDomainCreate,                 /* domainCreate */
4173
    esxDomainCreateWithFlags,        /* domainCreateWithFlags */
M
Matthias Bolte 已提交
4174
    esxDomainDefineXML,              /* domainDefineXML */
4175
    esxDomainUndefine,               /* domainUndefine */
4176
    NULL,                            /* domainAttachDevice */
4177
    NULL,                            /* domainAttachDeviceFlags */
4178
    NULL,                            /* domainDetachDevice */
4179
    NULL,                            /* domainDetachDeviceFlags */
4180
    NULL,                            /* domainUpdateDeviceFlags */
4181 4182 4183 4184 4185 4186 4187 4188 4189 4190
    NULL,                            /* domainGetAutostart */
    NULL,                            /* domainSetAutostart */
    esxDomainGetSchedulerType,       /* domainGetSchedulerType */
    esxDomainGetSchedulerParameters, /* domainGetSchedulerParameters */
    esxDomainSetSchedulerParameters, /* domainSetSchedulerParameters */
    esxDomainMigratePrepare,         /* domainMigratePrepare */
    esxDomainMigratePerform,         /* domainMigratePerform */
    esxDomainMigrateFinish,          /* domainMigrateFinish */
    NULL,                            /* domainBlockStats */
    NULL,                            /* domainInterfaceStats */
4191
    NULL,                            /* domainMemoryStats */
4192 4193
    NULL,                            /* domainBlockPeek */
    NULL,                            /* domainMemoryPeek */
4194
    NULL,                            /* domainGetBlockInfo */
4195
    NULL,                            /* nodeGetCellsFreeMemory */
M
Matthias Bolte 已提交
4196
    esxNodeGetFreeMemory,            /* nodeGetFreeMemory */
4197 4198 4199 4200 4201 4202 4203
    NULL,                            /* domainEventRegister */
    NULL,                            /* domainEventDeregister */
    NULL,                            /* domainMigratePrepare2 */
    NULL,                            /* domainMigrateFinish2 */
    NULL,                            /* nodeDeviceDettach */
    NULL,                            /* nodeDeviceReAttach */
    NULL,                            /* nodeDeviceReset */
C
Chris Lalancette 已提交
4204
    NULL,                            /* domainMigratePrepareTunnel */
4205 4206 4207 4208
    esxIsEncrypted,                  /* isEncrypted */
    esxIsSecure,                     /* isSecure */
    esxDomainIsActive,               /* domainIsActive */
    esxDomainIsPersistent,           /* domainIsPersistent */
J
Jiri Denemark 已提交
4209
    NULL,                            /* cpuCompare */
4210
    NULL,                            /* cpuBaseline */
4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227
    NULL,                            /* domainGetJobInfo */
    NULL,                            /* domainAbortJob */
    NULL,                            /* domainMigrateSetMaxDowntime */
    NULL,                            /* domainEventRegisterAny */
    NULL,                            /* domainEventDeregisterAny */
    NULL,                            /* domainManagedSave */
    NULL,                            /* domainHasManagedSaveImage */
    NULL,                            /* domainManagedSaveRemove */
    esxDomainSnapshotCreateXML,      /* domainSnapshotCreateXML */
    esxDomainSnapshotDumpXML,        /* domainSnapshotDumpXML */
    esxDomainSnapshotNum,            /* domainSnapshotNum */
    esxDomainSnapshotListNames,      /* domainSnapshotListNames */
    esxDomainSnapshotLookupByName,   /* domainSnapshotLookupByName */
    esxDomainHasCurrentSnapshot,     /* domainHasCurrentSnapshot */
    esxDomainSnapshotCurrent,        /* domainSnapshotCurrent */
    esxDomainRevertToSnapshot,       /* domainRevertToSnapshot */
    esxDomainSnapshotDelete,         /* domainSnapshotDelete */
C
Chris Lalancette 已提交
4228
    NULL,                            /* qemuDomainMonitorCommand */
4229 4230 4231 4232 4233 4234 4235
};



int
esxRegister(void)
{
4236 4237 4238 4239 4240
    if (virRegisterDriver(&esxDriver) < 0 ||
        esxInterfaceRegister() < 0 ||
        esxNetworkRegister() < 0 ||
        esxStorageRegister() < 0 ||
        esxDeviceRegister() < 0 ||
M
Matthias Bolte 已提交
4241 4242
        esxSecretRegister() < 0 ||
        esxNWFilterRegister() < 0) {
4243 4244
        return -1;
    }
4245 4246 4247

    return 0;
}