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
 * 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 "internal.h"
#include "domain_conf.h"
29
#include "authhelper.h"
30 31 32 33 34
#include "util.h"
#include "memory.h"
#include "logging.h"
#include "uuid.h"
#include "esx_driver.h"
35 36 37 38 39
#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 已提交
40
#include "esx_nwfilter_driver.h"
41
#include "esx_private.h"
42 43 44 45 46 47 48 49 50
#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);

51 52 53 54
typedef struct _esxVMX_Data esxVMX_Data;

struct _esxVMX_Data {
    esxVI_Context *ctx;
55
    char *datastorePathWithoutFileName;
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
/*
 * Parse a file name from a .vmx file and convert it to datastore path format.
 * A .vmx file can contain file names in various formats:
 *
 * - A single name referencing a file in the same directory as the .vmx file:
 *
 *     test1.vmdk
 *
 * - An absolute file name referencing a file in a datastore that is mounted at
 *   /vmfs/volumes/<datastore>:
 *
 *     /vmfs/volumes/b24b7a78-9d82b4f5/test1/test1.vmdk
 *     /vmfs/volumes/datastore1/test1/test1.vmdk
 *
 *   The actual mount directory is /vmfs/volumes/b24b7a78-9d82b4f5, the second
 *   form is a symlink to it using the datastore name. This is the typical
 *   setup on an ESX(i) server.
 *
 * - With GSX installed on Windows there are also Windows style file names
 *   including UNC file names:
 *
 *     C:\Virtual Machines\test1\test1.vmdk
 *     \\nas1\storage1\test1\test1.vmdk
 *
 * The datastore path format typically looks like this:
 *
 *  [datastore1] test1/test1.vmdk
 *
 * Firstly this functions checks if the given file name contains a separator.
 * If it doesn't then the referenced file is in the same directory as the .vmx
 * file. The datastore name and directory of the .vmx file are passed to this
 * function via the opaque paramater by the caller of esxVMX_ParseConfig.
 *
 * Otherwise query for all known datastores and their mount directories. Then
 * try to find a datastore with a mount directory that is a prefix to the given
 * file name. This mechanism covers the Windows style file names too.
 *
 * The symlinks using the datastore name (/vmfs/volumes/datastore1) are an
 * exception and need special handling. Parse the datastore name and use it
 * to lookup the datastore by name to verify that it exists.
 */
101
static char *
102
esxParseVMXFileName(const char *fileName, void *opaque)
103
{
104 105
    char *datastorePath = NULL;
    esxVMX_Data *data = opaque;
106
    esxVI_String *propertyNameList = NULL;
107
    esxVI_ObjectContent *datastoreList = NULL;
108
    esxVI_ObjectContent *datastore = NULL;
109 110 111 112 113 114 115 116 117 118
    esxVI_DatastoreHostMount *hostMount = NULL;
    char *datastoreName;
    char *tmp;
    char *saveptr;
    char *strippedFileName = NULL;
    char *copyOfFileName = NULL;
    char *directoryAndFileName;

    if (strchr(fileName, '/') == NULL && strchr(fileName, '\\') == NULL) {
        /* Plain file name, use same directory as for the .vmx file */
119 120
        if (virAsprintf(&datastorePath, "%s/%s",
                        data->datastorePathWithoutFileName, fileName) < 0) {
121 122 123 124 125 126 127 128 129 130
            virReportOOMError();
            goto cleanup;
        }
    } else {
        if (esxVI_String_AppendValueToList(&propertyNameList,
                                           "summary.name") < 0 ||
            esxVI_LookupDatastoreList(data->ctx, propertyNameList,
                                      &datastoreList) < 0) {
            return NULL;
        }
131

132 133 134 135 136
        /* Search for datastore by mount path */
        for (datastore = datastoreList; datastore != NULL;
             datastore = datastore->_next) {
            esxVI_DatastoreHostMount_Free(&hostMount);
            datastoreName = NULL;
137

138 139 140 141 142 143
            if (esxVI_LookupDatastoreHostMount(data->ctx, datastore->obj,
                                               &hostMount) < 0 ||
                esxVI_GetStringValue(datastore, "summary.name", &datastoreName,
                                     esxVI_Occurrence_RequiredItem) < 0) {
                goto cleanup;
            }
144

145
            tmp = (char *)STRSKIP(fileName, hostMount->mountInfo->path);
146

147 148 149
            if (tmp == NULL) {
                continue;
            }
150

151 152 153 154
            /* Found a match. Strip leading separators */
            while (*tmp == '/' || *tmp == '\\') {
                ++tmp;
            }
155

156 157 158
            if (esxVI_String_DeepCopyValue(&strippedFileName, tmp) < 0) {
                goto cleanup;
            }
159

160
            tmp = strippedFileName;
161

162 163 164 165 166
            /* Convert \ to / */
            while (*tmp != '\0') {
                if (*tmp == '\\') {
                    *tmp = '/';
                }
167

168 169
                ++tmp;
            }
170

171 172 173 174 175
            if (virAsprintf(&datastorePath, "[%s] %s", datastoreName,
                            strippedFileName) < 0) {
                virReportOOMError();
                goto cleanup;
            }
176

177 178
            break;
        }
179

180 181 182 183 184
        /* Fallback to direct datastore name match */
        if (datastorePath == NULL && STRPREFIX(fileName, "/vmfs/volumes/")) {
            if (esxVI_String_DeepCopyValue(&copyOfFileName, fileName) < 0) {
                goto cleanup;
            }
185

186 187 188 189 190 191 192 193 194
            /* Expected format: '/vmfs/volumes/<datastore>/<path>' */
            if ((tmp = STRSKIP(copyOfFileName, "/vmfs/volumes/")) == NULL ||
                (datastoreName = strtok_r(tmp, "/", &saveptr)) == NULL ||
                (directoryAndFileName = strtok_r(NULL, "", &saveptr)) == NULL) {
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                          _("File name '%s' doesn't have expected format "
                            "'/vmfs/volumes/<datastore>/<path>'"), fileName);
                goto cleanup;
            }
195

196
            esxVI_ObjectContent_Free(&datastoreList);
197

198 199 200 201 202
            if (esxVI_LookupDatastoreByName(data->ctx, datastoreName,
                                            NULL, &datastoreList,
                                            esxVI_Occurrence_OptionalItem) < 0) {
                goto cleanup;
            }
203

204 205 206 207 208 209
            if (datastoreList == NULL) {
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                          _("File name '%s' refers to non-existing datastore '%s'"),
                          fileName, datastoreName);
                goto cleanup;
            }
210

211 212 213 214 215
            if (virAsprintf(&datastorePath, "[%s] %s", datastoreName,
                            directoryAndFileName) < 0) {
                virReportOOMError();
                goto cleanup;
            }
216 217
        }

218 219 220 221
        if (datastorePath == NULL) {
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                      _("Could not find datastore for '%s'"), fileName);
            goto cleanup;
222
        }
223
    }
224

225 226 227 228 229 230
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&datastoreList);
    esxVI_DatastoreHostMount_Free(&hostMount);
    VIR_FREE(strippedFileName);
    VIR_FREE(copyOfFileName);
231

232
    return datastorePath;
233 234 235 236
}



237 238 239 240 241 242 243 244 245 246 247 248 249
/*
 * This function does the inverse of esxParseVMXFileName. It takes an file name
 * in datastore path format and converts it to a file name that can be used in
 * a .vmx file.
 *
 * The datastore path format and the formats found in a .vmx file are described
 * in the documentation of esxParseVMXFileName.
 *
 * Firstly parse the datastore path. Then use the datastore name to lookup the
 * datastore and it's mount path. Finally concatenate the mount path, directory
 * and file name to an absolute path and return it. Detect the seperator type
 * based on the mount path.
 */
250
static char *
251
esxFormatVMXFileName(const char *datastorePath, void *opaque)
252 253
{
    bool success = false;
254
    esxVMX_Data *data = opaque;
255
    char *datastoreName = NULL;
256
    char *directoryAndFileName = NULL;
257 258 259 260 261
    esxVI_ObjectContent *datastore = NULL;
    esxVI_DatastoreHostMount *hostMount = NULL;
    char separator = '/';
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    char *tmp;
262
    size_t length;
263 264
    char *absolutePath = NULL;

265
    /* Parse datastore path and lookup datastore */
266 267
    if (esxUtil_ParseDatastorePath(datastorePath, &datastoreName, NULL,
                                   &directoryAndFileName) < 0) {
268 269
        goto cleanup;
    }
270

271
    if (esxVI_LookupDatastoreByName(data->ctx, datastoreName, NULL, &datastore,
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
                                    esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_LookupDatastoreHostMount(data->ctx, datastore->obj,
                                       &hostMount) < 0) {
        goto cleanup;
    }

    /* Detect separator type */
    if (strchr(hostMount->mountInfo->path, '\\') != NULL) {
        separator = '\\';
    }

    /* Strip trailing separators */
    length = strlen(hostMount->mountInfo->path);

    while (length > 0 && hostMount->mountInfo->path[length - 1] == separator) {
        --length;
    }

290
    /* Format as <mount>[/<directory>]/<file>, convert / to \ when necessary */
291 292
    virBufferAdd(&buffer, hostMount->mountInfo->path, length);

293 294
    if (separator != '/') {
        tmp = directoryAndFileName;
295

296 297 298
        while (*tmp != '\0') {
            if (*tmp == '/') {
                *tmp = separator;
299 300
            }

301 302
            ++tmp;
        }
303 304 305
    }

    virBufferAddChar(&buffer, separator);
306
    virBufferAdd(&buffer, directoryAndFileName, -1);
307 308 309

    if (virBufferError(&buffer)) {
        virReportOOMError();
310 311 312
        goto cleanup;
    }

313 314
    absolutePath = virBufferContentAndReset(&buffer);

315 316 317 318 319 320
    /* FIXME: Check if referenced path/file really exists */

    success = true;

  cleanup:
    if (! success) {
321
        virBufferFreeAndReset(&buffer);
322 323 324 325
        VIR_FREE(absolutePath);
    }

    VIR_FREE(datastoreName);
326
    VIR_FREE(directoryAndFileName);
327 328
    esxVI_ObjectContent_Free(&datastore);
    esxVI_DatastoreHostMount_Free(&hostMount);
329 330 331 332 333 334 335 336 337 338 339 340

    return absolutePath;
}



static int
esxAutodetectSCSIControllerModel(virDomainDiskDefPtr def, int *model,
                                 void *opaque)
{
    int result = -1;
    esxVMX_Data *data = opaque;
341
    esxVI_FileInfo *fileInfo = NULL;
342 343 344 345 346 347 348 349 350 351 352 353 354 355
    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;
    }

356 357
    if (esxVI_LookupFileInfoByDatastorePath(data->ctx, def->src, &fileInfo,
                                            esxVI_Occurrence_RequiredItem) < 0) {
358 359 360
        goto cleanup;
    }

361
    vmDiskFileInfo = esxVI_VmDiskFileInfo_DynamicCast(fileInfo);
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

    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:
391
    esxVI_FileInfo_Free(&fileInfo);
392 393 394 395

    return result;
}

396 397


398
static esxVI_Boolean
399
esxSupportsLongMode(esxPrivate *priv)
400 401 402 403 404 405
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_HostCpuIdInfo *hostCpuIdInfoList = NULL;
    esxVI_HostCpuIdInfo *hostCpuIdInfo = NULL;
406
    esxVI_ParsedHostCpuIdInfo parsedHostCpuIdInfo;
407 408 409 410 411 412
    char edxLongModeBit = '?';

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

413
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
414
        return esxVI_Boolean_Undefined;
415 416
    }

417
    if (esxVI_String_AppendValueToList(&propertyNameList,
418
                                       "hardware.cpuFeature") < 0 ||
419 420
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
421
        goto cleanup;
422 423 424
    }

    if (hostSystem == NULL) {
425 426
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
427
        goto cleanup;
428 429 430 431 432 433
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuFeature")) {
            if (esxVI_HostCpuIdInfo_CastListFromAnyType
434
                  (dynamicProperty->val, &hostCpuIdInfoList) < 0) {
M
Matthias Bolte 已提交
435
                goto cleanup;
436 437 438 439 440
            }

            for (hostCpuIdInfo = hostCpuIdInfoList; hostCpuIdInfo != NULL;
                 hostCpuIdInfo = hostCpuIdInfo->_next) {
                if (hostCpuIdInfo->level->value == -2147483647) { /* 0x80000001 */
441 442
                    if (esxVI_ParseHostCpuIdInfo(&parsedHostCpuIdInfo,
                                                 hostCpuIdInfo) < 0) {
M
Matthias Bolte 已提交
443
                        goto cleanup;
444 445
                    }

446
                    edxLongModeBit = parsedHostCpuIdInfo.edx[29];
447 448 449 450 451 452

                    if (edxLongModeBit == '1') {
                        priv->supportsLongMode = esxVI_Boolean_True;
                    } else if (edxLongModeBit == '0') {
                        priv->supportsLongMode = esxVI_Boolean_False;
                    } else {
453
                        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
454 455 456 457
                                  _("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 已提交
458
                        goto cleanup;
459 460 461 462 463 464 465 466 467 468 469 470 471
                    }

                    break;
                }
            }

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

  cleanup:
M
Matthias Bolte 已提交
472 473 474 475
    /*
     * 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.
     */
476 477 478 479 480 481 482 483 484
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_HostCpuIdInfo_Free(&hostCpuIdInfoList);

    return priv->supportsLongMode;
}



485 486 487 488 489 490 491 492
static int
esxLookupHostSystemBiosUuid(esxPrivate *priv, unsigned char *uuid)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

493
    if (esxVI_EnsureSession(priv->primary) < 0) {
494 495 496 497 498
        return -1;
    }

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "hardware.systemInfo.uuid") < 0 ||
499 500
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
        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;
}



547
static virCapsPtr
548
esxCapsInit(esxPrivate *priv)
549
{
550
    esxVI_Boolean supportsLongMode = esxSupportsLongMode(priv);
551 552 553
    virCapsPtr caps = NULL;
    virCapsGuestPtr guest = NULL;

554 555 556 557 558 559 560 561 562
    if (supportsLongMode == esxVI_Boolean_Undefined) {
        return NULL;
    }

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

    if (caps == NULL) {
565
        virReportOOMError();
566 567 568
        return NULL;
    }

569
    virCapabilitiesSetMacPrefix(caps, (unsigned char[]){ 0x00, 0x0c, 0x29 });
570
    virCapabilitiesAddHostMigrateTransport(caps, "vpxmigr");
571

572 573
    caps->hasWideScsiBus = true;

574 575 576 577
    if (esxLookupHostSystemBiosUuid(priv, caps->host.host_uuid) < 0) {
        goto failure;
    }

578 579 580
    /* i686 */
    guest = virCapabilitiesAddGuest(caps, "hvm", "i686", 32, NULL, NULL, 0,
                                    NULL);
581 582 583 584 585 586 587 588 589 590 591 592 593 594

    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;
    }

595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
    /* 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;
        }
    }

614 615 616 617 618 619 620 621 622 623
    return caps;

  failure:
    virCapabilitiesFree(caps);

    return NULL;
}



624 625 626 627
static int
esxConnectToHost(esxPrivate *priv, virConnectAuthPtr auth,
                 const char *hostname, int port,
                 const char *predefinedUsername,
M
Matthias Bolte 已提交
628
                 esxUtil_ParsedUri *parsedUri,
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
                 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,
681 682
                              parsedUri) < 0 ||
        esxVI_Context_LookupObjectsByPath(priv->host, parsedUri) < 0) {
683 684 685 686 687
        goto cleanup;
    }

    if (expectedProductVersion == esxVI_ProductVersion_ESX) {
        if (priv->host->productVersion != esxVI_ProductVersion_ESX35 &&
M
Matthias Bolte 已提交
688 689 690
            priv->host->productVersion != esxVI_ProductVersion_ESX40 &&
            priv->host->productVersion != esxVI_ProductVersion_ESX41 &&
            priv->host->productVersion != esxVI_ProductVersion_ESX4x) {
691
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
M
Matthias Bolte 已提交
692
                      _("%s is neither an ESX 3.5 host nor an ESX 4.x host"),
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
                      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 ||
708 709
        esxVI_LookupHostSystemProperties(priv->host, propertyNameList,
                                         &hostSystem) < 0 ||
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
        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,
751
                    const char *hostSystemIpAddress,
M
Matthias Bolte 已提交
752
                    esxUtil_ParsedUri *parsedUri)
753 754 755 756 757 758 759
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
    char *password = NULL;
    char *url = NULL;

760 761 762 763 764 765 766 767
    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;
    }

768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
    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 已提交
803
                              password, parsedUri) < 0) {
804 805 806 807
        goto cleanup;
    }

    if (priv->vCenter->productVersion != esxVI_ProductVersion_VPX25 &&
M
Matthias Bolte 已提交
808 809 810
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX40 &&
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX41 &&
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX4x) {
811 812
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("%s is neither a vCenter 2.5 server nor a vCenter "
M
Matthias Bolte 已提交
813
                    "4.x server"), hostname);
814 815 816
        goto cleanup;
    }

817 818 819 820 821 822 823 824 825 826 827
    if (hostSystemIpAddress != NULL) {
        if (esxVI_Context_LookupObjectsByHostSystemIp(priv->vCenter,
                                                      hostSystemIpAddress) < 0) {
            goto cleanup;
        }
    } else {
        if (esxVI_Context_LookupObjectsByPath(priv->vCenter, parsedUri) < 0) {
            goto cleanup;
        }
    }

828 829 830 831 832 833 834 835 836 837 838 839
    result = 0;

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

    return result;
}



840
/*
841 842
 * URI format: {vpx|esx|gsx}://[<username>@]<hostname>[:<port>]/[<path>][?<query parameter> ...]
 *             <path> = <datacenter>/<computeresource>[/<hostsystem>]
843
 *
844 845
 * If no port is specified the default port is set dependent on the scheme and
 * transport parameter:
846 847
 * - vpx+http  80
 * - vpx+https 443
848
 * - esx+http  80
849
 * - esx+https 443
850 851 852
 * - gsx+http  8222
 * - gsx+https 8333
 *
853 854 855 856 857
 * 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.
 *
858 859
 * Optional query parameters:
 * - transport={http|https}
860
 * - vcenter={<vcenter>|*}             only useful for an esx:// connection
861 862
 * - no_verify={0|1}
 * - auto_answer={0|1}
M
Matthias Bolte 已提交
863
 * - proxy=[{http|socks|socks4|socks4a|socks5}://]<hostname>[:<port>]
864
 *
865 866 867
 * If no transport parameter is specified https is used.
 *
 * The vcenter parameter is only necessary for migration, because the vCenter
868
 * server is in charge to initiate a migration between two ESX hosts. The
869
 * vcenter parameter can be set to an explicitly hostname or to *. If set to *,
870 871
 * 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.
872 873
 *
 * If the no_verify parameter is set to 1, this disables libcurl client checks
874
 * of the server's certificate. The default value it 0.
875 876 877 878
 *
 * 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 已提交
879 880 881 882
 *
 * 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.
883 884 885 886
 */
static virDrvOpenStatus
esxOpen(virConnectPtr conn, virConnectAuthPtr auth, int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
887
    virDrvOpenStatus result = VIR_DRV_OPEN_ERROR;
888
    esxPrivate *priv = NULL;
M
Matthias Bolte 已提交
889
    esxUtil_ParsedUri *parsedUri = NULL;
890
    char *potentialVCenterIpAddress = NULL;
M
Matthias Bolte 已提交
891
    char vCenterIpAddress[NI_MAXHOST] = "";
892

893
    /* Decline if the URI is NULL or the scheme is not one of {vpx|esx|gsx} */
894
    if (conn->uri == NULL || conn->uri->scheme == NULL ||
895 896
        (STRCASENEQ(conn->uri->scheme, "vpx") &&
         STRCASENEQ(conn->uri->scheme, "esx") &&
897
         STRCASENEQ(conn->uri->scheme, "gsx"))) {
898 899 900
        return VIR_DRV_OPEN_DECLINED;
    }

M
Matthias Bolte 已提交
901 902 903
    /* Decline URIs without server part, or missing auth */
    if (conn->uri->server == NULL || auth == NULL || auth->cb == NULL) {
        return VIR_DRV_OPEN_DECLINED;
904 905 906 907
    }

    /* Allocate per-connection private data */
    if (VIR_ALLOC(priv) < 0) {
908
        virReportOOMError();
M
Matthias Bolte 已提交
909
        goto cleanup;
910 911
    }

M
Matthias Bolte 已提交
912
    if (esxUtil_ParseUri(&parsedUri, conn->uri) < 0) {
913 914 915
        goto cleanup;
    }

M
Matthias Bolte 已提交
916 917
    priv->transport = parsedUri->transport;
    parsedUri->transport = NULL;
918

M
Matthias Bolte 已提交
919 920
    priv->maxVcpus = -1;
    priv->supportsVMotion = esxVI_Boolean_Undefined;
921
    priv->supportsLongMode = esxVI_Boolean_Undefined;
M
Matthias Bolte 已提交
922 923
    priv->autoAnswer = parsedUri->autoAnswer ? esxVI_Boolean_True
                                             : esxVI_Boolean_False;
924 925
    priv->usedCpuTimeCounterId = -1;

M
Matthias Bolte 已提交
926 927 928 929 930 931 932
    /*
     * 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) {
933 934
        if (STRCASEEQ(conn->uri->scheme, "vpx") ||
            STRCASEEQ(conn->uri->scheme, "esx")) {
M
Matthias Bolte 已提交
935 936 937 938 939 940 941 942 943 944 945
            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;
            }
946
        }
M
Matthias Bolte 已提交
947
    }
948

949 950 951 952
    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 已提交
953
                             conn->uri->user, parsedUri,
954 955 956 957
                             STRCASEEQ(conn->uri->scheme, "esx")
                               ? esxVI_ProductVersion_ESX
                               : esxVI_ProductVersion_GSX,
                             &potentialVCenterIpAddress) < 0) {
M
Matthias Bolte 已提交
958
            goto cleanup;
959
        }
960

961
        /* Connect to vCenter */
M
Matthias Bolte 已提交
962 963
        if (parsedUri->vCenter != NULL) {
            if (STREQ(parsedUri->vCenter, "*")) {
964 965 966
                if (potentialVCenterIpAddress == NULL) {
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                              _("This host is not managed by a vCenter"));
M
Matthias Bolte 已提交
967
                    goto cleanup;
968 969
                }

970 971 972 973 974 975 976 977
                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 已提交
978
                if (esxUtil_ResolveHostname(parsedUri->vCenter,
979 980 981
                                            vCenterIpAddress, NI_MAXHOST) < 0) {
                    goto cleanup;
                }
982

983 984
                if (potentialVCenterIpAddress != NULL &&
                    STRNEQ(vCenterIpAddress, potentialVCenterIpAddress)) {
985
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
986 987 988
                              _("This host is managed by a vCenter with IP "
                                "address %s, but a mismachting vCenter '%s' "
                                "(%s) has been specified"),
M
Matthias Bolte 已提交
989
                              potentialVCenterIpAddress, parsedUri->vCenter,
990
                              vCenterIpAddress);
M
Matthias Bolte 已提交
991
                    goto cleanup;
992 993
                }
            }
994

995
            if (esxConnectToVCenter(priv, auth, vCenterIpAddress,
996 997
                                    conn->uri->port, NULL,
                                    priv->host->ipAddress, parsedUri) < 0) {
998 999
                goto cleanup;
            }
1000 1001
        }

1002 1003 1004 1005
        priv->primary = priv->host;
    } else { /* VPX */
        /* Connect to vCenter */
        if (esxConnectToVCenter(priv, auth, conn->uri->server, conn->uri->port,
1006
                                conn->uri->user, NULL, parsedUri) < 0) {
M
Matthias Bolte 已提交
1007
            goto cleanup;
1008 1009
        }

1010
        priv->primary = priv->vCenter;
1011 1012 1013
    }

    conn->privateData = priv;
1014

M
Matthias Bolte 已提交
1015
    /* Setup capabilities */
1016
    priv->caps = esxCapsInit(priv);
1017

M
Matthias Bolte 已提交
1018
    if (priv->caps == NULL) {
M
Matthias Bolte 已提交
1019
        goto cleanup;
1020 1021
    }

M
Matthias Bolte 已提交
1022
    result = VIR_DRV_OPEN_SUCCESS;
1023

M
Matthias Bolte 已提交
1024 1025
  cleanup:
    if (result == VIR_DRV_OPEN_ERROR && priv != NULL) {
1026
        esxVI_Context_Free(&priv->host);
M
Matthias Bolte 已提交
1027
        esxVI_Context_Free(&priv->vCenter);
1028

1029 1030
        virCapabilitiesFree(priv->caps);

M
Matthias Bolte 已提交
1031
        VIR_FREE(priv->transport);
1032 1033 1034
        VIR_FREE(priv);
    }

M
Matthias Bolte 已提交
1035
    esxUtil_FreeParsedUri(&parsedUri);
1036
    VIR_FREE(potentialVCenterIpAddress);
1037

M
Matthias Bolte 已提交
1038
    return result;
1039 1040 1041 1042 1043 1044 1045
}



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

1049 1050 1051 1052 1053
    if (priv->host != NULL) {
        if (esxVI_EnsureSession(priv->host) < 0 ||
            esxVI_Logout(priv->host) < 0) {
            result = -1;
        }
1054

1055 1056
        esxVI_Context_Free(&priv->host);
    }
1057

M
Matthias Bolte 已提交
1058
    if (priv->vCenter != NULL) {
E
Eric Blake 已提交
1059 1060 1061 1062
        if (esxVI_EnsureSession(priv->vCenter) < 0 ||
            esxVI_Logout(priv->vCenter) < 0) {
            result = -1;
        }
1063

M
Matthias Bolte 已提交
1064
        esxVI_Context_Free(&priv->vCenter);
1065 1066
    }

1067 1068
    virCapabilitiesFree(priv->caps);

1069 1070 1071 1072 1073
    VIR_FREE(priv->transport);
    VIR_FREE(priv);

    conn->privateData = NULL;

E
Eric Blake 已提交
1074
    return result;
1075 1076 1077 1078 1079
}



static esxVI_Boolean
1080
esxSupportsVMotion(esxPrivate *priv)
1081 1082 1083 1084
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;

M
Matthias Bolte 已提交
1085 1086
    if (priv->supportsVMotion != esxVI_Boolean_Undefined) {
        return priv->supportsVMotion;
1087 1088
    }

1089
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1090
        return esxVI_Boolean_Undefined;
1091 1092
    }

1093
    if (esxVI_String_AppendValueToList(&propertyNameList,
1094
                                       "capability.vmotionSupported") < 0 ||
1095 1096
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1097
        goto cleanup;
1098 1099 1100
    }

    if (hostSystem == NULL) {
1101 1102
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
1103
        goto cleanup;
1104 1105
    }

1106 1107 1108 1109
    if (esxVI_GetBoolean(hostSystem, "capability.vmotionSupported",
                         &priv->supportsVMotion,
                         esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
1110 1111 1112
    }

  cleanup:
M
Matthias Bolte 已提交
1113 1114 1115 1116
    /*
     * 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.
     */
1117 1118 1119
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
1120
    return priv->supportsVMotion;
1121 1122 1123 1124 1125 1126 1127
}



static int
esxSupportsFeature(virConnectPtr conn, int feature)
{
M
Matthias Bolte 已提交
1128
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1129
    esxVI_Boolean supportsVMotion = esxVI_Boolean_Undefined;
1130 1131 1132

    switch (feature) {
      case VIR_DRV_FEATURE_MIGRATION_V1:
1133
        supportsVMotion = esxSupportsVMotion(priv);
1134

M
Matthias Bolte 已提交
1135
        if (supportsVMotion == esxVI_Boolean_Undefined) {
1136 1137 1138
            return -1;
        }

M
Matthias Bolte 已提交
1139 1140 1141
        /* Migration is only possible via a vCenter and if VMotion is enabled */
        return priv->vCenter != NULL &&
               supportsVMotion == esxVI_Boolean_True ? 1 : 0;
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160

      default:
        return 0;
    }
}



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



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

1163
    if (virParseVersionString(priv->primary->service->about->version,
1164 1165
                              version) < 0) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1166
                  _("Could not parse version number from '%s'"),
1167
                  priv->primary->service->about->version);
1168

1169
        return -1;
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
    }

    return 0;
}



static char *
esxGetHostname(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1180
    esxPrivate *priv = conn->privateData;
1181 1182 1183 1184 1185 1186 1187
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    const char *hostName = NULL;
    const char *domainName = NULL;
    char *complete = NULL;

1188
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1189
        return NULL;
1190 1191 1192
    }

    if (esxVI_String_AppendValueListToList
1193
          (&propertyNameList,
1194 1195
           "config.network.dnsConfig.hostName\0"
           "config.network.dnsConfig.domainName\0") < 0 ||
1196 1197
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1198
        goto cleanup;
1199 1200 1201
    }

    if (hostSystem == NULL) {
1202 1203
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
1204
        goto cleanup;
1205 1206 1207 1208 1209 1210
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name,
                  "config.network.dnsConfig.hostName")) {
1211
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1212
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1213
                goto cleanup;
1214 1215 1216 1217 1218
            }

            hostName = dynamicProperty->val->string;
        } else if (STREQ(dynamicProperty->name,
                         "config.network.dnsConfig.domainName")) {
1219
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1220
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1221
                goto cleanup;
1222 1223 1224 1225 1226 1227 1228 1229
            }

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

M
Matthias Bolte 已提交
1230
    if (hostName == NULL || strlen(hostName) < 1) {
1231 1232
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Missing or empty 'hostName' property"));
M
Matthias Bolte 已提交
1233
        goto cleanup;
1234 1235
    }

M
Matthias Bolte 已提交
1236
    if (domainName == NULL || strlen(domainName) < 1) {
1237
        complete = strdup(hostName);
1238

1239
        if (complete == NULL) {
1240
            virReportOOMError();
M
Matthias Bolte 已提交
1241
            goto cleanup;
1242 1243 1244
        }
    } else {
        if (virAsprintf(&complete, "%s.%s", hostName, domainName) < 0) {
1245
            virReportOOMError();
M
Matthias Bolte 已提交
1246
            goto cleanup;
1247
        }
1248 1249 1250
    }

  cleanup:
M
Matthias Bolte 已提交
1251 1252 1253 1254 1255
    /*
     * 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
     */
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return complete;
}



static int
esxNodeGetInfo(virConnectPtr conn, virNodeInfoPtr nodeinfo)
{
M
Matthias Bolte 已提交
1267
    int result = -1;
M
Matthias Bolte 已提交
1268
    esxPrivate *priv = conn->privateData;
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
    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 已提交
1280
    memset(nodeinfo, 0, sizeof (*nodeinfo));
1281

1282
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1283
        return -1;
1284 1285
    }

1286
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1287 1288 1289 1290 1291 1292 1293
                                           "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 ||
1294 1295
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1296
        goto cleanup;
1297 1298 1299
    }

    if (hostSystem == NULL) {
1300 1301
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
1302
        goto cleanup;
1303 1304 1305 1306 1307
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuInfo.hz")) {
1308
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1309
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1310
                goto cleanup;
1311 1312 1313 1314 1315
            }

            cpuInfo_hz = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuCores")) {
1316
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1317
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1318
                goto cleanup;
1319 1320 1321 1322 1323
            }

            cpuInfo_numCpuCores = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuPackages")) {
1324
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1325
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1326
                goto cleanup;
1327 1328 1329 1330 1331
            }

            cpuInfo_numCpuPackages = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuThreads")) {
1332
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1333
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1334
                goto cleanup;
1335 1336 1337 1338
            }

            cpuInfo_numCpuThreads = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name, "hardware.memorySize")) {
1339
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1340
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1341
                goto cleanup;
1342 1343 1344 1345 1346
            }

            memorySize = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.numaInfo.numNodes")) {
1347
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1348
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1349
                goto cleanup;
1350 1351 1352 1353 1354
            }

            numaInfo_numNodes = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "summary.hardware.cpuModel")) {
1355
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1356
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1357
                goto cleanup;
1358 1359 1360 1361 1362 1363
            }

            ptr = dynamicProperty->val->string;

            /* Strip the string to fit more relevant information in 32 chars */
            while (*ptr != '\0') {
M
Matthias Bolte 已提交
1364 1365
                if (STRPREFIX(ptr, "  ")) {
                    memmove(ptr, ptr + 1, strlen(ptr + 1) + 1);
1366
                    continue;
1367
                } else if (STRPREFIX(ptr, "(R)") || STRPREFIX(ptr, "(C)")) {
M
Matthias Bolte 已提交
1368
                    memmove(ptr, ptr + 3, strlen(ptr + 3) + 1);
1369
                    continue;
1370 1371 1372
                } else if (STRPREFIX(ptr, "(TM)")) {
                    memmove(ptr, ptr + 4, strlen(ptr + 4) + 1);
                    continue;
1373 1374 1375 1376 1377
                }

                ++ptr;
            }

C
Chris Lalancette 已提交
1378 1379 1380
            if (virStrncpy(nodeinfo->model, dynamicProperty->val->string,
                           sizeof(nodeinfo->model) - 1,
                           sizeof(nodeinfo->model)) == NULL) {
1381
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1382
                          _("CPU Model %s too long for destination"),
C
Chris Lalancette 已提交
1383
                          dynamicProperty->val->string);
M
Matthias Bolte 已提交
1384
                goto cleanup;
C
Chris Lalancette 已提交
1385
            }
1386 1387 1388 1389 1390 1391 1392
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    nodeinfo->memory = memorySize / 1024; /* Scale from bytes to kilobytes */
    nodeinfo->cpus = cpuInfo_numCpuCores;
1393
    nodeinfo->mhz = cpuInfo_hz / (1000 * 1000); /* Scale from hz to mhz */
1394 1395 1396 1397 1398 1399 1400 1401 1402
    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 已提交
1403 1404
    result = 0;

1405 1406 1407 1408 1409 1410 1411 1412 1413
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



1414 1415 1416
static char *
esxGetCapabilities(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1417
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1418
    char *xml = virCapabilitiesFormatXML(priv->caps);
1419 1420

    if (xml == NULL) {
1421
        virReportOOMError();
1422 1423 1424 1425 1426 1427 1428 1429
        return NULL;
    }

    return xml;
}



1430 1431 1432
static int
esxListDomains(virConnectPtr conn, int *ids, int maxids)
{
M
Matthias Bolte 已提交
1433
    bool success = false;
M
Matthias Bolte 已提交
1434
    esxPrivate *priv = conn->privateData;
1435 1436 1437 1438 1439 1440 1441
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;

    if (ids == NULL || maxids < 0) {
1442 1443
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
1444 1445 1446 1447 1448 1449
    }

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

1450
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1451
        return -1;
1452 1453
    }

1454
    if (esxVI_String_AppendValueToList(&propertyNameList,
1455
                                       "runtime.powerState") < 0 ||
1456 1457
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1458
        goto cleanup;
1459 1460 1461 1462
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
1463
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1464
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1465
            goto cleanup;
1466 1467 1468 1469 1470 1471 1472 1473 1474
        }

        if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

        if (esxUtil_ParseVirtualMachineIDString(virtualMachine->obj->value,
                                                &ids[count]) < 0 ||
            ids[count] <= 0) {
1475
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1476
                      _("Failed to parse positive integer from '%s'"),
1477
                      virtualMachine->obj->value);
M
Matthias Bolte 已提交
1478
            goto cleanup;
1479 1480 1481 1482 1483 1484 1485 1486 1487
        }

        count++;

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

M
Matthias Bolte 已提交
1488 1489
    success = true;

1490 1491 1492 1493
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
1494
    return success ? count : -1;
1495 1496 1497 1498 1499 1500 1501
}



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

1504
    if (esxVI_EnsureSession(priv->primary) < 0) {
1505 1506 1507
        return -1;
    }

1508
    return esxVI_LookupNumberOfDomainsByPowerState
1509
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn,
1510 1511 1512 1513 1514 1515 1516 1517
              esxVI_Boolean_False);
}



static virDomainPtr
esxDomainLookupByID(virConnectPtr conn, int id)
{
M
Matthias Bolte 已提交
1518
    esxPrivate *priv = conn->privateData;
1519 1520 1521 1522
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
M
Matthias Bolte 已提交
1523 1524 1525
    int id_candidate = -1;
    char *name_candidate = NULL;
    unsigned char uuid_candidate[VIR_UUID_BUFLEN];
1526 1527
    virDomainPtr domain = NULL;

1528
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1529
        return NULL;
1530 1531
    }

1532
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1533
                                           "configStatus\0"
1534 1535
                                           "name\0"
                                           "runtime.powerState\0"
1536
                                           "config.uuid\0") < 0 ||
1537 1538
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1539
        goto cleanup;
1540 1541 1542 1543
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
1544
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1545
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1546
            goto cleanup;
1547 1548 1549 1550 1551 1552 1553
        }

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

M
Matthias Bolte 已提交
1554
        VIR_FREE(name_candidate);
1555

1556
        if (esxVI_GetVirtualMachineIdentity(virtualMachine,
M
Matthias Bolte 已提交
1557 1558
                                            &id_candidate, &name_candidate,
                                            uuid_candidate) < 0) {
M
Matthias Bolte 已提交
1559
            goto cleanup;
1560 1561
        }

M
Matthias Bolte 已提交
1562
        if (id != id_candidate) {
1563 1564 1565
            continue;
        }

M
Matthias Bolte 已提交
1566
        domain = virGetDomain(conn, name_candidate, uuid_candidate);
1567 1568

        if (domain == NULL) {
M
Matthias Bolte 已提交
1569
            goto cleanup;
1570 1571 1572 1573 1574 1575 1576 1577
        }

        domain->id = id;

        break;
    }

    if (domain == NULL) {
1578
        ESX_ERROR(VIR_ERR_NO_DOMAIN, _("No domain with ID %d"), id);
1579 1580 1581 1582 1583
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
M
Matthias Bolte 已提交
1584
    VIR_FREE(name_candidate);
1585 1586 1587 1588 1589 1590 1591 1592 1593

    return domain;
}



static virDomainPtr
esxDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
M
Matthias Bolte 已提交
1594
    esxPrivate *priv = conn->privateData;
1595 1596 1597
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1598 1599
    int id = -1;
    char *name = NULL;
1600 1601
    virDomainPtr domain = NULL;

1602
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1603
        return NULL;
1604 1605
    }

1606
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1607
                                           "name\0"
1608
                                           "runtime.powerState\0") < 0 ||
1609
        esxVI_LookupVirtualMachineByUuid(priv->primary, uuid, propertyNameList,
1610
                                         &virtualMachine,
M
Matthias Bolte 已提交
1611
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1612 1613
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, &name, NULL) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1614
        goto cleanup;
1615 1616
    }

1617
    domain = virGetDomain(conn, name, uuid);
1618 1619

    if (domain == NULL) {
M
Matthias Bolte 已提交
1620
        goto cleanup;
1621
    }
1622

1623 1624 1625 1626 1627
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1628 1629 1630 1631
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1632 1633
    esxVI_ObjectContent_Free(&virtualMachine);
    VIR_FREE(name);
1634 1635 1636 1637 1638 1639 1640 1641 1642

    return domain;
}



static virDomainPtr
esxDomainLookupByName(virConnectPtr conn, const char *name)
{
M
Matthias Bolte 已提交
1643
    esxPrivate *priv = conn->privateData;
1644 1645 1646
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1647 1648
    int id = -1;
    unsigned char uuid[VIR_UUID_BUFLEN];
1649 1650
    virDomainPtr domain = NULL;

1651
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1652
        return NULL;
1653 1654
    }

1655
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1656
                                           "configStatus\0"
1657
                                           "runtime.powerState\0"
1658
                                           "config.uuid\0") < 0 ||
1659
        esxVI_LookupVirtualMachineByName(priv->primary, name, propertyNameList,
1660 1661
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
1662
        goto cleanup;
1663 1664
    }

1665
    if (virtualMachine == NULL) {
1666
        ESX_ERROR(VIR_ERR_NO_DOMAIN, _("No domain with name '%s'"), name);
M
Matthias Bolte 已提交
1667
        goto cleanup;
1668
    }
1669 1670


M
Matthias Bolte 已提交
1671 1672 1673
    if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, uuid) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
1674
    }
1675

1676
    domain = virGetDomain(conn, name, uuid);
1677

1678
    if (domain == NULL) {
M
Matthias Bolte 已提交
1679
        goto cleanup;
1680 1681
    }

1682 1683 1684 1685 1686
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1687 1688 1689 1690
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1691
    esxVI_ObjectContent_Free(&virtualMachine);
1692 1693 1694 1695 1696 1697 1698 1699 1700

    return domain;
}



static int
esxDomainSuspend(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1701
    int result = -1;
M
Matthias Bolte 已提交
1702
    esxPrivate *priv = domain->conn->privateData;
1703 1704 1705 1706 1707 1708
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1709
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1710
        return -1;
1711 1712
    }

1713
    if (esxVI_String_AppendValueToList(&propertyNameList,
1714
                                       "runtime.powerState") < 0 ||
1715
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1716
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1717 1718
           priv->autoAnswer) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1719
        goto cleanup;
1720 1721 1722
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1723 1724
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1725
        goto cleanup;
1726 1727
    }

1728 1729
    if (esxVI_SuspendVM_Task(priv->primary, virtualMachine->obj, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1730
                                    esxVI_Occurrence_RequiredItem,
1731
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
1732
        goto cleanup;
1733 1734 1735
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1736
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not suspend domain"));
M
Matthias Bolte 已提交
1737
        goto cleanup;
1738 1739
    }

M
Matthias Bolte 已提交
1740 1741
    result = 0;

1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainResume(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1755
    int result = -1;
M
Matthias Bolte 已提交
1756
    esxPrivate *priv = domain->conn->privateData;
1757 1758 1759 1760 1761 1762
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1763
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1764
        return -1;
1765 1766
    }

1767
    if (esxVI_String_AppendValueToList(&propertyNameList,
1768
                                       "runtime.powerState") < 0 ||
1769
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1770
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1771 1772
           priv->autoAnswer) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1773
        goto cleanup;
1774 1775 1776
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended) {
1777
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not suspended"));
M
Matthias Bolte 已提交
1778
        goto cleanup;
1779 1780
    }

1781
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
1782
                             &task) < 0 ||
1783
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1784
                                    esxVI_Occurrence_RequiredItem,
1785
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
1786
        goto cleanup;
1787 1788 1789
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1790
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not resume domain"));
M
Matthias Bolte 已提交
1791
        goto cleanup;
1792 1793
    }

M
Matthias Bolte 已提交
1794 1795
    result = 0;

1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainShutdown(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1809
    int result = -1;
M
Matthias Bolte 已提交
1810
    esxPrivate *priv = domain->conn->privateData;
1811 1812 1813 1814
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1815
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1816
        return -1;
1817 1818
    }

1819
    if (esxVI_String_AppendValueToList(&propertyNameList,
1820
                                       "runtime.powerState") < 0 ||
1821
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1822
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1823
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1824
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1825
        goto cleanup;
1826 1827 1828
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1829 1830
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1831
        goto cleanup;
1832 1833
    }

1834
    if (esxVI_ShutdownGuest(priv->primary, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1835
        goto cleanup;
1836 1837
    }

M
Matthias Bolte 已提交
1838 1839
    result = 0;

1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
esxDomainReboot(virDomainPtr domain, unsigned int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
1852
    int result = -1;
M
Matthias Bolte 已提交
1853
    esxPrivate *priv = domain->conn->privateData;
1854 1855 1856 1857
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1858
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1859
        return -1;
1860 1861
    }

1862
    if (esxVI_String_AppendValueToList(&propertyNameList,
1863
                                       "runtime.powerState") < 0 ||
1864
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1865
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1866
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1867
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1868
        goto cleanup;
1869 1870 1871
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1872 1873
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1874
        goto cleanup;
1875 1876
    }

1877
    if (esxVI_RebootGuest(priv->primary, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1878
        goto cleanup;
1879 1880
    }

M
Matthias Bolte 已提交
1881 1882
    result = 0;

1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
esxDomainDestroy(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1895
    int result = -1;
M
Matthias Bolte 已提交
1896
    esxPrivate *priv = domain->conn->privateData;
1897
    esxVI_Context *ctx = NULL;
1898 1899 1900 1901 1902 1903
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1904 1905 1906 1907 1908 1909
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

1910
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
1911
        return -1;
1912 1913
    }

1914
    if (esxVI_String_AppendValueToList(&propertyNameList,
1915
                                       "runtime.powerState") < 0 ||
1916
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1917
          (ctx, domain->uuid, propertyNameList, &virtualMachine,
1918
           priv->autoAnswer) < 0 ||
1919
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1920
        goto cleanup;
1921 1922 1923
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1924 1925
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1926
        goto cleanup;
1927 1928
    }

1929
    if (esxVI_PowerOffVM_Task(ctx, virtualMachine->obj, &task) < 0 ||
1930 1931 1932
        esxVI_WaitForTaskCompletion(ctx, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
1933
        goto cleanup;
1934 1935 1936
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1937
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not destroy domain"));
M
Matthias Bolte 已提交
1938
        goto cleanup;
1939 1940
    }

1941
    domain->id = -1;
M
Matthias Bolte 已提交
1942 1943
    result = 0;

1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static char *
1955
esxDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED)
1956
{
1957 1958 1959
    char *osType = strdup("hvm");

    if (osType == NULL) {
1960
        virReportOOMError();
1961 1962 1963 1964
        return NULL;
    }

    return osType;
1965 1966 1967 1968 1969 1970 1971
}



static unsigned long
esxDomainGetMaxMemory(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1972
    esxPrivate *priv = domain->conn->privateData;
1973 1974 1975 1976 1977
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    unsigned long memoryMB = 0;

1978
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1979
        return 0;
1980 1981
    }

1982
    if (esxVI_String_AppendValueToList(&propertyNameList,
1983
                                       "config.hardware.memoryMB") < 0 ||
1984
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1985
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1986
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
1987
        goto cleanup;
1988 1989 1990 1991 1992
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
1993
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1994
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1995
                goto cleanup;
1996 1997 1998
            }

            if (dynamicProperty->val->int32 < 0) {
1999 2000
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                          _("Got invalid memory size %d"),
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023
                          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 已提交
2024
    int result = -1;
M
Matthias Bolte 已提交
2025
    esxPrivate *priv = domain->conn->privateData;
2026 2027 2028 2029 2030
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

2031
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2032
        return -1;
2033 2034
    }

2035
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2036
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2037
           priv->autoAnswer) < 0 ||
2038 2039
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Long_Alloc(&spec->memoryMB) < 0) {
M
Matthias Bolte 已提交
2040
        goto cleanup;
2041 2042 2043 2044 2045
    }

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

2046
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2047
                              &task) < 0 ||
2048
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2049
                                    esxVI_Occurrence_RequiredItem,
2050
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2051
        goto cleanup;
2052 2053 2054
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2055
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2056
                  _("Could not set max-memory to %lu kilobytes"), memory);
M
Matthias Bolte 已提交
2057
        goto cleanup;
2058 2059
    }

M
Matthias Bolte 已提交
2060 2061
    result = 0;

2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074
  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 已提交
2075
    int result = -1;
M
Matthias Bolte 已提交
2076
    esxPrivate *priv = domain->conn->privateData;
2077 2078 2079 2080 2081
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

2082
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2083
        return -1;
2084 2085
    }

2086
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2087
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2088
           priv->autoAnswer) < 0 ||
2089 2090 2091
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0 ||
        esxVI_Long_Alloc(&spec->memoryAllocation->limit) < 0) {
M
Matthias Bolte 已提交
2092
        goto cleanup;
2093 2094 2095 2096 2097
    }

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

2098
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2099
                              &task) < 0 ||
2100
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2101
                                    esxVI_Occurrence_RequiredItem,
2102
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2103
        goto cleanup;
2104 2105 2106
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2107
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2108
                  _("Could not set memory to %lu kilobytes"), memory);
M
Matthias Bolte 已提交
2109
        goto cleanup;
2110 2111
    }

M
Matthias Bolte 已提交
2112 2113
    result = 0;

2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126
  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 已提交
2127
    int result = -1;
M
Matthias Bolte 已提交
2128
    esxPrivate *priv = domain->conn->privateData;
2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140
    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;
2141 2142
    esxVI_PerfEntityMetricBase *perfEntityMetricBase = NULL;
    esxVI_PerfEntityMetricBase *perfEntityMetricBaseList = NULL;
2143 2144 2145 2146
    esxVI_PerfEntityMetric *perfEntityMetric = NULL;
    esxVI_PerfMetricIntSeries *perfMetricIntSeries = NULL;
    esxVI_Long *value = NULL;

M
Matthias Bolte 已提交
2147 2148
    memset(info, 0, sizeof (*info));

2149
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2150
        return -1;
2151 2152
    }

2153
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2154 2155 2156 2157
                                           "runtime.powerState\0"
                                           "config.hardware.memoryMB\0"
                                           "config.hardware.numCPU\0"
                                           "config.memoryAllocation.limit\0") < 0 ||
2158
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2159
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2160
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2161
        goto cleanup;
2162 2163 2164 2165 2166 2167 2168 2169
    }

    info->state = VIR_DOMAIN_NOSTATE;

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

2174 2175
            info->state = esxVI_VirtualMachinePowerState_ConvertToLibvirt
                            (powerState);
2176
        } else if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2177
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2178
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2179
                goto cleanup;
2180 2181 2182 2183
            }

            info->maxMem = dynamicProperty->val->int32 * 1024; /* Scale from megabyte to kilobyte */
        } else if (STREQ(dynamicProperty->name, "config.hardware.numCPU")) {
2184
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2185
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2186
                goto cleanup;
2187 2188 2189 2190 2191
            }

            info->nrVirtCpu = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "config.memoryAllocation.limit")) {
2192
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2193
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
2194
                goto cleanup;
2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210
            }

            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 */
2211 2212 2213 2214 2215 2216
    /* 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;
            }
2217

2218
            counterId->value = priv->usedCpuTimeCounterId;
2219

2220 2221 2222
            if (esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                goto cleanup;
            }
2223

2224 2225 2226 2227
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfo) < 0) {
                goto cleanup;
            }
2228

2229 2230 2231 2232 2233
            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);
2234

2235 2236 2237 2238 2239
                priv->usedCpuTimeCounterId = -1;
            }

            esxVI_Int_Free(&counterIdList);
            esxVI_PerfCounterInfo_Free(&perfCounterInfo);
2240 2241
        }

2242 2243 2244 2245 2246 2247 2248 2249 2250 2251
        /*
         * 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;
            }
2252

2253 2254 2255 2256
            for (perfMetricId = perfMetricIdList; perfMetricId != NULL;
                 perfMetricId = perfMetricId->_next) {
                VIR_DEBUG("perfMetricId counterId %d, instance '%s'",
                          perfMetricId->counterId->value, perfMetricId->instance);
2257

2258
                counterId = NULL;
2259

2260 2261 2262 2263 2264
                if (esxVI_Int_DeepCopy(&counterId, perfMetricId->counterId) < 0 ||
                    esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                    goto cleanup;
                }
            }
2265

2266 2267
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfoList) < 0) {
M
Matthias Bolte 已提交
2268
                goto cleanup;
2269 2270
            }

2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287
            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;
                }
2288 2289
            }

2290 2291 2292
            if (priv->usedCpuTimeCounterId < 0) {
                VIR_WARN0("Could not find 'used CPU time' performance counter");
            }
2293 2294
        }

2295 2296 2297 2298 2299 2300
        /*
         * 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);
2301

2302 2303 2304 2305 2306 2307
            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;
            }
2308

2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321
            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;
            }
2322

2323 2324 2325 2326
            for (perfEntityMetricBase = perfEntityMetricBaseList;
                 perfEntityMetricBase != NULL;
                 perfEntityMetricBase = perfEntityMetricBase->_next) {
                VIR_DEBUG0("perfEntityMetric ...");
2327

2328 2329
                perfEntityMetric =
                  esxVI_PerfEntityMetric_DynamicCast(perfEntityMetricBase);
2330

2331 2332 2333
                if (perfMetricIntSeries == NULL) {
                    VIR_ERROR0(_("QueryPerf returned object with unexpected type"));
                }
2334

2335 2336
                perfMetricIntSeries =
                  esxVI_PerfMetricIntSeries_DynamicCast(perfEntityMetric->value);
2337

2338 2339 2340
                if (perfMetricIntSeries == NULL) {
                    VIR_ERROR0(_("QueryPerf returned object with unexpected type"));
                }
2341

2342 2343 2344
                for (; perfMetricIntSeries != NULL;
                     perfMetricIntSeries = perfMetricIntSeries->_next) {
                    VIR_DEBUG0("perfMetricIntSeries ...");
2345

2346 2347 2348 2349 2350
                    for (value = perfMetricIntSeries->value;
                         value != NULL;
                         value = value->_next) {
                        VIR_DEBUG("value %lld", (long long int)value->value);
                    }
2351 2352 2353
                }
            }

2354 2355 2356
            querySpec->entity = NULL;
            querySpec->metricId->instance = NULL;
            querySpec->format = NULL;
2357

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

2360 2361 2362 2363 2364
            /*
             * FIXME: Cannot map between realtive used-cpu-time and absolute
             *        info->cpuTime
             */
        }
2365 2366
    }

M
Matthias Bolte 已提交
2367 2368
    result = 0;

2369 2370 2371 2372 2373 2374 2375
  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);
2376
    esxVI_PerfEntityMetricBase_Free(&perfEntityMetricBaseList);
2377 2378 2379 2380 2381 2382 2383 2384 2385

    return result;
}



static int
esxDomainSetVcpus(virDomainPtr domain, unsigned int nvcpus)
{
M
Matthias Bolte 已提交
2386
    int result = -1;
M
Matthias Bolte 已提交
2387
    esxPrivate *priv = domain->conn->privateData;
M
Matthias Bolte 已提交
2388
    int maxVcpus;
2389 2390 2391 2392 2393 2394
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

    if (nvcpus < 1) {
2395 2396
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Requested number of virtual CPUs must at least be 1"));
M
Matthias Bolte 已提交
2397
        return -1;
2398 2399
    }

2400
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2401
        return -1;
2402 2403
    }

M
Matthias Bolte 已提交
2404
    maxVcpus = esxDomainGetMaxVcpus(domain);
2405

M
Matthias Bolte 已提交
2406
    if (maxVcpus < 0) {
M
Matthias Bolte 已提交
2407
        return -1;
2408 2409
    }

M
Matthias Bolte 已提交
2410
    if (nvcpus > maxVcpus) {
2411
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2412 2413
                  _("Requested number of virtual CPUs is greater than max "
                    "allowable number of virtual CPUs for the domain: %d > %d"),
M
Matthias Bolte 已提交
2414
                  nvcpus, maxVcpus);
M
Matthias Bolte 已提交
2415
        return -1;
2416 2417
    }

2418
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2419
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2420
           priv->autoAnswer) < 0 ||
2421 2422
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Int_Alloc(&spec->numCPUs) < 0) {
M
Matthias Bolte 已提交
2423
        goto cleanup;
2424 2425 2426 2427
    }

    spec->numCPUs->value = nvcpus;

2428
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2429
                              &task) < 0 ||
2430
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2431
                                    esxVI_Occurrence_RequiredItem,
2432
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2433
        goto cleanup;
2434 2435 2436
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2437
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2438
                  _("Could not set number of virtual CPUs to %d"), nvcpus);
M
Matthias Bolte 已提交
2439
        goto cleanup;
2440 2441
    }

M
Matthias Bolte 已提交
2442 2443
    result = 0;

2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainGetMaxVcpus(virDomainPtr domain)
{
M
Matthias Bolte 已提交
2457
    esxPrivate *priv = domain->conn->privateData;
2458 2459 2460 2461
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

M
Matthias Bolte 已提交
2462 2463
    if (priv->maxVcpus > 0) {
        return priv->maxVcpus;
2464 2465
    }

M
Matthias Bolte 已提交
2466 2467
    priv->maxVcpus = -1;

2468
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2469
        return -1;
2470 2471
    }

2472
    if (esxVI_String_AppendValueToList(&propertyNameList,
2473
                                       "capability.maxSupportedVcpus") < 0 ||
2474 2475
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
2476
        goto cleanup;
2477 2478 2479
    }

    if (hostSystem == NULL) {
2480 2481
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
2482
        goto cleanup;
2483 2484 2485 2486 2487
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "capability.maxSupportedVcpus")) {
2488
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2489
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2490
                goto cleanup;
2491 2492
            }

M
Matthias Bolte 已提交
2493
            priv->maxVcpus = dynamicProperty->val->int32;
2494 2495 2496 2497 2498 2499 2500 2501 2502 2503
            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

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

M
Matthias Bolte 已提交
2504
    return priv->maxVcpus;
2505 2506 2507 2508 2509 2510 2511
}



static char *
esxDomainDumpXML(virDomainPtr domain, int flags)
{
M
Matthias Bolte 已提交
2512
    esxPrivate *priv = domain->conn->privateData;
2513 2514
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
2515 2516
    esxVI_VirtualMachinePowerState powerState;
    int id;
2517
    char *vmPathName = NULL;
2518
    char *datastoreName = NULL;
M
Matthias Bolte 已提交
2519
    char *directoryName = NULL;
2520
    char *directoryAndFileName = NULL;
2521
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
2522 2523
    char *url = NULL;
    char *vmx = NULL;
2524 2525
    esxVMX_Context ctx;
    esxVMX_Data data;
2526 2527 2528
    virDomainDefPtr def = NULL;
    char *xml = NULL;

2529
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2530
        return NULL;
2531 2532
    }

2533 2534 2535
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "config.files.vmPathName\0"
                                           "runtime.powerState\0") < 0 ||
2536
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2537
                                         propertyNameList, &virtualMachine,
2538
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2539 2540
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0 ||
2541 2542
        esxVI_GetStringValue(virtualMachine, "config.files.vmPathName",
                             &vmPathName, esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2543
        goto cleanup;
2544 2545
    }

2546
    if (esxUtil_ParseDatastorePath(vmPathName, &datastoreName, &directoryName,
2547
                                   &directoryAndFileName) < 0) {
M
Matthias Bolte 已提交
2548
        goto cleanup;
2549 2550
    }

2551 2552
    virBufferVSprintf(&buffer, "%s://%s:%d/folder/", priv->transport,
                      domain->conn->uri->server, domain->conn->uri->port);
2553
    virBufferURIEncodeString(&buffer, directoryAndFileName);
2554
    virBufferAddLit(&buffer, "?dcPath=");
2555
    virBufferURIEncodeString(&buffer, priv->primary->datacenter->name);
2556 2557 2558 2559
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
2560
        virReportOOMError();
M
Matthias Bolte 已提交
2561
        goto cleanup;
2562 2563
    }

2564 2565
    url = virBufferContentAndReset(&buffer);

2566
    if (esxVI_Context_DownloadFile(priv->primary, url, &vmx) < 0) {
M
Matthias Bolte 已提交
2567
        goto cleanup;
2568 2569
    }

2570
    data.ctx = priv->primary;
2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584

    if (directoryName == NULL) {
        if (virAsprintf(&data.datastorePathWithoutFileName, "[%s]",
                        datastoreName) < 0) {
            virReportOOMError();
            goto cleanup;
        }
    } else {
        if (virAsprintf(&data.datastorePathWithoutFileName, "[%s] %s",
                        datastoreName, directoryName) < 0) {
            virReportOOMError();
            goto cleanup;
        }
    }
2585 2586 2587 2588 2589 2590 2591 2592

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

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

    if (def != NULL) {
2595 2596 2597 2598
        if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
            def->id = id;
        }

2599
        xml = virDomainDefFormat(def, flags);
2600 2601 2602
    }

  cleanup:
M
Matthias Bolte 已提交
2603 2604 2605 2606
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

2607 2608
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2609
    VIR_FREE(datastoreName);
M
Matthias Bolte 已提交
2610
    VIR_FREE(directoryName);
2611
    VIR_FREE(directoryAndFileName);
2612
    VIR_FREE(url);
2613
    VIR_FREE(data.datastorePathWithoutFileName);
2614
    VIR_FREE(vmx);
2615
    virDomainDefFree(def);
2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626

    return xml;
}



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

    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2634
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2635
                  _("Unsupported config format '%s'"), nativeFormat);
2636
        return NULL;
2637 2638
    }

2639
    data.ctx = priv->primary;
2640
    data.datastorePathWithoutFileName = (char *)"[?] ?";
2641 2642 2643 2644 2645 2646 2647

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

    def = esxVMX_ParseConfig(&ctx, priv->caps, nativeConfig,
2648
                             priv->primary->productVersion);
2649 2650

    if (def != NULL) {
2651
        xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
2652 2653 2654 2655 2656 2657 2658 2659 2660
    }

    virDomainDefFree(def);

    return xml;
}



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

    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2673
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2674
                  _("Unsupported config format '%s'"), nativeFormat);
M
Matthias Bolte 已提交
2675 2676 2677
        return NULL;
    }

2678
    def = virDomainDefParseString(priv->caps, domainXml, 0);
M
Matthias Bolte 已提交
2679 2680 2681 2682 2683

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

2684
    data.ctx = priv->primary;
2685
    data.datastorePathWithoutFileName = NULL;
2686 2687 2688 2689 2690 2691 2692

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

    vmx = esxVMX_FormatConfig(&ctx, priv->caps, def,
2693
                              priv->primary->productVersion);
M
Matthias Bolte 已提交
2694 2695 2696 2697 2698 2699 2700 2701

    virDomainDefFree(def);

    return vmx;
}



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

    if (names == NULL || maxnames < 0) {
2716 2717
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
2718 2719 2720 2721 2722 2723
    }

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

2724
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2725
        return -1;
2726 2727
    }

2728
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2729 2730
                                           "name\0"
                                           "runtime.powerState\0") < 0 ||
2731 2732
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2733
        goto cleanup;
2734 2735 2736 2737
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
2738
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
2739
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
2740
            goto cleanup;
2741 2742 2743 2744 2745 2746 2747 2748 2749 2750
        }

        if (powerState == esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

        for (dynamicProperty = virtualMachine->propSet;
             dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "name")) {
2751
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2752
                                             esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
2753
                    goto cleanup;
2754 2755 2756 2757 2758
                }

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

                if (names[count] == NULL) {
2759
                    virReportOOMError();
M
Matthias Bolte 已提交
2760
                    goto cleanup;
2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772
                }

                count++;
                break;
            }
        }

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

M
Matthias Bolte 已提交
2773
    success = true;
2774

M
Matthias Bolte 已提交
2775 2776 2777 2778 2779
  cleanup:
    if (! success) {
        for (i = 0; i < count; ++i) {
            VIR_FREE(names[i]);
        }
2780

M
Matthias Bolte 已提交
2781
        count = -1;
2782 2783
    }

M
Matthias Bolte 已提交
2784 2785
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
2786

M
Matthias Bolte 已提交
2787
    return count;
2788 2789 2790 2791 2792 2793 2794
}



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

2797
    if (esxVI_EnsureSession(priv->primary) < 0) {
2798 2799 2800
        return -1;
    }

2801
    return esxVI_LookupNumberOfDomainsByPowerState
2802
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn,
2803 2804 2805 2806 2807 2808
              esxVI_Boolean_True);
}



static int
2809
esxDomainCreateWithFlags(virDomainPtr domain, unsigned int flags)
2810
{
M
Matthias Bolte 已提交
2811
    int result = -1;
M
Matthias Bolte 已提交
2812
    esxPrivate *priv = domain->conn->privateData;
2813 2814 2815
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
2816
    int id = -1;
2817 2818 2819
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

2820 2821
    virCheckFlags(0, -1);

2822
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2823
        return -1;
2824 2825
    }

2826
    if (esxVI_String_AppendValueToList(&propertyNameList,
2827
                                       "runtime.powerState") < 0 ||
2828
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2829
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
2830
           priv->autoAnswer) < 0 ||
2831 2832
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0) {
M
Matthias Bolte 已提交
2833
        goto cleanup;
2834 2835 2836
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2837 2838
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered off"));
M
Matthias Bolte 已提交
2839
        goto cleanup;
2840 2841
    }

2842
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
2843
                             &task) < 0 ||
2844
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2845
                                    esxVI_Occurrence_RequiredItem,
2846
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2847
        goto cleanup;
2848 2849 2850
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2851
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not start domain"));
M
Matthias Bolte 已提交
2852
        goto cleanup;
2853 2854
    }

2855
    domain->id = id;
M
Matthias Bolte 已提交
2856 2857
    result = 0;

2858 2859 2860 2861 2862 2863 2864 2865
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}

2866 2867 2868 2869 2870
static int
esxDomainCreate(virDomainPtr domain)
{
    return esxDomainCreateWithFlags(domain, 0);
}
2871

M
Matthias Bolte 已提交
2872 2873 2874
static virDomainPtr
esxDomainDefineXML(virConnectPtr conn, const char *xml ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2875
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
2876 2877
    virDomainDefPtr def = NULL;
    char *vmx = NULL;
2878 2879
    int i;
    virDomainDiskDefPtr disk = NULL;
M
Matthias Bolte 已提交
2880
    esxVI_ObjectContent *virtualMachine = NULL;
2881 2882
    esxVMX_Context ctx;
    esxVMX_Data data;
M
Matthias Bolte 已提交
2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894
    char *datastoreName = NULL;
    char *directoryName = 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;

2895
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2896
        return NULL;
M
Matthias Bolte 已提交
2897 2898 2899
    }

    /* Parse domain XML */
2900
    def = virDomainDefParseString(priv->caps, xml,
M
Matthias Bolte 已提交
2901 2902 2903
                                  VIR_DOMAIN_XML_INACTIVE);

    if (def == NULL) {
M
Matthias Bolte 已提交
2904
        return NULL;
M
Matthias Bolte 已提交
2905 2906 2907
    }

    /* Check if an existing domain should be edited */
2908
    if (esxVI_LookupVirtualMachineByUuid(priv->primary, def->uuid, NULL,
M
Matthias Bolte 已提交
2909
                                         &virtualMachine,
M
Matthias Bolte 已提交
2910
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
2911
        goto cleanup;
M
Matthias Bolte 已提交
2912 2913 2914 2915
    }

    if (virtualMachine != NULL) {
        /* FIXME */
2916 2917 2918
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Domain already exists, editing existing domains is not "
                    "supported yet"));
M
Matthias Bolte 已提交
2919
        goto cleanup;
M
Matthias Bolte 已提交
2920 2921 2922
    }

    /* Build VMX from domain XML */
2923
    data.ctx = priv->primary;
2924
    data.datastorePathWithoutFileName = NULL;
2925 2926 2927 2928 2929 2930 2931

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

    vmx = esxVMX_FormatConfig(&ctx, priv->caps, def,
2932
                              priv->primary->productVersion);
M
Matthias Bolte 已提交
2933 2934

    if (vmx == NULL) {
M
Matthias Bolte 已提交
2935
        goto cleanup;
M
Matthias Bolte 已提交
2936 2937
    }

2938 2939 2940 2941 2942 2943 2944
    /*
     * 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 已提交
2945
    if (def->ndisks < 1) {
2946 2947 2948
        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 已提交
2949
        goto cleanup;
2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960
    }

    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) {
2961 2962 2963
        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 已提交
2964
        goto cleanup;
M
Matthias Bolte 已提交
2965 2966
    }

2967
    if (disk->src == NULL) {
2968 2969 2970
        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 已提交
2971
        goto cleanup;
M
Matthias Bolte 已提交
2972 2973
    }

2974
    if (esxUtil_ParseDatastorePath(disk->src, &datastoreName, &directoryName,
2975
                                   NULL) < 0) {
M
Matthias Bolte 已提交
2976
        goto cleanup;
M
Matthias Bolte 已提交
2977 2978
    }

2979
    if (! virFileHasSuffix(disk->src, ".vmdk")) {
2980
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2981 2982
                  _("Expecting source '%s' of first file-based harddisk to "
                    "be a VMDK image"), disk->src);
M
Matthias Bolte 已提交
2983
        goto cleanup;
M
Matthias Bolte 已提交
2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995
    }

    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=");
2996
    virBufferURIEncodeString(&buffer, priv->primary->datacenter->name);
M
Matthias Bolte 已提交
2997 2998 2999 3000
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
3001
        virReportOOMError();
M
Matthias Bolte 已提交
3002
        goto cleanup;
M
Matthias Bolte 已提交
3003 3004 3005 3006 3007 3008 3009
    }

    url = virBufferContentAndReset(&buffer);

    if (directoryName != NULL) {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s/%s.vmx", datastoreName,
                        directoryName, def->name) < 0) {
3010
            virReportOOMError();
M
Matthias Bolte 已提交
3011
            goto cleanup;
M
Matthias Bolte 已提交
3012 3013 3014 3015
        }
    } else {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s.vmx", datastoreName,
                        def->name) < 0) {
3016
            virReportOOMError();
M
Matthias Bolte 已提交
3017
            goto cleanup;
M
Matthias Bolte 已提交
3018 3019 3020 3021 3022 3023 3024
        }
    }

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

    /* Upload VMX file */
3025
    if (esxVI_Context_UploadFile(priv->primary, url, vmx) < 0) {
M
Matthias Bolte 已提交
3026
        goto cleanup;
M
Matthias Bolte 已提交
3027 3028 3029
    }

    /* Register the domain */
3030
    if (esxVI_RegisterVM_Task(priv->primary, priv->primary->datacenter->vmFolder,
M
Matthias Bolte 已提交
3031
                              datastoreRelatedPath, NULL, esxVI_Boolean_False,
3032 3033 3034 3035
                              priv->primary->computeResource->resourcePool,
                              priv->primary->hostSystem->_reference,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, def->uuid,
3036
                                    esxVI_Occurrence_OptionalItem,
3037
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3038
        goto cleanup;
M
Matthias Bolte 已提交
3039 3040 3041
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3042
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not define domain"));
M
Matthias Bolte 已提交
3043
        goto cleanup;
M
Matthias Bolte 已提交
3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054
    }

    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 已提交
3055 3056 3057 3058
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

M
Matthias Bolte 已提交
3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075
    virDomainDefFree(def);
    VIR_FREE(vmx);
    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
    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;
}



3076 3077 3078
static int
esxDomainUndefine(virDomainPtr domain)
{
M
Matthias Bolte 已提交
3079
    int result = -1;
M
Matthias Bolte 已提交
3080
    esxPrivate *priv = domain->conn->privateData;
3081
    esxVI_Context *ctx = NULL;
3082 3083 3084 3085
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

3086 3087 3088 3089 3090 3091
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

3092
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
3093
        return -1;
3094 3095
    }

3096
    if (esxVI_String_AppendValueToList(&propertyNameList,
3097
                                       "runtime.powerState") < 0 ||
3098 3099
        esxVI_LookupVirtualMachineByUuid(ctx, domain->uuid, propertyNameList,
                                         &virtualMachine,
M
Matthias Bolte 已提交
3100
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3101
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
3102
        goto cleanup;
3103 3104 3105 3106
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended &&
        powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
3107 3108
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not suspended or powered off"));
M
Matthias Bolte 已提交
3109
        goto cleanup;
3110 3111
    }

3112
    if (esxVI_UnregisterVM(ctx, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
3113
        goto cleanup;
3114 3115
    }

M
Matthias Bolte 已提交
3116 3117
    result = 0;

3118 3119 3120 3121 3122 3123 3124 3125 3126
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138
/*
 * 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)
 *
3139
 *   The amount of CPU resource that is guaranteed to be available to the domain.
3140 3141 3142 3143
 *
 *
 * - limit (VIR_DOMAIN_SCHED_FIELD_LLONG >= 0, or -1, in megaherz)
 *
3144 3145
 *   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
3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156
 *   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'.
 */
3157
static char *
3158
esxDomainGetSchedulerType(virDomainPtr domain ATTRIBUTE_UNUSED, int *nparams)
3159 3160 3161 3162
{
    char *type = strdup("allocation");

    if (type == NULL) {
3163
        virReportOOMError();
3164
        return NULL;
3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177
    }

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

    return type;
}



static int
esxDomainGetSchedulerParameters(virDomainPtr domain,
                                virSchedParameterPtr params, int *nparams)
{
M
Matthias Bolte 已提交
3178
    int result = -1;
M
Matthias Bolte 已提交
3179
    esxPrivate *priv = domain->conn->privateData;
3180 3181 3182 3183 3184 3185 3186 3187
    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) {
3188 3189
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Parameter array must have space for 3 items"));
M
Matthias Bolte 已提交
3190
        return -1;
3191 3192
    }

3193
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3194
        return -1;
3195 3196
    }

3197
    if (esxVI_String_AppendValueListToList(&propertyNameList,
3198 3199 3200
                                           "config.cpuAllocation.reservation\0"
                                           "config.cpuAllocation.limit\0"
                                           "config.cpuAllocation.shares\0") < 0 ||
3201
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
3202
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3203
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3204
        goto cleanup;
3205 3206 3207 3208 3209 3210
    }

    for (dynamicProperty = virtualMachine->propSet;
         dynamicProperty != NULL && mask != 7 && i < 3;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.cpuAllocation.reservation") &&
M
Matthias Bolte 已提交
3211
            ! (mask & (1 << 0))) {
3212 3213 3214 3215 3216
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "reservation");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_LLONG;

3217
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3218
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3219
                goto cleanup;
3220 3221 3222 3223 3224 3225 3226
            }

            params[i].value.l = dynamicProperty->val->int64;
            mask |= 1 << 0;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.limit") &&
M
Matthias Bolte 已提交
3227
                   ! (mask & (1 << 1))) {
3228 3229 3230 3231 3232
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "limit");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_LLONG;

3233
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3234
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3235
                goto cleanup;
3236 3237 3238 3239 3240 3241 3242
            }

            params[i].value.l = dynamicProperty->val->int64;
            mask |= 1 << 1;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.shares") &&
M
Matthias Bolte 已提交
3243
                   ! (mask & (1 << 2))) {
3244 3245 3246 3247 3248
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "shares");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_INT;

3249
            if (esxVI_SharesInfo_CastFromAnyType(dynamicProperty->val,
3250
                                                 &sharesInfo) < 0) {
M
Matthias Bolte 已提交
3251
                goto cleanup;
3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271
            }

            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:
3272
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3273
                          _("Shares level has unknown value %d"),
3274
                          (int)sharesInfo->level);
M
Matthias Bolte 已提交
3275
                goto cleanup;
3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287
            }

            esxVI_SharesInfo_Free(&sharesInfo);

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

    *nparams = i;
M
Matthias Bolte 已提交
3288
    result = 0;
3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302

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

    return result;
}



static int
esxDomainSetSchedulerParameters(virDomainPtr domain,
                                virSchedParameterPtr params, int nparams)
{
M
Matthias Bolte 已提交
3303
    int result = -1;
M
Matthias Bolte 已提交
3304
    esxPrivate *priv = domain->conn->privateData;
3305 3306 3307 3308 3309 3310 3311
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
    int i;

3312
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3313
        return -1;
3314 3315
    }

3316
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3317
          (priv->primary, domain->uuid, NULL, &virtualMachine,
3318
           priv->autoAnswer) < 0 ||
3319 3320
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->cpuAllocation) < 0) {
M
Matthias Bolte 已提交
3321
        goto cleanup;
3322 3323 3324 3325 3326
    }

    for (i = 0; i < nparams; ++i) {
        if (STREQ (params[i].field, "reservation") &&
            params[i].type == VIR_DOMAIN_SCHED_FIELD_LLONG) {
3327
            if (esxVI_Long_Alloc(&spec->cpuAllocation->reservation) < 0) {
M
Matthias Bolte 已提交
3328
                goto cleanup;
3329 3330 3331
            }

            if (params[i].value.l < 0) {
3332
                ESX_ERROR(VIR_ERR_INVALID_ARG,
3333 3334
                          _("Could not set reservation to %lld MHz, expecting "
                            "positive value"), params[i].value.l);
M
Matthias Bolte 已提交
3335
                goto cleanup;
3336 3337 3338 3339 3340
            }

            spec->cpuAllocation->reservation->value = params[i].value.l;
        } else if (STREQ (params[i].field, "limit") &&
                   params[i].type == VIR_DOMAIN_SCHED_FIELD_LLONG) {
3341
            if (esxVI_Long_Alloc(&spec->cpuAllocation->limit) < 0) {
M
Matthias Bolte 已提交
3342
                goto cleanup;
3343 3344 3345
            }

            if (params[i].value.l < -1) {
3346
                ESX_ERROR(VIR_ERR_INVALID_ARG,
3347 3348
                          _("Could not set limit to %lld MHz, expecting "
                            "positive value or -1 (unlimited)"),
3349
                          params[i].value.l);
M
Matthias Bolte 已提交
3350
                goto cleanup;
3351 3352 3353 3354
            }

            spec->cpuAllocation->limit->value = params[i].value.l;
        } else if (STREQ (params[i].field, "shares") &&
3355
                   params[i].type == VIR_DOMAIN_SCHED_FIELD_INT) {
3356 3357
            if (esxVI_SharesInfo_Alloc(&sharesInfo) < 0 ||
                esxVI_Int_Alloc(&sharesInfo->shares) < 0) {
M
Matthias Bolte 已提交
3358
                goto cleanup;
3359 3360 3361 3362
            }

            spec->cpuAllocation->shares = sharesInfo;

3363
            if (params[i].value.i >= 0) {
3364
                spec->cpuAllocation->shares->level = esxVI_SharesLevel_Custom;
3365
                spec->cpuAllocation->shares->shares->value = params[i].value.i;
3366
            } else {
3367
                switch (params[i].value.i) {
3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385
                  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:
3386
                    ESX_ERROR(VIR_ERR_INVALID_ARG,
3387 3388
                              _("Could not set shares to %d, expecting positive "
                                "value or -1 (low), -2 (normal) or -3 (high)"),
3389
                              params[i].value.i);
M
Matthias Bolte 已提交
3390
                    goto cleanup;
3391 3392 3393
                }
            }
        } else {
3394
            ESX_ERROR(VIR_ERR_INVALID_ARG, _("Unknown field '%s'"),
3395
                      params[i].field);
M
Matthias Bolte 已提交
3396
            goto cleanup;
3397 3398 3399
        }
    }

3400
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
3401
                              &task) < 0 ||
3402
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3403
                                    esxVI_Occurrence_RequiredItem,
3404
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3405
        goto cleanup;
3406 3407 3408
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3409 3410
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not change scheduler parameters"));
M
Matthias Bolte 已提交
3411
        goto cleanup;
3412 3413
    }

M
Matthias Bolte 已提交
3414 3415
    result = 0;

3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429
  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,
3430 3431
                        const char *uri_in ATTRIBUTE_UNUSED,
                        char **uri_out,
3432 3433 3434 3435
                        unsigned long flags ATTRIBUTE_UNUSED,
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
3436
    esxPrivate *priv = dconn->privateData;
3437 3438

    if (uri_in == NULL) {
3439 3440 3441 3442
        if (virAsprintf(uri_out, "vpxmigr://%s/%s/%s",
                        priv->vCenter->ipAddress,
                        priv->vCenter->computeResource->resourcePool->value,
                        priv->vCenter->hostSystem->_reference->value) < 0) {
3443
            virReportOOMError();
3444
            return -1;
3445 3446 3447
        }
    }

3448
    return 0;
3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461
}



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 已提交
3462
    int result = -1;
M
Matthias Bolte 已提交
3463
    esxPrivate *priv = domain->conn->privateData;
3464 3465 3466 3467
    xmlURIPtr parsedUri = NULL;
    char *saveptr;
    char *path_resourcePool;
    char *path_hostSystem;
3468
    esxVI_ObjectContent *virtualMachine = NULL;
3469 3470
    esxVI_ManagedObjectReference resourcePool;
    esxVI_ManagedObjectReference hostSystem;
3471 3472 3473 3474
    esxVI_Event *eventList = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

M
Matthias Bolte 已提交
3475
    if (priv->vCenter == NULL) {
3476 3477
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Migration not possible without a vCenter"));
M
Matthias Bolte 已提交
3478
        return -1;
3479 3480 3481
    }

    if (dname != NULL) {
3482 3483
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Renaming domains on migration not supported"));
M
Matthias Bolte 已提交
3484
        return -1;
3485 3486
    }

3487
    if (esxVI_EnsureSession(priv->vCenter) < 0) {
M
Matthias Bolte 已提交
3488
        return -1;
3489 3490
    }

3491 3492
    /* Parse migration URI */
    parsedUri = xmlParseURI(uri);
3493

3494
    if (parsedUri == NULL) {
3495
        virReportOOMError();
M
Matthias Bolte 已提交
3496
        return -1;
3497 3498
    }

3499 3500 3501
    if (parsedUri->scheme == NULL || STRCASENEQ(parsedUri->scheme, "vpxmigr")) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Only vpxmigr:// migration URIs are supported"));
M
Matthias Bolte 已提交
3502
        goto cleanup;
3503 3504
    }

3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517
    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 已提交
3518
        goto cleanup;
3519 3520
    }

3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534
    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 已提交
3535
        goto cleanup;
3536 3537 3538
    }

    /* Validate the purposed migration */
3539
    if (esxVI_ValidateMigration(priv->vCenter, virtualMachine->obj,
3540 3541
                                esxVI_VirtualMachinePowerState_Undefined, NULL,
                                &resourcePool, &hostSystem, &eventList) < 0) {
M
Matthias Bolte 已提交
3542
        goto cleanup;
3543 3544 3545 3546 3547 3548 3549 3550
    }

    if (eventList != NULL) {
        /*
         * FIXME: Need to report the complete list of events. Limit reporting
         *        to the first event for now.
         */
        if (eventList->fullFormattedMessage != NULL) {
3551
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3552 3553
                      _("Could not migrate domain, validation reported a "
                        "problem: %s"), eventList->fullFormattedMessage);
3554
        } else {
3555 3556 3557
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                      _("Could not migrate domain, validation reported a "
                        "problem"));
3558 3559
        }

M
Matthias Bolte 已提交
3560
        goto cleanup;
3561 3562 3563
    }

    /* Perform the purposed migration */
3564 3565
    if (esxVI_MigrateVM_Task(priv->vCenter, virtualMachine->obj,
                             &resourcePool, &hostSystem,
3566 3567 3568
                             esxVI_VirtualMachineMovePriority_DefaultPriority,
                             esxVI_VirtualMachinePowerState_Undefined,
                             &task) < 0 ||
3569
        esxVI_WaitForTaskCompletion(priv->vCenter, task, domain->uuid,
3570
                                    esxVI_Occurrence_RequiredItem,
3571
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3572
        goto cleanup;
3573 3574 3575
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3576 3577 3578
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not migrate domain, migration task finished with "
                    "an error"));
M
Matthias Bolte 已提交
3579
        goto cleanup;
3580 3581
    }

M
Matthias Bolte 已提交
3582 3583
    result = 0;

3584
  cleanup:
3585
    xmlFreeURI(parsedUri);
3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606
    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 已提交
3607 3608 3609 3610
static unsigned long long
esxNodeGetFreeMemory(virConnectPtr conn)
{
    unsigned long long result = 0;
M
Matthias Bolte 已提交
3611
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
3612 3613 3614 3615 3616
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *resourcePool = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ResourcePoolResourceUsage *resourcePoolResourceUsage = NULL;

3617
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3618
        return 0;
M
Matthias Bolte 已提交
3619 3620 3621
    }

    /* Get memory usage of resource pool */
3622
    if (esxVI_String_AppendValueToList(&propertyNameList,
M
Matthias Bolte 已提交
3623
                                       "runtime.memory") < 0 ||
3624 3625
        esxVI_LookupObjectContentByType(priv->primary,
                                        priv->primary->computeResource->resourcePool,
3626 3627
                                        "ResourcePool", propertyNameList,
                                        &resourcePool) < 0) {
M
Matthias Bolte 已提交
3628
        goto cleanup;
M
Matthias Bolte 已提交
3629 3630 3631 3632 3633 3634
    }

    for (dynamicProperty = resourcePool->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.memory")) {
            if (esxVI_ResourcePoolResourceUsage_CastFromAnyType
3635
                  (dynamicProperty->val, &resourcePoolResourceUsage) < 0) {
M
Matthias Bolte 已提交
3636
                goto cleanup;
M
Matthias Bolte 已提交
3637 3638 3639 3640 3641 3642 3643 3644 3645
            }

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

    if (resourcePoolResourceUsage == NULL) {
3646 3647
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve memory usage of resource pool"));
M
Matthias Bolte 已提交
3648
        goto cleanup;
M
Matthias Bolte 已提交
3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662
    }

    result = resourcePoolResourceUsage->unreservedForVm->value;

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

    return result;
}



3663 3664 3665
static int
esxIsEncrypted(virConnectPtr conn)
{
M
Matthias Bolte 已提交
3666
    esxPrivate *priv = conn->privateData;
3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679

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



static int
esxIsSecure(virConnectPtr conn)
{
M
Matthias Bolte 已提交
3680
    esxPrivate *priv = conn->privateData;
3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693

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



static int
esxDomainIsActive(virDomainPtr domain)
{
M
Matthias Bolte 已提交
3694
    int result = -1;
M
Matthias Bolte 已提交
3695
    esxPrivate *priv = domain->conn->privateData;
3696 3697 3698 3699
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

3700
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3701
        return -1;
3702 3703
    }

3704
    if (esxVI_String_AppendValueToList(&propertyNameList,
3705
                                       "runtime.powerState") < 0 ||
3706
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
3707
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3708
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3709
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
3710
        goto cleanup;
3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736
    }

    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;
}



3737 3738
static virDomainSnapshotPtr
esxDomainSnapshotCreateXML(virDomainPtr domain, const char *xmlDesc,
3739
                           unsigned int flags)
3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750
{
    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;

3751 3752
    virCheckFlags(0, NULL);

3753
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3754
        return NULL;
3755 3756 3757 3758 3759
    }

    def = virDomainSnapshotDefParseString(xmlDesc, 1);

    if (def == NULL) {
M
Matthias Bolte 已提交
3760
        return NULL;
3761 3762 3763
    }

    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3764
          (priv->primary, domain->uuid, NULL, &virtualMachine,
3765
           priv->autoAnswer) < 0 ||
3766
        esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
3767 3768 3769 3770
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, def->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
3771
        goto cleanup;
3772 3773 3774 3775 3776
    }

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

3780
    if (esxVI_CreateSnapshot_Task(priv->primary, virtualMachine->obj,
3781 3782 3783
                                  def->name, def->description,
                                  esxVI_Boolean_True,
                                  esxVI_Boolean_False, &task) < 0 ||
3784
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3785
                                    esxVI_Occurrence_RequiredItem,
3786
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3787
        goto cleanup;
3788 3789 3790 3791
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not create snapshot"));
M
Matthias Bolte 已提交
3792
        goto cleanup;
3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809
    }

    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,
3810
                         unsigned int flags)
3811 3812 3813 3814 3815 3816 3817 3818 3819
{
    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;

3820 3821
    virCheckFlags(0, NULL);

M
Matthias Bolte 已提交
3822
    memset(&def, 0, sizeof (def));
3823

3824
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3825
        return NULL;
3826 3827
    }

3828
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
3829 3830 3831 3832
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3833
        goto cleanup;
3834 3835 3836 3837 3838 3839 3840 3841
    }

    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 已提交
3842
        goto cleanup;
3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860
    }

    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
3861
esxDomainSnapshotNum(virDomainPtr domain, unsigned int flags)
3862
{
M
Matthias Bolte 已提交
3863
    int count;
3864 3865 3866
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;

3867 3868
    virCheckFlags(0, -1);

3869
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3870
        return -1;
3871 3872
    }

3873
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
3874
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
3875
        return -1;
3876 3877
    }

M
Matthias Bolte 已提交
3878
    count = esxVI_GetNumberOfSnapshotTrees(rootSnapshotTreeList);
3879 3880 3881

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

M
Matthias Bolte 已提交
3882
    return count;
3883 3884 3885 3886 3887 3888
}



static int
esxDomainSnapshotListNames(virDomainPtr domain, char **names, int nameslen,
3889
                           unsigned int flags)
3890
{
M
Matthias Bolte 已提交
3891
    int result;
3892 3893 3894
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;

3895 3896
    virCheckFlags(0, -1);

3897 3898 3899 3900 3901 3902 3903 3904 3905
    if (names == NULL || nameslen < 0) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
    }

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

3906
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3907
        return -1;
3908 3909
    }

3910
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
3911
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
3912
        return -1;
3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925
    }

    result = esxVI_GetSnapshotTreeNames(rootSnapshotTreeList, names, nameslen);

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



static virDomainSnapshotPtr
esxDomainSnapshotLookupByName(virDomainPtr domain, const char *name,
3926
                              unsigned int flags)
3927 3928 3929 3930 3931 3932 3933
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    virDomainSnapshotPtr snapshot = NULL;

3934 3935
    virCheckFlags(0, NULL);

3936
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3937
        return NULL;
3938 3939
    }

3940
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963
                                         &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;

3964
    virCheckFlags(0, -1);
3965

3966
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3967
        return -1;
3968 3969
    }

3970
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
3971 3972
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
3973
        return -1;
3974 3975 3976
    }

    if (currentSnapshotTree != NULL) {
M
Matthias Bolte 已提交
3977 3978
        esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);
        return 1;
3979 3980
    }

M
Matthias Bolte 已提交
3981
    return 0;
3982 3983 3984 3985 3986 3987 3988 3989 3990
}



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

3993
    virCheckFlags(0, NULL);
3994

3995
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3996
        return NULL;
3997 3998
    }

3999
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4000 4001
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4002
        return NULL;
4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016
    }

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

    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return snapshot;
}



static int
esxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4017
    int result = -1;
4018 4019 4020 4021 4022 4023 4024
    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;

4025
    virCheckFlags(0, -1);
4026

4027
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4028
        return -1;
4029 4030
    }

4031
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4032 4033 4034 4035
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4036
        goto cleanup;
4037 4038
    }

4039
    if (esxVI_RevertToSnapshot_Task(priv->primary, snapshotTree->snapshot, NULL,
4040
                                    &task) < 0 ||
4041
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4042
                                    esxVI_Occurrence_RequiredItem,
4043
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
4044
        goto cleanup;
4045 4046 4047 4048 4049
    }

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

M
Matthias Bolte 已提交
4053 4054
    result = 0;

4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainSnapshotDelete(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4067
    int result = -1;
4068 4069 4070 4071 4072 4073 4074 4075
    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;

4076 4077
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN, -1);

4078
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4079
        return -1;
4080 4081 4082 4083 4084 4085
    }

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

4086
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4087 4088 4089 4090
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4091
        goto cleanup;
4092 4093
    }

4094
    if (esxVI_RemoveSnapshot_Task(priv->primary, snapshotTree->snapshot,
4095
                                  removeChildren, &task) < 0 ||
4096
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4097
                                    esxVI_Occurrence_RequiredItem,
4098
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
4099
        goto cleanup;
4100 4101 4102 4103 4104
    }

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

M
Matthias Bolte 已提交
4108 4109
    result = 0;

4110 4111 4112 4113 4114 4115 4116 4117 4118
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



4119 4120 4121 4122 4123 4124 4125 4126
static virDriver esxDriver = {
    VIR_DRV_ESX,
    "ESX",
    esxOpen,                         /* open */
    esxClose,                        /* close */
    esxSupportsFeature,              /* supports_feature */
    esxGetType,                      /* type */
    esxGetVersion,                   /* version */
4127
    NULL,                            /* libvirtVersion (impl. in libvirt.c) */
4128 4129 4130
    esxGetHostname,                  /* hostname */
    NULL,                            /* getMaxVcpus */
    esxNodeGetInfo,                  /* nodeGetInfo */
4131
    esxGetCapabilities,              /* getCapabilities */
4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157
    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 */
4158
    esxDomainXMLFromNative,          /* domainXMLFromNative */
M
Matthias Bolte 已提交
4159
    esxDomainXMLToNative,            /* domainXMLToNative */
4160 4161 4162
    esxListDefinedDomains,           /* listDefinedDomains */
    esxNumberOfDefinedDomains,       /* numOfDefinedDomains */
    esxDomainCreate,                 /* domainCreate */
4163
    esxDomainCreateWithFlags,        /* domainCreateWithFlags */
M
Matthias Bolte 已提交
4164
    esxDomainDefineXML,              /* domainDefineXML */
4165
    esxDomainUndefine,               /* domainUndefine */
4166
    NULL,                            /* domainAttachDevice */
4167
    NULL,                            /* domainAttachDeviceFlags */
4168
    NULL,                            /* domainDetachDevice */
4169
    NULL,                            /* domainDetachDeviceFlags */
4170
    NULL,                            /* domainUpdateDeviceFlags */
4171 4172 4173 4174 4175 4176 4177 4178 4179 4180
    NULL,                            /* domainGetAutostart */
    NULL,                            /* domainSetAutostart */
    esxDomainGetSchedulerType,       /* domainGetSchedulerType */
    esxDomainGetSchedulerParameters, /* domainGetSchedulerParameters */
    esxDomainSetSchedulerParameters, /* domainSetSchedulerParameters */
    esxDomainMigratePrepare,         /* domainMigratePrepare */
    esxDomainMigratePerform,         /* domainMigratePerform */
    esxDomainMigrateFinish,          /* domainMigrateFinish */
    NULL,                            /* domainBlockStats */
    NULL,                            /* domainInterfaceStats */
4181
    NULL,                            /* domainMemoryStats */
4182 4183
    NULL,                            /* domainBlockPeek */
    NULL,                            /* domainMemoryPeek */
4184
    NULL,                            /* domainGetBlockInfo */
4185
    NULL,                            /* nodeGetCellsFreeMemory */
M
Matthias Bolte 已提交
4186
    esxNodeGetFreeMemory,            /* nodeGetFreeMemory */
4187 4188 4189 4190 4191 4192 4193
    NULL,                            /* domainEventRegister */
    NULL,                            /* domainEventDeregister */
    NULL,                            /* domainMigratePrepare2 */
    NULL,                            /* domainMigrateFinish2 */
    NULL,                            /* nodeDeviceDettach */
    NULL,                            /* nodeDeviceReAttach */
    NULL,                            /* nodeDeviceReset */
C
Chris Lalancette 已提交
4194
    NULL,                            /* domainMigratePrepareTunnel */
4195 4196 4197 4198
    esxIsEncrypted,                  /* isEncrypted */
    esxIsSecure,                     /* isSecure */
    esxDomainIsActive,               /* domainIsActive */
    esxDomainIsPersistent,           /* domainIsPersistent */
J
Jiri Denemark 已提交
4199
    NULL,                            /* cpuCompare */
4200
    NULL,                            /* cpuBaseline */
4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217
    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 已提交
4218
    NULL,                            /* qemuDomainMonitorCommand */
4219 4220 4221 4222 4223 4224 4225
};



int
esxRegister(void)
{
4226 4227 4228 4229 4230
    if (virRegisterDriver(&esxDriver) < 0 ||
        esxInterfaceRegister() < 0 ||
        esxNetworkRegister() < 0 ||
        esxStorageRegister() < 0 ||
        esxDeviceRegister() < 0 ||
M
Matthias Bolte 已提交
4231 4232
        esxSecretRegister() < 0 ||
        esxNWFilterRegister() < 0) {
4233 4234
        return -1;
    }
4235 4236 4237

    return 0;
}