esx_driver.c 148.8 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-2011 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
#include "util.h"
#include "memory.h"
#include "logging.h"
#include "uuid.h"
34
#include "vmx.h"
35
#include "esx_driver.h"
36 37 38 39 40
#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 已提交
41
#include "esx_nwfilter_driver.h"
42
#include "esx_private.h"
43 44 45 46 47 48 49 50
#include "esx_vi.h"
#include "esx_vi_methods.h"
#include "esx_util.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
/*
 * 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
91
 * function via the opaque parameter by the caller of virVMXParseConfig.
92 93 94 95 96 97 98 99 100
 *
 * 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,
                                            false, &fileInfo,
358
                                            esxVI_Occurrence_RequiredItem) < 0) {
359 360 361
        goto cleanup;
    }

362
    vmDiskFileInfo = esxVI_VmDiskFileInfo_DynamicCast(fileInfo);
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391

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

    return result;
}

397 398


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

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

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

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

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

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

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

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

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

                    break;
                }
            }

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

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

    return priv->supportsLongMode;
}



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

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

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "hardware.systemInfo.uuid") < 0 ||
500 501
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
        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) {
521 522 523 524 525
                    VIR_WARN("Could not parse host UUID from string '%s'",
                             dynamicProperty->val->string);

                    /* HostSystem has an invalid UUID, ignore it */
                    memset(uuid, 0, VIR_UUID_BUFLEN);
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
                }
            } 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;
}



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

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

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

    if (caps == NULL) {
567
        virReportOOMError();
568 569 570
        return NULL;
    }

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

574 575
    caps->hasWideScsiBus = true;

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

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

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

    if (virCapabilitiesAddGuestDomain(guest, "vmware", NULL, NULL, 0,
                                      NULL) == NULL) {
        goto failure;
    }

593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
    /* x86_64 */
    if (supportsLongMode == esxVI_Boolean_True) {
        guest = virCapabilitiesAddGuest(caps, "hvm", "x86_64", 64, NULL, NULL,
                                        0, NULL);

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

        if (virCapabilitiesAddGuestDomain(guest, "vmware", NULL, NULL, 0,
                                          NULL) == NULL) {
            goto failure;
        }
    }

608 609 610 611 612 613 614 615 616 617
    return caps;

  failure:
    virCapabilitiesFree(caps);

    return NULL;
}



618 619 620 621
static int
esxConnectToHost(esxPrivate *priv, virConnectAuthPtr auth,
                 const char *hostname, int port,
                 const char *predefinedUsername,
M
Matthias Bolte 已提交
622
                 esxUtil_ParsedUri *parsedUri,
623 624 625 626 627 628
                 esxVI_ProductVersion expectedProductVersion,
                 char **vCenterIpAddress)
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
M
Matthias Bolte 已提交
629
    char *unescapedPassword = NULL;
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
    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;
        }
    }

M
Matthias Bolte 已提交
661
    unescapedPassword = virRequestPassword(auth, username, hostname);
662

M
Matthias Bolte 已提交
663
    if (unescapedPassword == NULL) {
664 665 666 667
        ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
        goto cleanup;
    }

M
Matthias Bolte 已提交
668 669 670 671 672 673
    password = esxUtil_EscapeForXml(unescapedPassword);

    if (password == NULL) {
        goto cleanup;
    }

674 675 676 677 678 679 680 681
    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,
682 683
                              parsedUri) < 0 ||
        esxVI_Context_LookupObjectsByPath(priv->host, parsedUri) < 0) {
684 685 686 687 688
        goto cleanup;
    }

    if (expectedProductVersion == esxVI_ProductVersion_ESX) {
        if (priv->host->productVersion != esxVI_ProductVersion_ESX35 &&
M
Matthias Bolte 已提交
689 690 691
            priv->host->productVersion != esxVI_ProductVersion_ESX40 &&
            priv->host->productVersion != esxVI_ProductVersion_ESX41 &&
            priv->host->productVersion != esxVI_ProductVersion_ESX4x) {
692
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
M
Matthias Bolte 已提交
693
                      _("%s is neither an ESX 3.5 host nor an ESX 4.x host"),
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
                      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 ||
709 710
        esxVI_LookupHostSystemProperties(priv->host, propertyNameList,
                                         &hostSystem) < 0 ||
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
        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(username);
M
Matthias Bolte 已提交
738 739
    VIR_FREE(unescapedPassword);
    VIR_FREE(password);
740 741 742 743 744 745 746 747 748 749 750 751 752
    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,
753
                    const char *hostSystemIpAddress,
M
Matthias Bolte 已提交
754
                    esxUtil_ParsedUri *parsedUri)
755 756 757 758
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
M
Matthias Bolte 已提交
759
    char *unescapedPassword = NULL;
760 761 762
    char *password = NULL;
    char *url = NULL;

763 764 765 766 767 768 769 770
    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;
    }

771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
    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;
        }
    }

M
Matthias Bolte 已提交
791
    unescapedPassword = virRequestPassword(auth, username, hostname);
792

M
Matthias Bolte 已提交
793
    if (unescapedPassword == NULL) {
794 795 796 797
        ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
        goto cleanup;
    }

M
Matthias Bolte 已提交
798 799 800 801 802 803
    password = esxUtil_EscapeForXml(unescapedPassword);

    if (password == NULL) {
        goto cleanup;
    }

804 805 806 807 808 809 810 811
    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 已提交
812
                              password, parsedUri) < 0) {
813 814 815 816
        goto cleanup;
    }

    if (priv->vCenter->productVersion != esxVI_ProductVersion_VPX25 &&
M
Matthias Bolte 已提交
817 818 819
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX40 &&
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX41 &&
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX4x) {
820 821
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("%s is neither a vCenter 2.5 server nor a vCenter "
M
Matthias Bolte 已提交
822
                    "4.x server"), hostname);
823 824 825
        goto cleanup;
    }

826 827 828 829 830 831 832 833 834 835 836
    if (hostSystemIpAddress != NULL) {
        if (esxVI_Context_LookupObjectsByHostSystemIp(priv->vCenter,
                                                      hostSystemIpAddress) < 0) {
            goto cleanup;
        }
    } else {
        if (esxVI_Context_LookupObjectsByPath(priv->vCenter, parsedUri) < 0) {
            goto cleanup;
        }
    }

837 838 839 840
    result = 0;

  cleanup:
    VIR_FREE(username);
M
Matthias Bolte 已提交
841 842
    VIR_FREE(unescapedPassword);
    VIR_FREE(password);
843 844 845 846 847 848 849
    VIR_FREE(url);

    return result;
}



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

903
    /* Decline if the URI is NULL or the scheme is not one of {vpx|esx|gsx} */
904
    if (conn->uri == NULL || conn->uri->scheme == NULL ||
905 906
        (STRCASENEQ(conn->uri->scheme, "vpx") &&
         STRCASENEQ(conn->uri->scheme, "esx") &&
907
         STRCASENEQ(conn->uri->scheme, "gsx"))) {
908 909 910
        return VIR_DRV_OPEN_DECLINED;
    }

M
Matthias Bolte 已提交
911 912 913
    /* Decline URIs without server part, or missing auth */
    if (conn->uri->server == NULL || auth == NULL || auth->cb == NULL) {
        return VIR_DRV_OPEN_DECLINED;
914 915 916 917
    }

    /* Allocate per-connection private data */
    if (VIR_ALLOC(priv) < 0) {
918
        virReportOOMError();
M
Matthias Bolte 已提交
919
        goto cleanup;
920 921
    }

M
Matthias Bolte 已提交
922
    if (esxUtil_ParseUri(&parsedUri, conn->uri) < 0) {
923 924 925
        goto cleanup;
    }

M
Matthias Bolte 已提交
926 927
    priv->transport = parsedUri->transport;
    parsedUri->transport = NULL;
928

M
Matthias Bolte 已提交
929 930
    priv->maxVcpus = -1;
    priv->supportsVMotion = esxVI_Boolean_Undefined;
931
    priv->supportsLongMode = esxVI_Boolean_Undefined;
M
Matthias Bolte 已提交
932 933
    priv->autoAnswer = parsedUri->autoAnswer ? esxVI_Boolean_True
                                             : esxVI_Boolean_False;
934 935
    priv->usedCpuTimeCounterId = -1;

M
Matthias Bolte 已提交
936 937 938 939 940 941 942
    /*
     * 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) {
943 944
        if (STRCASEEQ(conn->uri->scheme, "vpx") ||
            STRCASEEQ(conn->uri->scheme, "esx")) {
M
Matthias Bolte 已提交
945 946 947 948 949 950 951 952 953 954 955
            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;
            }
956
        }
M
Matthias Bolte 已提交
957
    }
958

959 960 961 962
    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 已提交
963
                             conn->uri->user, parsedUri,
964 965 966 967
                             STRCASEEQ(conn->uri->scheme, "esx")
                               ? esxVI_ProductVersion_ESX
                               : esxVI_ProductVersion_GSX,
                             &potentialVCenterIpAddress) < 0) {
M
Matthias Bolte 已提交
968
            goto cleanup;
969
        }
970

971
        /* Connect to vCenter */
M
Matthias Bolte 已提交
972 973
        if (parsedUri->vCenter != NULL) {
            if (STREQ(parsedUri->vCenter, "*")) {
974 975 976
                if (potentialVCenterIpAddress == NULL) {
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                              _("This host is not managed by a vCenter"));
M
Matthias Bolte 已提交
977
                    goto cleanup;
978 979
                }

980 981 982 983 984 985 986 987
                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 已提交
988
                if (esxUtil_ResolveHostname(parsedUri->vCenter,
989 990 991
                                            vCenterIpAddress, NI_MAXHOST) < 0) {
                    goto cleanup;
                }
992

993 994
                if (potentialVCenterIpAddress != NULL &&
                    STRNEQ(vCenterIpAddress, potentialVCenterIpAddress)) {
995
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
996 997 998
                              _("This host is managed by a vCenter with IP "
                                "address %s, but a mismachting vCenter '%s' "
                                "(%s) has been specified"),
M
Matthias Bolte 已提交
999
                              potentialVCenterIpAddress, parsedUri->vCenter,
1000
                              vCenterIpAddress);
M
Matthias Bolte 已提交
1001
                    goto cleanup;
1002 1003
                }
            }
1004

1005
            if (esxConnectToVCenter(priv, auth, vCenterIpAddress,
1006 1007
                                    conn->uri->port, NULL,
                                    priv->host->ipAddress, parsedUri) < 0) {
1008 1009
                goto cleanup;
            }
1010 1011
        }

1012 1013 1014 1015
        priv->primary = priv->host;
    } else { /* VPX */
        /* Connect to vCenter */
        if (esxConnectToVCenter(priv, auth, conn->uri->server, conn->uri->port,
1016
                                conn->uri->user, NULL, parsedUri) < 0) {
M
Matthias Bolte 已提交
1017
            goto cleanup;
1018 1019
        }

1020
        priv->primary = priv->vCenter;
1021 1022 1023
    }

    conn->privateData = priv;
1024

M
Matthias Bolte 已提交
1025
    /* Setup capabilities */
1026
    priv->caps = esxCapsInit(priv);
1027

M
Matthias Bolte 已提交
1028
    if (priv->caps == NULL) {
M
Matthias Bolte 已提交
1029
        goto cleanup;
1030 1031
    }

M
Matthias Bolte 已提交
1032
    result = VIR_DRV_OPEN_SUCCESS;
1033

M
Matthias Bolte 已提交
1034 1035
  cleanup:
    if (result == VIR_DRV_OPEN_ERROR && priv != NULL) {
1036
        esxVI_Context_Free(&priv->host);
M
Matthias Bolte 已提交
1037
        esxVI_Context_Free(&priv->vCenter);
1038

1039 1040
        virCapabilitiesFree(priv->caps);

M
Matthias Bolte 已提交
1041
        VIR_FREE(priv->transport);
1042 1043 1044
        VIR_FREE(priv);
    }

M
Matthias Bolte 已提交
1045
    esxUtil_FreeParsedUri(&parsedUri);
1046
    VIR_FREE(potentialVCenterIpAddress);
1047

M
Matthias Bolte 已提交
1048
    return result;
1049 1050 1051 1052 1053 1054 1055
}



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

1059 1060 1061 1062 1063
    if (priv->host != NULL) {
        if (esxVI_EnsureSession(priv->host) < 0 ||
            esxVI_Logout(priv->host) < 0) {
            result = -1;
        }
1064

1065 1066
        esxVI_Context_Free(&priv->host);
    }
1067

M
Matthias Bolte 已提交
1068
    if (priv->vCenter != NULL) {
E
Eric Blake 已提交
1069 1070 1071 1072
        if (esxVI_EnsureSession(priv->vCenter) < 0 ||
            esxVI_Logout(priv->vCenter) < 0) {
            result = -1;
        }
1073

M
Matthias Bolte 已提交
1074
        esxVI_Context_Free(&priv->vCenter);
1075 1076
    }

1077 1078
    virCapabilitiesFree(priv->caps);

1079 1080 1081 1082 1083
    VIR_FREE(priv->transport);
    VIR_FREE(priv);

    conn->privateData = NULL;

E
Eric Blake 已提交
1084
    return result;
1085 1086 1087 1088 1089
}



static esxVI_Boolean
1090
esxSupportsVMotion(esxPrivate *priv)
1091 1092 1093 1094
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;

M
Matthias Bolte 已提交
1095 1096
    if (priv->supportsVMotion != esxVI_Boolean_Undefined) {
        return priv->supportsVMotion;
1097 1098
    }

1099
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1100
        return esxVI_Boolean_Undefined;
1101 1102
    }

1103
    if (esxVI_String_AppendValueToList(&propertyNameList,
1104
                                       "capability.vmotionSupported") < 0 ||
1105 1106
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1107
        goto cleanup;
1108 1109 1110
    }

    if (hostSystem == NULL) {
1111 1112
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
1113
        goto cleanup;
1114 1115
    }

1116 1117 1118 1119
    if (esxVI_GetBoolean(hostSystem, "capability.vmotionSupported",
                         &priv->supportsVMotion,
                         esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
1120 1121 1122
    }

  cleanup:
M
Matthias Bolte 已提交
1123 1124 1125 1126
    /*
     * 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.
     */
1127 1128 1129
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
1130
    return priv->supportsVMotion;
1131 1132 1133 1134 1135 1136 1137
}



static int
esxSupportsFeature(virConnectPtr conn, int feature)
{
M
Matthias Bolte 已提交
1138
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1139
    esxVI_Boolean supportsVMotion = esxVI_Boolean_Undefined;
1140 1141 1142

    switch (feature) {
      case VIR_DRV_FEATURE_MIGRATION_V1:
1143
        supportsVMotion = esxSupportsVMotion(priv);
1144

M
Matthias Bolte 已提交
1145
        if (supportsVMotion == esxVI_Boolean_Undefined) {
1146 1147 1148
            return -1;
        }

M
Matthias Bolte 已提交
1149 1150 1151
        /* Migration is only possible via a vCenter and if VMotion is enabled */
        return priv->vCenter != NULL &&
               supportsVMotion == esxVI_Boolean_True ? 1 : 0;
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170

      default:
        return 0;
    }
}



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



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

1173
    if (virParseVersionString(priv->primary->service->about->version,
1174 1175
                              version) < 0) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1176
                  _("Could not parse version number from '%s'"),
1177
                  priv->primary->service->about->version);
1178

1179
        return -1;
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
    }

    return 0;
}



static char *
esxGetHostname(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1190
    esxPrivate *priv = conn->privateData;
1191 1192 1193 1194 1195 1196 1197
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    const char *hostName = NULL;
    const char *domainName = NULL;
    char *complete = NULL;

1198
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1199
        return NULL;
1200 1201 1202
    }

    if (esxVI_String_AppendValueListToList
1203
          (&propertyNameList,
1204 1205
           "config.network.dnsConfig.hostName\0"
           "config.network.dnsConfig.domainName\0") < 0 ||
1206 1207
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1208
        goto cleanup;
1209 1210 1211
    }

    if (hostSystem == NULL) {
1212 1213
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
1214
        goto cleanup;
1215 1216 1217 1218 1219 1220
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name,
                  "config.network.dnsConfig.hostName")) {
1221
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1222
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1223
                goto cleanup;
1224 1225 1226 1227 1228
            }

            hostName = dynamicProperty->val->string;
        } else if (STREQ(dynamicProperty->name,
                         "config.network.dnsConfig.domainName")) {
1229
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1230
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1231
                goto cleanup;
1232 1233 1234 1235 1236 1237 1238 1239
            }

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

M
Matthias Bolte 已提交
1240
    if (hostName == NULL || strlen(hostName) < 1) {
1241 1242
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Missing or empty 'hostName' property"));
M
Matthias Bolte 已提交
1243
        goto cleanup;
1244 1245
    }

M
Matthias Bolte 已提交
1246
    if (domainName == NULL || strlen(domainName) < 1) {
1247
        complete = strdup(hostName);
1248

1249
        if (complete == NULL) {
1250
            virReportOOMError();
M
Matthias Bolte 已提交
1251
            goto cleanup;
1252 1253 1254
        }
    } else {
        if (virAsprintf(&complete, "%s.%s", hostName, domainName) < 0) {
1255
            virReportOOMError();
M
Matthias Bolte 已提交
1256
            goto cleanup;
1257
        }
1258 1259 1260
    }

  cleanup:
M
Matthias Bolte 已提交
1261 1262 1263 1264 1265
    /*
     * 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
     */
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return complete;
}



static int
esxNodeGetInfo(virConnectPtr conn, virNodeInfoPtr nodeinfo)
{
M
Matthias Bolte 已提交
1277
    int result = -1;
M
Matthias Bolte 已提交
1278
    esxPrivate *priv = conn->privateData;
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
    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 已提交
1290
    memset(nodeinfo, 0, sizeof (*nodeinfo));
1291

1292
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1293
        return -1;
1294 1295
    }

1296
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1297 1298 1299 1300 1301 1302 1303
                                           "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 ||
1304 1305
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1306
        goto cleanup;
1307 1308 1309
    }

    if (hostSystem == NULL) {
1310 1311
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
1312
        goto cleanup;
1313 1314 1315 1316 1317
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuInfo.hz")) {
1318
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1319
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1320
                goto cleanup;
1321 1322 1323 1324 1325
            }

            cpuInfo_hz = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuCores")) {
1326
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1327
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1328
                goto cleanup;
1329 1330 1331 1332 1333
            }

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

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

            cpuInfo_numCpuThreads = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name, "hardware.memorySize")) {
1349
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1350
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1351
                goto cleanup;
1352 1353 1354 1355 1356
            }

            memorySize = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.numaInfo.numNodes")) {
1357
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1358
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1359
                goto cleanup;
1360 1361 1362 1363 1364
            }

            numaInfo_numNodes = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "summary.hardware.cpuModel")) {
1365
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1366
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1367
                goto cleanup;
1368 1369 1370 1371 1372 1373
            }

            ptr = dynamicProperty->val->string;

            /* Strip the string to fit more relevant information in 32 chars */
            while (*ptr != '\0') {
M
Matthias Bolte 已提交
1374 1375
                if (STRPREFIX(ptr, "  ")) {
                    memmove(ptr, ptr + 1, strlen(ptr + 1) + 1);
1376
                    continue;
1377
                } else if (STRPREFIX(ptr, "(R)") || STRPREFIX(ptr, "(C)")) {
M
Matthias Bolte 已提交
1378
                    memmove(ptr, ptr + 3, strlen(ptr + 3) + 1);
1379
                    continue;
1380 1381 1382
                } else if (STRPREFIX(ptr, "(TM)")) {
                    memmove(ptr, ptr + 4, strlen(ptr + 4) + 1);
                    continue;
1383 1384 1385 1386 1387
                }

                ++ptr;
            }

C
Chris Lalancette 已提交
1388 1389 1390
            if (virStrncpy(nodeinfo->model, dynamicProperty->val->string,
                           sizeof(nodeinfo->model) - 1,
                           sizeof(nodeinfo->model)) == NULL) {
1391
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1392
                          _("CPU Model %s too long for destination"),
C
Chris Lalancette 已提交
1393
                          dynamicProperty->val->string);
M
Matthias Bolte 已提交
1394
                goto cleanup;
C
Chris Lalancette 已提交
1395
            }
1396 1397 1398 1399 1400 1401 1402
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    nodeinfo->memory = memorySize / 1024; /* Scale from bytes to kilobytes */
    nodeinfo->cpus = cpuInfo_numCpuCores;
1403
    nodeinfo->mhz = cpuInfo_hz / (1000 * 1000); /* Scale from hz to mhz */
1404 1405 1406 1407 1408 1409 1410 1411 1412
    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 已提交
1413 1414
    result = 0;

1415 1416 1417 1418 1419 1420 1421 1422 1423
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



1424 1425 1426
static char *
esxGetCapabilities(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1427
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1428
    char *xml = virCapabilitiesFormatXML(priv->caps);
1429 1430

    if (xml == NULL) {
1431
        virReportOOMError();
1432 1433 1434 1435 1436 1437 1438 1439
        return NULL;
    }

    return xml;
}



1440 1441 1442
static int
esxListDomains(virConnectPtr conn, int *ids, int maxids)
{
M
Matthias Bolte 已提交
1443
    bool success = false;
M
Matthias Bolte 已提交
1444
    esxPrivate *priv = conn->privateData;
1445 1446 1447 1448 1449 1450 1451
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;

    if (ids == NULL || maxids < 0) {
1452 1453
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
1454 1455 1456 1457 1458 1459
    }

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

1460
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1461
        return -1;
1462 1463
    }

1464
    if (esxVI_String_AppendValueToList(&propertyNameList,
1465
                                       "runtime.powerState") < 0 ||
1466 1467
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1468
        goto cleanup;
1469 1470 1471 1472
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
1473
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1474
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1475
            goto cleanup;
1476 1477 1478 1479 1480 1481 1482 1483 1484
        }

        if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

        if (esxUtil_ParseVirtualMachineIDString(virtualMachine->obj->value,
                                                &ids[count]) < 0 ||
            ids[count] <= 0) {
1485
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1486
                      _("Failed to parse positive integer from '%s'"),
1487
                      virtualMachine->obj->value);
M
Matthias Bolte 已提交
1488
            goto cleanup;
1489 1490 1491 1492 1493 1494 1495 1496 1497
        }

        count++;

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

M
Matthias Bolte 已提交
1498 1499
    success = true;

1500 1501 1502 1503
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
1504
    return success ? count : -1;
1505 1506 1507 1508 1509 1510 1511
}



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

1514
    if (esxVI_EnsureSession(priv->primary) < 0) {
1515 1516 1517
        return -1;
    }

1518
    return esxVI_LookupNumberOfDomainsByPowerState
1519
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn,
1520 1521 1522 1523 1524 1525 1526 1527
              esxVI_Boolean_False);
}



static virDomainPtr
esxDomainLookupByID(virConnectPtr conn, int id)
{
M
Matthias Bolte 已提交
1528
    esxPrivate *priv = conn->privateData;
1529 1530 1531 1532
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
M
Matthias Bolte 已提交
1533 1534 1535
    int id_candidate = -1;
    char *name_candidate = NULL;
    unsigned char uuid_candidate[VIR_UUID_BUFLEN];
1536 1537
    virDomainPtr domain = NULL;

1538
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1539
        return NULL;
1540 1541
    }

1542
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1543
                                           "configStatus\0"
1544 1545
                                           "name\0"
                                           "runtime.powerState\0"
1546
                                           "config.uuid\0") < 0 ||
1547 1548
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1549
        goto cleanup;
1550 1551 1552 1553
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
1554
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1555
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1556
            goto cleanup;
1557 1558 1559 1560 1561 1562 1563
        }

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

M
Matthias Bolte 已提交
1564
        VIR_FREE(name_candidate);
1565

1566
        if (esxVI_GetVirtualMachineIdentity(virtualMachine,
M
Matthias Bolte 已提交
1567 1568
                                            &id_candidate, &name_candidate,
                                            uuid_candidate) < 0) {
M
Matthias Bolte 已提交
1569
            goto cleanup;
1570 1571
        }

M
Matthias Bolte 已提交
1572
        if (id != id_candidate) {
1573 1574 1575
            continue;
        }

M
Matthias Bolte 已提交
1576
        domain = virGetDomain(conn, name_candidate, uuid_candidate);
1577 1578

        if (domain == NULL) {
M
Matthias Bolte 已提交
1579
            goto cleanup;
1580 1581 1582 1583 1584 1585 1586 1587
        }

        domain->id = id;

        break;
    }

    if (domain == NULL) {
1588
        ESX_ERROR(VIR_ERR_NO_DOMAIN, _("No domain with ID %d"), id);
1589 1590 1591 1592 1593
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
M
Matthias Bolte 已提交
1594
    VIR_FREE(name_candidate);
1595 1596 1597 1598 1599 1600 1601 1602 1603

    return domain;
}



static virDomainPtr
esxDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
M
Matthias Bolte 已提交
1604
    esxPrivate *priv = conn->privateData;
1605 1606 1607
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1608 1609
    int id = -1;
    char *name = NULL;
1610 1611
    virDomainPtr domain = NULL;

1612
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1613
        return NULL;
1614 1615
    }

1616
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1617
                                           "name\0"
1618
                                           "runtime.powerState\0") < 0 ||
1619
        esxVI_LookupVirtualMachineByUuid(priv->primary, uuid, propertyNameList,
1620
                                         &virtualMachine,
M
Matthias Bolte 已提交
1621
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1622 1623
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, &name, NULL) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1624
        goto cleanup;
1625 1626
    }

1627
    domain = virGetDomain(conn, name, uuid);
1628 1629

    if (domain == NULL) {
M
Matthias Bolte 已提交
1630
        goto cleanup;
1631
    }
1632

1633 1634 1635 1636 1637
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1638 1639 1640 1641
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1642 1643
    esxVI_ObjectContent_Free(&virtualMachine);
    VIR_FREE(name);
1644 1645 1646 1647 1648 1649 1650 1651 1652

    return domain;
}



static virDomainPtr
esxDomainLookupByName(virConnectPtr conn, const char *name)
{
M
Matthias Bolte 已提交
1653
    esxPrivate *priv = conn->privateData;
1654 1655 1656
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1657 1658
    int id = -1;
    unsigned char uuid[VIR_UUID_BUFLEN];
1659 1660
    virDomainPtr domain = NULL;

1661
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1662
        return NULL;
1663 1664
    }

1665
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1666
                                           "configStatus\0"
1667
                                           "runtime.powerState\0"
1668
                                           "config.uuid\0") < 0 ||
1669
        esxVI_LookupVirtualMachineByName(priv->primary, name, propertyNameList,
1670 1671
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
1672
        goto cleanup;
1673 1674
    }

1675
    if (virtualMachine == NULL) {
1676
        ESX_ERROR(VIR_ERR_NO_DOMAIN, _("No domain with name '%s'"), name);
M
Matthias Bolte 已提交
1677
        goto cleanup;
1678
    }
1679

M
Matthias Bolte 已提交
1680 1681 1682
    if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, uuid) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
1683
    }
1684

1685
    domain = virGetDomain(conn, name, uuid);
1686

1687
    if (domain == NULL) {
M
Matthias Bolte 已提交
1688
        goto cleanup;
1689 1690
    }

1691 1692 1693 1694 1695
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1696 1697 1698 1699
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1700
    esxVI_ObjectContent_Free(&virtualMachine);
1701 1702 1703 1704 1705 1706 1707 1708 1709

    return domain;
}



static int
esxDomainSuspend(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1710
    int result = -1;
M
Matthias Bolte 已提交
1711
    esxPrivate *priv = domain->conn->privateData;
1712 1713 1714 1715 1716
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1717
    char *taskInfoErrorMessage = NULL;
1718

1719
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1720
        return -1;
1721 1722
    }

1723
    if (esxVI_String_AppendValueToList(&propertyNameList,
1724
                                       "runtime.powerState") < 0 ||
1725
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1726
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1727 1728
           priv->autoAnswer) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1729
        goto cleanup;
1730 1731 1732
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1733 1734
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1735
        goto cleanup;
1736 1737
    }

1738 1739
    if (esxVI_SuspendVM_Task(priv->primary, virtualMachine->obj, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1740
                                    esxVI_Occurrence_RequiredItem,
1741 1742
                                    priv->autoAnswer, &taskInfoState,
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1743
        goto cleanup;
1744 1745 1746
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1747 1748
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not suspend domain: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
1749
        goto cleanup;
1750 1751
    }

M
Matthias Bolte 已提交
1752 1753
    result = 0;

1754 1755 1756 1757
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1758
    VIR_FREE(taskInfoErrorMessage);
1759 1760 1761 1762 1763 1764 1765 1766 1767

    return result;
}



static int
esxDomainResume(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1768
    int result = -1;
M
Matthias Bolte 已提交
1769
    esxPrivate *priv = domain->conn->privateData;
1770 1771 1772 1773 1774
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1775
    char *taskInfoErrorMessage = NULL;
1776

1777
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1778
        return -1;
1779 1780
    }

1781
    if (esxVI_String_AppendValueToList(&propertyNameList,
1782
                                       "runtime.powerState") < 0 ||
1783
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1784
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1785 1786
           priv->autoAnswer) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1787
        goto cleanup;
1788 1789 1790
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended) {
1791
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not suspended"));
M
Matthias Bolte 已提交
1792
        goto cleanup;
1793 1794
    }

1795
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
1796
                             &task) < 0 ||
1797
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1798
                                    esxVI_Occurrence_RequiredItem,
1799 1800
                                    priv->autoAnswer, &taskInfoState,
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1801
        goto cleanup;
1802 1803 1804
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1805 1806
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not resume domain: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
1807
        goto cleanup;
1808 1809
    }

M
Matthias Bolte 已提交
1810 1811
    result = 0;

1812 1813 1814 1815
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1816
    VIR_FREE(taskInfoErrorMessage);
1817 1818 1819 1820 1821 1822 1823 1824 1825

    return result;
}



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

1832
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1833
        return -1;
1834 1835
    }

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

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

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

M
Matthias Bolte 已提交
1855 1856
    result = 0;

1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



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

1875
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1876
        return -1;
1877 1878
    }

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

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

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

M
Matthias Bolte 已提交
1898 1899
    result = 0;

1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



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

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

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

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

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

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

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

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

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

    return result;
}



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

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

    return osType;
1986 1987 1988 1989 1990 1991 1992
}



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

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

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

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

            if (dynamicProperty->val->int32 < 0) {
2020 2021
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                          _("Got invalid memory size %d"),
2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044
                          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 已提交
2045
    int result = -1;
M
Matthias Bolte 已提交
2046
    esxPrivate *priv = domain->conn->privateData;
2047
    esxVI_String *propertyNameList = NULL;
2048
    esxVI_ObjectContent *virtualMachine = NULL;
2049
    esxVI_VirtualMachinePowerState powerState;
2050 2051 2052
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2053
    char *taskInfoErrorMessage = NULL;
2054

2055
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2056
        return -1;
2057 2058
    }

2059 2060 2061 2062
    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "runtime.powerState") < 0 ||
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
2063
           priv->autoAnswer) < 0 ||
2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered off"));
        goto cleanup;
    }

    if (esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
2075
        esxVI_Long_Alloc(&spec->memoryMB) < 0) {
M
Matthias Bolte 已提交
2076
        goto cleanup;
2077 2078
    }

2079
    /* max-memory must be a multiple of 4096 kilobyte */
2080
    spec->memoryMB->value =
2081
      VIR_DIV_UP(memory, 4096) * 4; /* Scale from kilobytes to megabytes */
2082

2083
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2084
                              &task) < 0 ||
2085
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2086
                                    esxVI_Occurrence_RequiredItem,
2087 2088
                                    priv->autoAnswer, &taskInfoState,
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2089
        goto cleanup;
2090 2091 2092
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2093
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2094 2095
                  _("Could not set max-memory to %lu kilobytes: %s"), memory,
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
2096
        goto cleanup;
2097 2098
    }

M
Matthias Bolte 已提交
2099 2100
    result = 0;

2101
  cleanup:
2102
    esxVI_String_Free(&propertyNameList);
2103 2104 2105
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2106
    VIR_FREE(taskInfoErrorMessage);
2107 2108 2109 2110 2111 2112 2113 2114 2115

    return result;
}



static int
esxDomainSetMemory(virDomainPtr domain, unsigned long memory)
{
M
Matthias Bolte 已提交
2116
    int result = -1;
M
Matthias Bolte 已提交
2117
    esxPrivate *priv = domain->conn->privateData;
2118 2119 2120 2121
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2122
    char *taskInfoErrorMessage = NULL;
2123

2124
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2125
        return -1;
2126 2127
    }

2128
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2129
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2130
           priv->autoAnswer) < 0 ||
2131 2132 2133
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0 ||
        esxVI_Long_Alloc(&spec->memoryAllocation->limit) < 0) {
M
Matthias Bolte 已提交
2134
        goto cleanup;
2135 2136 2137
    }

    spec->memoryAllocation->limit->value =
2138
      VIR_DIV_UP(memory, 1024); /* Scale from kilobytes to megabytes */
2139

2140
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2141
                              &task) < 0 ||
2142
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2143
                                    esxVI_Occurrence_RequiredItem,
2144 2145
                                    priv->autoAnswer, &taskInfoState,
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2146
        goto cleanup;
2147 2148 2149
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2150
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2151 2152
                  _("Could not set memory to %lu kilobytes: %s"), memory,
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
2153
        goto cleanup;
2154 2155
    }

M
Matthias Bolte 已提交
2156 2157
    result = 0;

2158 2159 2160 2161
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2162
    VIR_FREE(taskInfoErrorMessage);
2163 2164 2165 2166 2167 2168 2169 2170 2171

    return result;
}



static int
esxDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info)
{
M
Matthias Bolte 已提交
2172
    int result = -1;
M
Matthias Bolte 已提交
2173
    esxPrivate *priv = domain->conn->privateData;
2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185
    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;
2186 2187
    esxVI_PerfEntityMetricBase *perfEntityMetricBase = NULL;
    esxVI_PerfEntityMetricBase *perfEntityMetricBaseList = NULL;
2188 2189 2190 2191
    esxVI_PerfEntityMetric *perfEntityMetric = NULL;
    esxVI_PerfMetricIntSeries *perfMetricIntSeries = NULL;
    esxVI_Long *value = NULL;

M
Matthias Bolte 已提交
2192 2193
    memset(info, 0, sizeof (*info));

2194
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2195
        return -1;
2196 2197
    }

2198
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2199 2200 2201 2202
                                           "runtime.powerState\0"
                                           "config.hardware.memoryMB\0"
                                           "config.hardware.numCPU\0"
                                           "config.memoryAllocation.limit\0") < 0 ||
2203
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2204
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2205
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2206
        goto cleanup;
2207 2208 2209 2210 2211 2212 2213 2214
    }

    info->state = VIR_DOMAIN_NOSTATE;

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

2219 2220
            info->state = esxVI_VirtualMachinePowerState_ConvertToLibvirt
                            (powerState);
2221
        } else if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2222
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2223
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2224
                goto cleanup;
2225 2226 2227 2228
            }

            info->maxMem = dynamicProperty->val->int32 * 1024; /* Scale from megabyte to kilobyte */
        } else if (STREQ(dynamicProperty->name, "config.hardware.numCPU")) {
2229
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2230
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2231
                goto cleanup;
2232 2233 2234 2235 2236
            }

            info->nrVirtCpu = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "config.memoryAllocation.limit")) {
2237
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2238
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
2239
                goto cleanup;
2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255
            }

            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 */
2256 2257 2258 2259 2260 2261
    /* 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;
            }
2262

2263
            counterId->value = priv->usedCpuTimeCounterId;
2264

2265 2266 2267
            if (esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                goto cleanup;
            }
2268

2269 2270 2271 2272
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfo) < 0) {
                goto cleanup;
            }
2273

2274 2275 2276 2277 2278
            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);
2279

2280 2281 2282 2283 2284
                priv->usedCpuTimeCounterId = -1;
            }

            esxVI_Int_Free(&counterIdList);
            esxVI_PerfCounterInfo_Free(&perfCounterInfo);
2285 2286
        }

2287 2288 2289 2290 2291 2292 2293 2294 2295 2296
        /*
         * 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;
            }
2297

2298 2299 2300 2301
            for (perfMetricId = perfMetricIdList; perfMetricId != NULL;
                 perfMetricId = perfMetricId->_next) {
                VIR_DEBUG("perfMetricId counterId %d, instance '%s'",
                          perfMetricId->counterId->value, perfMetricId->instance);
2302

2303
                counterId = NULL;
2304

2305 2306 2307 2308 2309
                if (esxVI_Int_DeepCopy(&counterId, perfMetricId->counterId) < 0 ||
                    esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                    goto cleanup;
                }
            }
2310

2311 2312
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfoList) < 0) {
M
Matthias Bolte 已提交
2313
                goto cleanup;
2314 2315
            }

2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332
            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;
                }
2333 2334
            }

2335 2336 2337
            if (priv->usedCpuTimeCounterId < 0) {
                VIR_WARN0("Could not find 'used CPU time' performance counter");
            }
2338 2339
        }

2340 2341 2342 2343 2344 2345
        /*
         * 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);
2346

2347 2348 2349 2350 2351 2352
            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;
            }
2353

2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366
            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;
            }
2367

2368 2369 2370 2371
            for (perfEntityMetricBase = perfEntityMetricBaseList;
                 perfEntityMetricBase != NULL;
                 perfEntityMetricBase = perfEntityMetricBase->_next) {
                VIR_DEBUG0("perfEntityMetric ...");
2372

2373 2374
                perfEntityMetric =
                  esxVI_PerfEntityMetric_DynamicCast(perfEntityMetricBase);
2375

2376 2377 2378
                if (perfEntityMetric == NULL) {
                    VIR_ERROR(_("QueryPerf returned object with unexpected type '%s'"),
                              esxVI_Type_ToString(perfEntityMetricBase->_type));
2379
                }
2380

2381 2382
                perfMetricIntSeries =
                  esxVI_PerfMetricIntSeries_DynamicCast(perfEntityMetric->value);
2383

2384
                if (perfMetricIntSeries == NULL) {
2385 2386
                    VIR_ERROR(_("QueryPerf returned object with unexpected type '%s'"),
                              esxVI_Type_ToString(perfEntityMetric->value->_type));
2387
                }
2388

2389 2390 2391
                for (; perfMetricIntSeries != NULL;
                     perfMetricIntSeries = perfMetricIntSeries->_next) {
                    VIR_DEBUG0("perfMetricIntSeries ...");
2392

2393 2394 2395 2396 2397
                    for (value = perfMetricIntSeries->value;
                         value != NULL;
                         value = value->_next) {
                        VIR_DEBUG("value %lld", (long long int)value->value);
                    }
2398 2399 2400
                }
            }

2401 2402 2403
            querySpec->entity = NULL;
            querySpec->metricId->instance = NULL;
            querySpec->format = NULL;
2404

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

2407 2408 2409 2410 2411
            /*
             * FIXME: Cannot map between realtive used-cpu-time and absolute
             *        info->cpuTime
             */
        }
2412 2413
    }

M
Matthias Bolte 已提交
2414 2415
    result = 0;

2416 2417 2418 2419 2420 2421 2422
  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);
2423
    esxVI_PerfEntityMetricBase_Free(&perfEntityMetricBaseList);
2424 2425 2426 2427 2428 2429 2430

    return result;
}



static int
2431 2432
esxDomainSetVcpusFlags(virDomainPtr domain, unsigned int nvcpus,
                       unsigned int flags)
2433
{
M
Matthias Bolte 已提交
2434
    int result = -1;
M
Matthias Bolte 已提交
2435
    esxPrivate *priv = domain->conn->privateData;
M
Matthias Bolte 已提交
2436
    int maxVcpus;
2437 2438 2439 2440
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2441
    char *taskInfoErrorMessage = NULL;
2442

2443 2444 2445 2446 2447
    if (flags != VIR_DOMAIN_VCPU_LIVE) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
        return -1;
    }

2448
    if (nvcpus < 1) {
2449 2450
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Requested number of virtual CPUs must at least be 1"));
M
Matthias Bolte 已提交
2451
        return -1;
2452 2453
    }

2454
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2455
        return -1;
2456 2457
    }

M
Matthias Bolte 已提交
2458
    maxVcpus = esxDomainGetMaxVcpus(domain);
2459

M
Matthias Bolte 已提交
2460
    if (maxVcpus < 0) {
M
Matthias Bolte 已提交
2461
        return -1;
2462 2463
    }

M
Matthias Bolte 已提交
2464
    if (nvcpus > maxVcpus) {
2465
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2466 2467
                  _("Requested number of virtual CPUs is greater than max "
                    "allowable number of virtual CPUs for the domain: %d > %d"),
M
Matthias Bolte 已提交
2468
                  nvcpus, maxVcpus);
M
Matthias Bolte 已提交
2469
        return -1;
2470 2471
    }

2472
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2473
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2474
           priv->autoAnswer) < 0 ||
2475 2476
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Int_Alloc(&spec->numCPUs) < 0) {
M
Matthias Bolte 已提交
2477
        goto cleanup;
2478 2479 2480 2481
    }

    spec->numCPUs->value = nvcpus;

2482
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2483
                              &task) < 0 ||
2484
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2485
                                    esxVI_Occurrence_RequiredItem,
2486 2487
                                    priv->autoAnswer, &taskInfoState,
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2488
        goto cleanup;
2489 2490 2491
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2492
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2493 2494
                  _("Could not set number of virtual CPUs to %d: %s"), nvcpus,
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
2495
        goto cleanup;
2496 2497
    }

M
Matthias Bolte 已提交
2498 2499
    result = 0;

2500 2501 2502 2503
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2504
    VIR_FREE(taskInfoErrorMessage);
2505 2506 2507 2508 2509

    return result;
}


M
Matthias Bolte 已提交
2510

2511 2512 2513 2514 2515 2516
static int
esxDomainSetVcpus(virDomainPtr domain, unsigned int nvcpus)
{
    return esxDomainSetVcpusFlags(domain, nvcpus, VIR_DOMAIN_VCPU_LIVE);
}

2517

M
Matthias Bolte 已提交
2518

2519
static int
2520
esxDomainGetVcpusFlags(virDomainPtr domain, unsigned int flags)
2521
{
M
Matthias Bolte 已提交
2522
    esxPrivate *priv = domain->conn->privateData;
2523 2524 2525 2526
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

2527 2528 2529 2530 2531
    if (flags != (VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_MAXIMUM)) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
        return -1;
    }

M
Matthias Bolte 已提交
2532 2533
    if (priv->maxVcpus > 0) {
        return priv->maxVcpus;
2534 2535
    }

M
Matthias Bolte 已提交
2536 2537
    priv->maxVcpus = -1;

2538
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2539
        return -1;
2540 2541
    }

2542
    if (esxVI_String_AppendValueToList(&propertyNameList,
2543
                                       "capability.maxSupportedVcpus") < 0 ||
2544 2545
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
2546
        goto cleanup;
2547 2548 2549
    }

    if (hostSystem == NULL) {
2550 2551
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
2552
        goto cleanup;
2553 2554 2555 2556 2557
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "capability.maxSupportedVcpus")) {
2558
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2559
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2560
                goto cleanup;
2561 2562
            }

M
Matthias Bolte 已提交
2563
            priv->maxVcpus = dynamicProperty->val->int32;
2564 2565 2566 2567 2568 2569 2570 2571 2572 2573
            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

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

M
Matthias Bolte 已提交
2574
    return priv->maxVcpus;
2575 2576
}

M
Matthias Bolte 已提交
2577 2578


2579 2580 2581 2582 2583 2584
static int
esxDomainGetMaxVcpus(virDomainPtr domain)
{
    return esxDomainGetVcpusFlags(domain, (VIR_DOMAIN_VCPU_LIVE |
                                           VIR_DOMAIN_VCPU_MAXIMUM));
}
2585

M
Matthias Bolte 已提交
2586 2587


2588 2589 2590
static char *
esxDomainDumpXML(virDomainPtr domain, int flags)
{
M
Matthias Bolte 已提交
2591
    esxPrivate *priv = domain->conn->privateData;
2592 2593
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
2594 2595
    esxVI_VirtualMachinePowerState powerState;
    int id;
2596
    char *vmPathName = NULL;
2597
    char *datastoreName = NULL;
M
Matthias Bolte 已提交
2598
    char *directoryName = NULL;
2599
    char *directoryAndFileName = NULL;
2600
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
2601 2602
    char *url = NULL;
    char *vmx = NULL;
2603
    virVMXContext ctx;
2604
    esxVMX_Data data;
2605 2606 2607
    virDomainDefPtr def = NULL;
    char *xml = NULL;

2608
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2609
        return NULL;
2610 2611
    }

2612 2613 2614
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "config.files.vmPathName\0"
                                           "runtime.powerState\0") < 0 ||
2615
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2616
                                         propertyNameList, &virtualMachine,
2617
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2618 2619
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0 ||
2620 2621
        esxVI_GetStringValue(virtualMachine, "config.files.vmPathName",
                             &vmPathName, esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2622
        goto cleanup;
2623 2624
    }

2625
    if (esxUtil_ParseDatastorePath(vmPathName, &datastoreName, &directoryName,
2626
                                   &directoryAndFileName) < 0) {
M
Matthias Bolte 已提交
2627
        goto cleanup;
2628 2629
    }

2630 2631
    virBufferVSprintf(&buffer, "%s://%s:%d/folder/", priv->transport,
                      domain->conn->uri->server, domain->conn->uri->port);
2632
    virBufferURIEncodeString(&buffer, directoryAndFileName);
2633
    virBufferAddLit(&buffer, "?dcPath=");
2634
    virBufferURIEncodeString(&buffer, priv->primary->datacenter->name);
2635 2636 2637 2638
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
2639
        virReportOOMError();
M
Matthias Bolte 已提交
2640
        goto cleanup;
2641 2642
    }

2643 2644
    url = virBufferContentAndReset(&buffer);

2645
    if (esxVI_Context_DownloadFile(priv->primary, url, &vmx) < 0) {
M
Matthias Bolte 已提交
2646
        goto cleanup;
2647 2648
    }

2649
    data.ctx = priv->primary;
2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663

    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;
        }
    }
2664 2665 2666 2667 2668 2669

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

2670
    def = virVMXParseConfig(&ctx, priv->caps, vmx);
2671 2672

    if (def != NULL) {
2673 2674 2675 2676
        if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
            def->id = id;
        }

2677
        xml = virDomainDefFormat(def, flags);
2678 2679 2680
    }

  cleanup:
M
Matthias Bolte 已提交
2681 2682 2683 2684
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

2685 2686
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2687
    VIR_FREE(datastoreName);
M
Matthias Bolte 已提交
2688
    VIR_FREE(directoryName);
2689
    VIR_FREE(directoryAndFileName);
2690
    VIR_FREE(url);
2691
    VIR_FREE(data.datastorePathWithoutFileName);
2692
    VIR_FREE(vmx);
2693
    virDomainDefFree(def);
2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704

    return xml;
}



static char *
esxDomainXMLFromNative(virConnectPtr conn, const char *nativeFormat,
                       const char *nativeConfig,
                       unsigned int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2705
    esxPrivate *priv = conn->privateData;
2706
    virVMXContext ctx;
2707
    esxVMX_Data data;
2708 2709 2710 2711
    virDomainDefPtr def = NULL;
    char *xml = NULL;

    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2712
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2713
                  _("Unsupported config format '%s'"), nativeFormat);
2714
        return NULL;
2715 2716
    }

2717
    data.ctx = priv->primary;
2718
    data.datastorePathWithoutFileName = (char *)"[?] ?";
2719 2720 2721 2722 2723 2724

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

2725
    def = virVMXParseConfig(&ctx, priv->caps, nativeConfig);
2726 2727

    if (def != NULL) {
2728
        xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
2729 2730 2731 2732 2733 2734 2735 2736 2737
    }

    virDomainDefFree(def);

    return xml;
}



M
Matthias Bolte 已提交
2738 2739 2740 2741 2742
static char *
esxDomainXMLToNative(virConnectPtr conn, const char *nativeFormat,
                     const char *domainXml,
                     unsigned int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2743
    esxPrivate *priv = conn->privateData;
2744 2745
    int virtualHW_version;
    virVMXContext ctx;
2746
    esxVMX_Data data;
M
Matthias Bolte 已提交
2747 2748 2749 2750
    virDomainDefPtr def = NULL;
    char *vmx = NULL;

    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2751
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2752
                  _("Unsupported config format '%s'"), nativeFormat);
M
Matthias Bolte 已提交
2753 2754 2755
        return NULL;
    }

2756 2757 2758 2759 2760 2761 2762
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        return NULL;
    }

2763
    def = virDomainDefParseString(priv->caps, domainXml, 0);
M
Matthias Bolte 已提交
2764 2765 2766 2767 2768

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

2769
    data.ctx = priv->primary;
2770
    data.datastorePathWithoutFileName = NULL;
2771 2772 2773 2774 2775 2776

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

2777
    vmx = virVMXFormatConfig(&ctx, priv->caps, def, virtualHW_version);
M
Matthias Bolte 已提交
2778 2779 2780 2781 2782 2783 2784 2785

    virDomainDefFree(def);

    return vmx;
}



2786 2787 2788
static int
esxListDefinedDomains(virConnectPtr conn, char **const names, int maxnames)
{
M
Matthias Bolte 已提交
2789
    bool success = false;
M
Matthias Bolte 已提交
2790
    esxPrivate *priv = conn->privateData;
2791 2792 2793 2794 2795
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;
2796
    int i;
2797 2798

    if (names == NULL || maxnames < 0) {
2799 2800
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
2801 2802 2803 2804 2805 2806
    }

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

2807
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2808
        return -1;
2809 2810
    }

2811
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2812 2813
                                           "name\0"
                                           "runtime.powerState\0") < 0 ||
2814 2815
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2816
        goto cleanup;
2817 2818 2819 2820
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
2821
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
2822
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
2823
            goto cleanup;
2824 2825 2826 2827 2828 2829
        }

        if (powerState == esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

2830
        names[count] = NULL;
2831

2832 2833 2834
        if (esxVI_GetVirtualMachineIdentity(virtualMachine, NULL, &names[count],
                                            NULL) < 0) {
            goto cleanup;
2835 2836
        }

2837 2838
        ++count;

2839 2840 2841 2842 2843
        if (count >= maxnames) {
            break;
        }
    }

M
Matthias Bolte 已提交
2844
    success = true;
2845

M
Matthias Bolte 已提交
2846 2847 2848 2849 2850
  cleanup:
    if (! success) {
        for (i = 0; i < count; ++i) {
            VIR_FREE(names[i]);
        }
2851

M
Matthias Bolte 已提交
2852
        count = -1;
2853 2854
    }

M
Matthias Bolte 已提交
2855 2856
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
2857

M
Matthias Bolte 已提交
2858
    return count;
2859 2860 2861 2862 2863 2864 2865
}



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

2868
    if (esxVI_EnsureSession(priv->primary) < 0) {
2869 2870 2871
        return -1;
    }

2872
    return esxVI_LookupNumberOfDomainsByPowerState
2873
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn,
2874 2875 2876 2877 2878 2879
              esxVI_Boolean_True);
}



static int
2880
esxDomainCreateWithFlags(virDomainPtr domain, unsigned int flags)
2881
{
M
Matthias Bolte 已提交
2882
    int result = -1;
M
Matthias Bolte 已提交
2883
    esxPrivate *priv = domain->conn->privateData;
2884 2885 2886
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
2887
    int id = -1;
2888 2889
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2890
    char *taskInfoErrorMessage = NULL;
2891

2892 2893
    virCheckFlags(0, -1);

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

2898
    if (esxVI_String_AppendValueToList(&propertyNameList,
2899
                                       "runtime.powerState") < 0 ||
2900
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2901
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
2902
           priv->autoAnswer) < 0 ||
2903 2904
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0) {
M
Matthias Bolte 已提交
2905
        goto cleanup;
2906 2907 2908
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2909 2910
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered off"));
M
Matthias Bolte 已提交
2911
        goto cleanup;
2912 2913
    }

2914
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
2915
                             &task) < 0 ||
2916
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2917
                                    esxVI_Occurrence_RequiredItem,
2918 2919
                                    priv->autoAnswer, &taskInfoState,
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2920
        goto cleanup;
2921 2922 2923
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2924 2925
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not start domain: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
2926
        goto cleanup;
2927 2928
    }

2929
    domain->id = id;
M
Matthias Bolte 已提交
2930 2931
    result = 0;

2932 2933 2934 2935
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
2936
    VIR_FREE(taskInfoErrorMessage);
2937 2938 2939 2940

    return result;
}

2941 2942


2943 2944 2945 2946 2947
static int
esxDomainCreate(virDomainPtr domain)
{
    return esxDomainCreateWithFlags(domain, 0);
}
2948

2949 2950


M
Matthias Bolte 已提交
2951
static virDomainPtr
2952
esxDomainDefineXML(virConnectPtr conn, const char *xml)
M
Matthias Bolte 已提交
2953
{
M
Matthias Bolte 已提交
2954
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
2955 2956
    virDomainDefPtr def = NULL;
    char *vmx = NULL;
2957 2958
    int i;
    virDomainDiskDefPtr disk = NULL;
M
Matthias Bolte 已提交
2959
    esxVI_ObjectContent *virtualMachine = NULL;
2960 2961
    int virtualHW_version;
    virVMXContext ctx;
2962
    esxVMX_Data data;
M
Matthias Bolte 已提交
2963 2964
    char *datastoreName = NULL;
    char *directoryName = NULL;
2965
    char *escapedName = NULL;
M
Matthias Bolte 已提交
2966 2967 2968 2969 2970 2971 2972 2973
    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;
2974
    char *taskInfoErrorMessage = NULL;
M
Matthias Bolte 已提交
2975 2976
    virDomainPtr domain = NULL;

2977
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2978
        return NULL;
M
Matthias Bolte 已提交
2979 2980 2981
    }

    /* Parse domain XML */
2982
    def = virDomainDefParseString(priv->caps, xml,
M
Matthias Bolte 已提交
2983 2984 2985
                                  VIR_DOMAIN_XML_INACTIVE);

    if (def == NULL) {
M
Matthias Bolte 已提交
2986
        return NULL;
M
Matthias Bolte 已提交
2987 2988 2989
    }

    /* Check if an existing domain should be edited */
2990
    if (esxVI_LookupVirtualMachineByUuid(priv->primary, def->uuid, NULL,
M
Matthias Bolte 已提交
2991
                                         &virtualMachine,
M
Matthias Bolte 已提交
2992
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
2993
        goto cleanup;
M
Matthias Bolte 已提交
2994 2995
    }

2996 2997 2998 2999 3000 3001 3002
    if (virtualMachine == NULL &&
        esxVI_LookupVirtualMachineByName(priv->primary, def->name, NULL,
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
    }

M
Matthias Bolte 已提交
3003 3004
    if (virtualMachine != NULL) {
        /* FIXME */
3005 3006 3007
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Domain already exists, editing existing domains is not "
                    "supported yet"));
M
Matthias Bolte 已提交
3008
        goto cleanup;
M
Matthias Bolte 已提交
3009 3010 3011
    }

    /* Build VMX from domain XML */
3012 3013 3014 3015 3016 3017 3018
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        goto cleanup;
    }

3019
    data.ctx = priv->primary;
3020
    data.datastorePathWithoutFileName = NULL;
3021 3022 3023 3024 3025 3026

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

3027
    vmx = virVMXFormatConfig(&ctx, priv->caps, def, virtualHW_version);
M
Matthias Bolte 已提交
3028 3029

    if (vmx == NULL) {
M
Matthias Bolte 已提交
3030
        goto cleanup;
M
Matthias Bolte 已提交
3031 3032
    }

3033 3034 3035 3036 3037 3038 3039
    /*
     * 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 已提交
3040
    if (def->ndisks < 1) {
3041 3042 3043
        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 已提交
3044
        goto cleanup;
3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055
    }

    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) {
3056 3057 3058
        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 已提交
3059
        goto cleanup;
M
Matthias Bolte 已提交
3060 3061
    }

3062
    if (disk->src == NULL) {
3063 3064 3065
        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 已提交
3066
        goto cleanup;
M
Matthias Bolte 已提交
3067 3068
    }

3069
    if (esxUtil_ParseDatastorePath(disk->src, &datastoreName, &directoryName,
3070
                                   NULL) < 0) {
M
Matthias Bolte 已提交
3071
        goto cleanup;
M
Matthias Bolte 已提交
3072 3073
    }

3074
    if (! virFileHasSuffix(disk->src, ".vmdk")) {
3075
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3076 3077
                  _("Expecting source '%s' of first file-based harddisk to "
                    "be a VMDK image"), disk->src);
M
Matthias Bolte 已提交
3078
        goto cleanup;
M
Matthias Bolte 已提交
3079 3080 3081 3082 3083 3084 3085 3086 3087 3088
    }

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

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

3089 3090 3091 3092 3093 3094 3095
    escapedName = esxUtil_EscapeDatastoreItem(def->name);

    if (escapedName == NULL) {
        goto cleanup;
    }

    virBufferURIEncodeString(&buffer, escapedName);
M
Matthias Bolte 已提交
3096
    virBufferAddLit(&buffer, ".vmx?dcPath=");
3097
    virBufferURIEncodeString(&buffer, priv->primary->datacenter->name);
M
Matthias Bolte 已提交
3098 3099 3100 3101
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
3102
        virReportOOMError();
M
Matthias Bolte 已提交
3103
        goto cleanup;
M
Matthias Bolte 已提交
3104 3105 3106 3107
    }

    url = virBufferContentAndReset(&buffer);

3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118
    /* Check, if VMX file already exists */
    /* FIXME */

    /* Upload VMX file */
    VIR_DEBUG("Uploading .vmx config, url='%s' vmx='%s'", url, vmx);

    if (esxVI_Context_UploadFile(priv->primary, url, vmx) < 0) {
        goto cleanup;
    }

    /* Register the domain */
M
Matthias Bolte 已提交
3119 3120
    if (directoryName != NULL) {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s/%s.vmx", datastoreName,
3121
                        directoryName, escapedName) < 0) {
3122
            virReportOOMError();
M
Matthias Bolte 已提交
3123
            goto cleanup;
M
Matthias Bolte 已提交
3124 3125 3126
        }
    } else {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s.vmx", datastoreName,
3127
                        escapedName) < 0) {
3128
            virReportOOMError();
M
Matthias Bolte 已提交
3129
            goto cleanup;
M
Matthias Bolte 已提交
3130 3131 3132
        }
    }

3133
    if (esxVI_RegisterVM_Task(priv->primary, priv->primary->datacenter->vmFolder,
M
Matthias Bolte 已提交
3134
                              datastoreRelatedPath, NULL, esxVI_Boolean_False,
3135 3136 3137 3138
                              priv->primary->computeResource->resourcePool,
                              priv->primary->hostSystem->_reference,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, def->uuid,
3139
                                    esxVI_Occurrence_OptionalItem,
3140 3141
                                    priv->autoAnswer, &taskInfoState,
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3142
        goto cleanup;
M
Matthias Bolte 已提交
3143 3144 3145
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3146 3147
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not define domain: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
3148
        goto cleanup;
M
Matthias Bolte 已提交
3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159
    }

    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 已提交
3160 3161 3162 3163
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

M
Matthias Bolte 已提交
3164 3165 3166 3167
    virDomainDefFree(def);
    VIR_FREE(vmx);
    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
3168
    VIR_FREE(escapedName);
M
Matthias Bolte 已提交
3169 3170 3171 3172 3173 3174 3175
    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);
3176
    VIR_FREE(taskInfoErrorMessage);
M
Matthias Bolte 已提交
3177 3178 3179 3180 3181 3182

    return domain;
}



3183 3184 3185
static int
esxDomainUndefine(virDomainPtr domain)
{
M
Matthias Bolte 已提交
3186
    int result = -1;
M
Matthias Bolte 已提交
3187
    esxPrivate *priv = domain->conn->privateData;
3188
    esxVI_Context *ctx = NULL;
3189 3190 3191 3192
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

3193 3194 3195 3196 3197 3198
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

3199
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
3200
        return -1;
3201 3202
    }

3203
    if (esxVI_String_AppendValueToList(&propertyNameList,
3204
                                       "runtime.powerState") < 0 ||
3205 3206
        esxVI_LookupVirtualMachineByUuid(ctx, domain->uuid, propertyNameList,
                                         &virtualMachine,
M
Matthias Bolte 已提交
3207
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3208
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
3209
        goto cleanup;
3210 3211 3212 3213
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended &&
        powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
3214 3215
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not suspended or powered off"));
M
Matthias Bolte 已提交
3216
        goto cleanup;
3217 3218
    }

3219
    if (esxVI_UnregisterVM(ctx, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
3220
        goto cleanup;
3221 3222
    }

M
Matthias Bolte 已提交
3223 3224
    result = 0;

3225 3226 3227 3228 3229 3230 3231 3232 3233
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412
static int
esxDomainGetAutostart(virDomainPtr domain, int *autostart)
{
    int result = -1;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_AutoStartDefaults *defaults = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostAutoStartManager = NULL;
    esxVI_AutoStartPowerInfo *powerInfo = NULL;
    esxVI_AutoStartPowerInfo *powerInfoList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;

    *autostart = 0;

    if (esxVI_EnsureSession(priv->primary) < 0) {
        return -1;
    }

    /* Check general autostart config */
    if (esxVI_LookupAutoStartDefaults(priv->primary, &defaults) < 0) {
        goto cleanup;
    }

    if (defaults->enabled != esxVI_Boolean_True) {
        /* Autostart is disabled in general, exit early here */
        result = 0;
        goto cleanup;
    }

    /* Check specific autostart config */
    if (esxVI_LookupAutoStartPowerInfoList(priv->primary, &powerInfoList) < 0) {
        goto cleanup;
    }

    if (powerInfoList == NULL) {
        /* powerInfo list is empty, exit early here */
        result = 0;
        goto cleanup;
    }

    if (esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
                                         NULL, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    for (powerInfo = powerInfoList; powerInfo != NULL;
         powerInfo = powerInfo->_next) {
        if (STREQ(powerInfo->key->value, virtualMachine->obj->value)) {
            if (STRCASEEQ(powerInfo->startAction, "powerOn")) {
                *autostart = 1;
            }

            break;
        }
    }

    result = 0;

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostAutoStartManager);
    esxVI_AutoStartDefaults_Free(&defaults);
    esxVI_AutoStartPowerInfo_Free(&powerInfoList);
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
}



static int
esxDomainSetAutostart(virDomainPtr domain, int autostart)
{
    int result = -1;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_HostAutoStartManagerConfig *spec = NULL;
    esxVI_AutoStartDefaults *defaults = NULL;
    esxVI_AutoStartPowerInfo *powerInfoList = NULL;
    esxVI_AutoStartPowerInfo *powerInfo = NULL;
    esxVI_AutoStartPowerInfo *newPowerInfo = NULL;

    if (esxVI_EnsureSession(priv->primary) < 0) {
        return -1;
    }

    if (esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
                                         NULL, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_HostAutoStartManagerConfig_Alloc(&spec) < 0) {
        goto cleanup;
    }

    if (autostart) {
        /*
         * There is a general autostart option that affects the autostart
         * behavior of all domains. If it's disabled then no domain does
         * autostart. If it's enabled then the autostart behavior depends on
         * the per-domain autostart config.
         */
        if (esxVI_LookupAutoStartDefaults(priv->primary, &defaults) < 0) {
            goto cleanup;
        }

        if (defaults->enabled != esxVI_Boolean_True) {
            /*
             * Autostart is disabled in general. Check if no other domain is
             * in the list of autostarted domains, so it's safe to enable the
             * general autostart option without affecting the autostart
             * behavior of other domains.
             */
            if (esxVI_LookupAutoStartPowerInfoList(priv->primary,
                                                   &powerInfoList) < 0) {
                goto cleanup;
            }

            for (powerInfo = powerInfoList; powerInfo != NULL;
                 powerInfo = powerInfo->_next) {
                if (STRNEQ(powerInfo->key->value, virtualMachine->obj->value)) {
                    ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                              _("Cannot enable general autostart option "
                                "without affecting other domains"));
                    goto cleanup;
                }
            }

            /* Enable autostart in general */
            if (esxVI_AutoStartDefaults_Alloc(&spec->defaults) < 0) {
                goto cleanup;
            }

            spec->defaults->enabled = esxVI_Boolean_True;
        }
    }

    if (esxVI_AutoStartPowerInfo_Alloc(&newPowerInfo) < 0 ||
        esxVI_Int_Alloc(&newPowerInfo->startOrder) < 0 ||
        esxVI_Int_Alloc(&newPowerInfo->startDelay) < 0 ||
        esxVI_Int_Alloc(&newPowerInfo->stopDelay) < 0 ||
        esxVI_AutoStartPowerInfo_AppendToList(&spec->powerInfo,
                                              newPowerInfo) < 0) {
        goto cleanup;
    }

    newPowerInfo->key = virtualMachine->obj;
    newPowerInfo->startOrder->value = -1; /* no specific start order */
    newPowerInfo->startDelay->value = -1; /* use system default */
    newPowerInfo->waitForHeartbeat = esxVI_AutoStartWaitHeartbeatSetting_SystemDefault;
    newPowerInfo->startAction = autostart ? (char *)"powerOn" : (char *)"none";
    newPowerInfo->stopDelay->value = -1; /* use system default */
    newPowerInfo->stopAction = (char *)"none";

    if (esxVI_ReconfigureAutostart
          (priv->primary,
           priv->primary->hostSystem->configManager->autoStartManager,
           spec) < 0) {
        goto cleanup;
    }

    result = 0;

  cleanup:
    if (newPowerInfo != NULL) {
        newPowerInfo->key = NULL;
        newPowerInfo->startAction = NULL;
        newPowerInfo->stopAction = NULL;
    }

    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_HostAutoStartManagerConfig_Free(&spec);
    esxVI_AutoStartDefaults_Free(&defaults);
    esxVI_AutoStartPowerInfo_Free(&powerInfoList);

    return result;
}



3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424
/*
 * 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)
 *
3425
 *   The amount of CPU resource that is guaranteed to be available to the domain.
3426 3427 3428 3429
 *
 *
 * - limit (VIR_DOMAIN_SCHED_FIELD_LLONG >= 0, or -1, in megaherz)
 *
3430 3431
 *   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
3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442
 *   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'.
 */
3443
static char *
3444
esxDomainGetSchedulerType(virDomainPtr domain ATTRIBUTE_UNUSED, int *nparams)
3445 3446 3447 3448
{
    char *type = strdup("allocation");

    if (type == NULL) {
3449
        virReportOOMError();
3450
        return NULL;
3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463
    }

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

    return type;
}



static int
esxDomainGetSchedulerParameters(virDomainPtr domain,
                                virSchedParameterPtr params, int *nparams)
{
M
Matthias Bolte 已提交
3464
    int result = -1;
M
Matthias Bolte 已提交
3465
    esxPrivate *priv = domain->conn->privateData;
3466 3467 3468 3469 3470 3471 3472 3473
    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) {
3474 3475
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Parameter array must have space for 3 items"));
M
Matthias Bolte 已提交
3476
        return -1;
3477 3478
    }

3479
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3480
        return -1;
3481 3482
    }

3483
    if (esxVI_String_AppendValueListToList(&propertyNameList,
3484 3485 3486
                                           "config.cpuAllocation.reservation\0"
                                           "config.cpuAllocation.limit\0"
                                           "config.cpuAllocation.shares\0") < 0 ||
3487
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
3488
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3489
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3490
        goto cleanup;
3491 3492 3493 3494 3495 3496
    }

    for (dynamicProperty = virtualMachine->propSet;
         dynamicProperty != NULL && mask != 7 && i < 3;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.cpuAllocation.reservation") &&
M
Matthias Bolte 已提交
3497
            ! (mask & (1 << 0))) {
3498 3499 3500 3501 3502
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "reservation");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_LLONG;

3503
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3504
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3505
                goto cleanup;
3506 3507 3508 3509 3510 3511 3512
            }

            params[i].value.l = dynamicProperty->val->int64;
            mask |= 1 << 0;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.limit") &&
M
Matthias Bolte 已提交
3513
                   ! (mask & (1 << 1))) {
3514 3515 3516 3517 3518
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "limit");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_LLONG;

3519
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3520
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3521
                goto cleanup;
3522 3523 3524 3525 3526 3527 3528
            }

            params[i].value.l = dynamicProperty->val->int64;
            mask |= 1 << 1;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.shares") &&
M
Matthias Bolte 已提交
3529
                   ! (mask & (1 << 2))) {
3530 3531 3532 3533 3534
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "shares");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_INT;

3535
            if (esxVI_SharesInfo_CastFromAnyType(dynamicProperty->val,
3536
                                                 &sharesInfo) < 0) {
M
Matthias Bolte 已提交
3537
                goto cleanup;
3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557
            }

            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:
3558
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3559
                          _("Shares level has unknown value %d"),
3560
                          (int)sharesInfo->level);
M
Matthias Bolte 已提交
3561
                goto cleanup;
3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573
            }

            esxVI_SharesInfo_Free(&sharesInfo);

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

    *nparams = i;
M
Matthias Bolte 已提交
3574
    result = 0;
3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588

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

    return result;
}



static int
esxDomainSetSchedulerParameters(virDomainPtr domain,
                                virSchedParameterPtr params, int nparams)
{
M
Matthias Bolte 已提交
3589
    int result = -1;
M
Matthias Bolte 已提交
3590
    esxPrivate *priv = domain->conn->privateData;
3591 3592 3593 3594 3595
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3596
    char *taskInfoErrorMessage = NULL;
3597 3598
    int i;

3599
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3600
        return -1;
3601 3602
    }

3603
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3604
          (priv->primary, domain->uuid, NULL, &virtualMachine,
3605
           priv->autoAnswer) < 0 ||
3606 3607
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->cpuAllocation) < 0) {
M
Matthias Bolte 已提交
3608
        goto cleanup;
3609 3610 3611 3612 3613
    }

    for (i = 0; i < nparams; ++i) {
        if (STREQ (params[i].field, "reservation") &&
            params[i].type == VIR_DOMAIN_SCHED_FIELD_LLONG) {
3614
            if (esxVI_Long_Alloc(&spec->cpuAllocation->reservation) < 0) {
M
Matthias Bolte 已提交
3615
                goto cleanup;
3616 3617 3618
            }

            if (params[i].value.l < 0) {
3619
                ESX_ERROR(VIR_ERR_INVALID_ARG,
3620 3621
                          _("Could not set reservation to %lld MHz, expecting "
                            "positive value"), params[i].value.l);
M
Matthias Bolte 已提交
3622
                goto cleanup;
3623 3624 3625 3626 3627
            }

            spec->cpuAllocation->reservation->value = params[i].value.l;
        } else if (STREQ (params[i].field, "limit") &&
                   params[i].type == VIR_DOMAIN_SCHED_FIELD_LLONG) {
3628
            if (esxVI_Long_Alloc(&spec->cpuAllocation->limit) < 0) {
M
Matthias Bolte 已提交
3629
                goto cleanup;
3630 3631 3632
            }

            if (params[i].value.l < -1) {
3633
                ESX_ERROR(VIR_ERR_INVALID_ARG,
3634 3635
                          _("Could not set limit to %lld MHz, expecting "
                            "positive value or -1 (unlimited)"),
3636
                          params[i].value.l);
M
Matthias Bolte 已提交
3637
                goto cleanup;
3638 3639 3640 3641
            }

            spec->cpuAllocation->limit->value = params[i].value.l;
        } else if (STREQ (params[i].field, "shares") &&
3642
                   params[i].type == VIR_DOMAIN_SCHED_FIELD_INT) {
3643 3644
            if (esxVI_SharesInfo_Alloc(&sharesInfo) < 0 ||
                esxVI_Int_Alloc(&sharesInfo->shares) < 0) {
M
Matthias Bolte 已提交
3645
                goto cleanup;
3646 3647 3648 3649
            }

            spec->cpuAllocation->shares = sharesInfo;

3650
            if (params[i].value.i >= 0) {
3651
                spec->cpuAllocation->shares->level = esxVI_SharesLevel_Custom;
3652
                spec->cpuAllocation->shares->shares->value = params[i].value.i;
3653
            } else {
3654
                switch (params[i].value.i) {
3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672
                  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:
3673
                    ESX_ERROR(VIR_ERR_INVALID_ARG,
3674 3675
                              _("Could not set shares to %d, expecting positive "
                                "value or -1 (low), -2 (normal) or -3 (high)"),
3676
                              params[i].value.i);
M
Matthias Bolte 已提交
3677
                    goto cleanup;
3678 3679 3680
                }
            }
        } else {
3681
            ESX_ERROR(VIR_ERR_INVALID_ARG, _("Unknown field '%s'"),
3682
                      params[i].field);
M
Matthias Bolte 已提交
3683
            goto cleanup;
3684 3685 3686
        }
    }

3687
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
3688
                              &task) < 0 ||
3689
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3690
                                    esxVI_Occurrence_RequiredItem,
3691 3692
                                    priv->autoAnswer, &taskInfoState,
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3693
        goto cleanup;
3694 3695 3696
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3697 3698 3699
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not change scheduler parameters: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
3700
        goto cleanup;
3701 3702
    }

M
Matthias Bolte 已提交
3703 3704
    result = 0;

3705 3706 3707 3708
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
3709
    VIR_FREE(taskInfoErrorMessage);
3710 3711 3712 3713 3714 3715 3716 3717 3718 3719

    return result;
}



static int
esxDomainMigratePrepare(virConnectPtr dconn,
                        char **cookie ATTRIBUTE_UNUSED,
                        int *cookielen ATTRIBUTE_UNUSED,
3720 3721
                        const char *uri_in ATTRIBUTE_UNUSED,
                        char **uri_out,
3722 3723 3724 3725
                        unsigned long flags ATTRIBUTE_UNUSED,
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
3726
    esxPrivate *priv = dconn->privateData;
3727 3728

    if (uri_in == NULL) {
3729 3730 3731 3732
        if (virAsprintf(uri_out, "vpxmigr://%s/%s/%s",
                        priv->vCenter->ipAddress,
                        priv->vCenter->computeResource->resourcePool->value,
                        priv->vCenter->hostSystem->_reference->value) < 0) {
3733
            virReportOOMError();
3734
            return -1;
3735 3736 3737
        }
    }

3738
    return 0;
3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751
}



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 已提交
3752
    int result = -1;
M
Matthias Bolte 已提交
3753
    esxPrivate *priv = domain->conn->privateData;
3754 3755 3756 3757
    xmlURIPtr parsedUri = NULL;
    char *saveptr;
    char *path_resourcePool;
    char *path_hostSystem;
3758
    esxVI_ObjectContent *virtualMachine = NULL;
3759 3760
    esxVI_ManagedObjectReference resourcePool;
    esxVI_ManagedObjectReference hostSystem;
3761 3762 3763
    esxVI_Event *eventList = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3764
    char *taskInfoErrorMessage = NULL;
3765

M
Matthias Bolte 已提交
3766
    if (priv->vCenter == NULL) {
3767 3768
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Migration not possible without a vCenter"));
M
Matthias Bolte 已提交
3769
        return -1;
3770 3771 3772
    }

    if (dname != NULL) {
3773 3774
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Renaming domains on migration not supported"));
M
Matthias Bolte 已提交
3775
        return -1;
3776 3777
    }

3778
    if (esxVI_EnsureSession(priv->vCenter) < 0) {
M
Matthias Bolte 已提交
3779
        return -1;
3780 3781
    }

3782 3783
    /* Parse migration URI */
    parsedUri = xmlParseURI(uri);
3784

3785
    if (parsedUri == NULL) {
3786
        virReportOOMError();
M
Matthias Bolte 已提交
3787
        return -1;
3788 3789
    }

3790 3791 3792
    if (parsedUri->scheme == NULL || STRCASENEQ(parsedUri->scheme, "vpxmigr")) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Only vpxmigr:// migration URIs are supported"));
M
Matthias Bolte 已提交
3793
        goto cleanup;
3794 3795
    }

3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808
    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 已提交
3809
        goto cleanup;
3810 3811
    }

3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825
    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 已提交
3826
        goto cleanup;
3827 3828 3829
    }

    /* Validate the purposed migration */
3830
    if (esxVI_ValidateMigration(priv->vCenter, virtualMachine->obj,
3831 3832
                                esxVI_VirtualMachinePowerState_Undefined, NULL,
                                &resourcePool, &hostSystem, &eventList) < 0) {
M
Matthias Bolte 已提交
3833
        goto cleanup;
3834 3835 3836 3837 3838 3839 3840 3841
    }

    if (eventList != NULL) {
        /*
         * FIXME: Need to report the complete list of events. Limit reporting
         *        to the first event for now.
         */
        if (eventList->fullFormattedMessage != NULL) {
3842
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3843 3844
                      _("Could not migrate domain, validation reported a "
                        "problem: %s"), eventList->fullFormattedMessage);
3845
        } else {
3846 3847 3848
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                      _("Could not migrate domain, validation reported a "
                        "problem"));
3849 3850
        }

M
Matthias Bolte 已提交
3851
        goto cleanup;
3852 3853 3854
    }

    /* Perform the purposed migration */
3855 3856
    if (esxVI_MigrateVM_Task(priv->vCenter, virtualMachine->obj,
                             &resourcePool, &hostSystem,
3857 3858 3859
                             esxVI_VirtualMachineMovePriority_DefaultPriority,
                             esxVI_VirtualMachinePowerState_Undefined,
                             &task) < 0 ||
3860
        esxVI_WaitForTaskCompletion(priv->vCenter, task, domain->uuid,
3861
                                    esxVI_Occurrence_RequiredItem,
3862 3863
                                    priv->autoAnswer, &taskInfoState,
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3864
        goto cleanup;
3865 3866 3867
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3868
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3869
                  _("Could not migrate domain, migration task finished with "
3870 3871
                    "an error: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
3872
        goto cleanup;
3873 3874
    }

M
Matthias Bolte 已提交
3875 3876
    result = 0;

3877
  cleanup:
3878
    xmlFreeURI(parsedUri);
3879 3880 3881
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Event_Free(&eventList);
    esxVI_ManagedObjectReference_Free(&task);
3882
    VIR_FREE(taskInfoErrorMessage);
3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900

    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 已提交
3901 3902 3903 3904
static unsigned long long
esxNodeGetFreeMemory(virConnectPtr conn)
{
    unsigned long long result = 0;
M
Matthias Bolte 已提交
3905
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
3906 3907 3908 3909 3910
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *resourcePool = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ResourcePoolResourceUsage *resourcePoolResourceUsage = NULL;

3911
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3912
        return 0;
M
Matthias Bolte 已提交
3913 3914 3915
    }

    /* Get memory usage of resource pool */
3916
    if (esxVI_String_AppendValueToList(&propertyNameList,
M
Matthias Bolte 已提交
3917
                                       "runtime.memory") < 0 ||
3918 3919
        esxVI_LookupObjectContentByType(priv->primary,
                                        priv->primary->computeResource->resourcePool,
3920
                                        "ResourcePool", propertyNameList,
3921 3922
                                        &resourcePool,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3923
        goto cleanup;
M
Matthias Bolte 已提交
3924 3925 3926 3927 3928 3929
    }

    for (dynamicProperty = resourcePool->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.memory")) {
            if (esxVI_ResourcePoolResourceUsage_CastFromAnyType
3930
                  (dynamicProperty->val, &resourcePoolResourceUsage) < 0) {
M
Matthias Bolte 已提交
3931
                goto cleanup;
M
Matthias Bolte 已提交
3932 3933 3934 3935 3936 3937 3938 3939 3940
            }

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

    if (resourcePoolResourceUsage == NULL) {
3941 3942
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve memory usage of resource pool"));
M
Matthias Bolte 已提交
3943
        goto cleanup;
M
Matthias Bolte 已提交
3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957
    }

    result = resourcePoolResourceUsage->unreservedForVm->value;

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

    return result;
}



3958 3959 3960
static int
esxIsEncrypted(virConnectPtr conn)
{
M
Matthias Bolte 已提交
3961
    esxPrivate *priv = conn->privateData;
3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974

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



static int
esxIsSecure(virConnectPtr conn)
{
M
Matthias Bolte 已提交
3975
    esxPrivate *priv = conn->privateData;
3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988

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



static int
esxDomainIsActive(virDomainPtr domain)
{
M
Matthias Bolte 已提交
3989
    int result = -1;
M
Matthias Bolte 已提交
3990
    esxPrivate *priv = domain->conn->privateData;
3991 3992 3993 3994
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

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

3999
    if (esxVI_String_AppendValueToList(&propertyNameList,
4000
                                       "runtime.powerState") < 0 ||
4001
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
4002
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
4003
                                         esxVI_Occurrence_RequiredItem) < 0 ||
4004
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
4005
        goto cleanup;
4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029
    }

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

M
Matthias Bolte 已提交
4030 4031


4032 4033 4034 4035 4036
static int
esxDomainIsUpdated(virDomainPtr domain ATTRIBUTE_UNUSED)
{
    return 0;
}
4037

M
Matthias Bolte 已提交
4038 4039


4040 4041
static virDomainSnapshotPtr
esxDomainSnapshotCreateXML(virDomainPtr domain, const char *xmlDesc,
4042
                           unsigned int flags)
4043 4044 4045 4046 4047 4048 4049 4050 4051
{
    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;
4052
    char *taskInfoErrorMessage = NULL;
4053 4054
    virDomainSnapshotPtr snapshot = NULL;

4055 4056
    virCheckFlags(0, NULL);

4057
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4058
        return NULL;
4059 4060 4061 4062 4063
    }

    def = virDomainSnapshotDefParseString(xmlDesc, 1);

    if (def == NULL) {
M
Matthias Bolte 已提交
4064
        return NULL;
4065 4066 4067
    }

    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
4068
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4069
           priv->autoAnswer) < 0 ||
4070
        esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4071 4072 4073 4074
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, def->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4075
        goto cleanup;
4076 4077 4078 4079 4080
    }

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

4084
    if (esxVI_CreateSnapshot_Task(priv->primary, virtualMachine->obj,
4085 4086 4087
                                  def->name, def->description,
                                  esxVI_Boolean_True,
                                  esxVI_Boolean_False, &task) < 0 ||
4088
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
4089
                                    esxVI_Occurrence_RequiredItem,
4090 4091
                                    priv->autoAnswer, &taskInfoState,
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4092
        goto cleanup;
4093 4094 4095
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4096 4097
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not create snapshot: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
4098
        goto cleanup;
4099 4100 4101 4102 4103 4104 4105 4106 4107
    }

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

  cleanup:
    virDomainSnapshotDefFree(def);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4108
    VIR_FREE(taskInfoErrorMessage);
4109 4110 4111 4112 4113 4114 4115 4116

    return snapshot;
}



static char *
esxDomainSnapshotDumpXML(virDomainSnapshotPtr snapshot,
4117
                         unsigned int flags)
4118 4119 4120 4121 4122 4123 4124 4125 4126
{
    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;

4127 4128
    virCheckFlags(0, NULL);

M
Matthias Bolte 已提交
4129
    memset(&def, 0, sizeof (def));
4130

4131
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4132
        return NULL;
4133 4134
    }

4135
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4136 4137 4138 4139
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4140
        goto cleanup;
4141 4142 4143 4144 4145 4146 4147 4148
    }

    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 已提交
4149
        goto cleanup;
4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167
    }

    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
4168
esxDomainSnapshotNum(virDomainPtr domain, unsigned int flags)
4169
{
M
Matthias Bolte 已提交
4170
    int count;
4171 4172 4173
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;

4174 4175
    virCheckFlags(0, -1);

4176
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4177
        return -1;
4178 4179
    }

4180
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4181
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4182
        return -1;
4183 4184
    }

M
Matthias Bolte 已提交
4185
    count = esxVI_GetNumberOfSnapshotTrees(rootSnapshotTreeList);
4186 4187 4188

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

M
Matthias Bolte 已提交
4189
    return count;
4190 4191 4192 4193 4194 4195
}



static int
esxDomainSnapshotListNames(virDomainPtr domain, char **names, int nameslen,
4196
                           unsigned int flags)
4197
{
M
Matthias Bolte 已提交
4198
    int result;
4199 4200 4201
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;

4202 4203
    virCheckFlags(0, -1);

4204 4205 4206 4207 4208 4209 4210 4211 4212
    if (names == NULL || nameslen < 0) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
    }

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

4213
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4214
        return -1;
4215 4216
    }

4217
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4218
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4219
        return -1;
4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232
    }

    result = esxVI_GetSnapshotTreeNames(rootSnapshotTreeList, names, nameslen);

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



static virDomainSnapshotPtr
esxDomainSnapshotLookupByName(virDomainPtr domain, const char *name,
4233
                              unsigned int flags)
4234 4235 4236 4237 4238 4239 4240
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    virDomainSnapshotPtr snapshot = NULL;

4241 4242
    virCheckFlags(0, NULL);

4243
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4244
        return NULL;
4245 4246
    }

4247
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270
                                         &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;

4271
    virCheckFlags(0, -1);
4272

4273
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4274
        return -1;
4275 4276
    }

4277
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4278 4279
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4280
        return -1;
4281 4282 4283
    }

    if (currentSnapshotTree != NULL) {
M
Matthias Bolte 已提交
4284 4285
        esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);
        return 1;
4286 4287
    }

M
Matthias Bolte 已提交
4288
    return 0;
4289 4290 4291 4292 4293 4294 4295 4296 4297
}



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

4300
    virCheckFlags(0, NULL);
4301

4302
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4303
        return NULL;
4304 4305
    }

4306
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4307 4308
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4309
        return NULL;
4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323
    }

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

    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return snapshot;
}



static int
esxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4324
    int result = -1;
4325 4326 4327 4328 4329 4330
    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;
4331
    char *taskInfoErrorMessage = NULL;
4332

4333
    virCheckFlags(0, -1);
4334

4335
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4336
        return -1;
4337 4338
    }

4339
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4340 4341 4342 4343
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4344
        goto cleanup;
4345 4346
    }

4347
    if (esxVI_RevertToSnapshot_Task(priv->primary, snapshotTree->snapshot, NULL,
4348
                                    &task) < 0 ||
4349
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4350
                                    esxVI_Occurrence_RequiredItem,
4351 4352
                                    priv->autoAnswer, &taskInfoState,
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4353
        goto cleanup;
4354 4355 4356 4357
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
4358 4359
                  _("Could not revert to snapshot '%s': %s"), snapshot->name,
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
4360
        goto cleanup;
4361 4362
    }

M
Matthias Bolte 已提交
4363 4364
    result = 0;

4365 4366 4367
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4368
    VIR_FREE(taskInfoErrorMessage);
4369 4370 4371 4372 4373 4374 4375 4376 4377

    return result;
}



static int
esxDomainSnapshotDelete(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4378
    int result = -1;
4379 4380 4381 4382 4383 4384 4385
    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;
4386
    char *taskInfoErrorMessage = NULL;
4387

4388 4389
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN, -1);

4390
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4391
        return -1;
4392 4393 4394 4395 4396 4397
    }

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

4398
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4399 4400 4401 4402
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4403
        goto cleanup;
4404 4405
    }

4406
    if (esxVI_RemoveSnapshot_Task(priv->primary, snapshotTree->snapshot,
4407
                                  removeChildren, &task) < 0 ||
4408
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4409
                                    esxVI_Occurrence_RequiredItem,
4410 4411
                                    priv->autoAnswer, &taskInfoState,
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4412
        goto cleanup;
4413 4414 4415 4416
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
4417 4418
                  _("Could not delete snapshot '%s': %s"), snapshot->name,
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
4419
        goto cleanup;
4420 4421
    }

M
Matthias Bolte 已提交
4422 4423
    result = 0;

4424 4425 4426
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4427
    VIR_FREE(taskInfoErrorMessage);
4428 4429 4430 4431 4432 4433

    return result;
}



4434 4435 4436 4437 4438 4439 4440 4441 4442 4443
static int
esxDomainSetMemoryParameters(virDomainPtr domain, virMemoryParameterPtr params,
                             int nparams, unsigned int flags)
{
    int result = -1;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
4444
    char *taskInfoErrorMessage = NULL;
4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468
    int i;

    virCheckFlags(0, -1);

    if (esxVI_EnsureSession(priv->primary) < 0) {
        return -1;
    }

    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, NULL, &virtualMachine,
           priv->autoAnswer) < 0 ||
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0) {
        goto cleanup;
    }

    for (i = 0; i < nparams; ++i) {
        if (STREQ (params[i].field, VIR_DOMAIN_MEMORY_MIN_GUARANTEE) &&
            params[i].type == VIR_DOMAIN_SCHED_FIELD_ULLONG) {
            if (esxVI_Long_Alloc(&spec->memoryAllocation->reservation) < 0) {
                goto cleanup;
            }

            spec->memoryAllocation->reservation->value =
4469
              VIR_DIV_UP(params[i].value.ul, 1024); /* Scale from kilobytes to megabytes */
4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480
        } else {
            ESX_ERROR(VIR_ERR_INVALID_ARG, _("Unknown field '%s'"),
                      params[i].field);
            goto cleanup;
        }
    }

    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
4481 4482
                                    priv->autoAnswer, &taskInfoState,
                                    &taskInfoErrorMessage) < 0) {
4483 4484 4485 4486
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4487 4488 4489
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not change memory parameters: %s"),
                  taskInfoErrorMessage);
4490 4491 4492 4493 4494 4495 4496 4497 4498
        goto cleanup;
    }

    result = 0;

  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
4499
    VIR_FREE(taskInfoErrorMessage);
4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566

    return result;
}



static int
esxDomainGetMemoryParameters(virDomainPtr domain, virMemoryParameterPtr params,
                             int *nparams, unsigned int flags)
{
    int result = -1;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_Long *reservation = NULL;

    virCheckFlags(0, -1);

    if (*nparams == 0) {
        *nparams = 1; /* min_guarantee */
        return 0;
    }

    if (*nparams < 1) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Parameter array must have space for 1 item"));
        return -1;
    }

    if (esxVI_EnsureSession(priv->primary) < 0) {
        return -1;
    }

    if (esxVI_String_AppendValueToList
          (&propertyNameList, "config.memoryAllocation.reservation") < 0 ||
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
                                         propertyNameList, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_GetLong(virtualMachine, "config.memoryAllocation.reservation",
                      &reservation, esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    if (virStrcpyStatic(params[0].field,
                        VIR_DOMAIN_MEMORY_MIN_GUARANTEE) == NULL) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Field %s too big for destination"),
                  VIR_DOMAIN_MEMORY_MIN_GUARANTEE);
        goto cleanup;
    }

    params[0].type = VIR_DOMAIN_SCHED_FIELD_ULLONG;
    params[0].value.ul = reservation->value * 1024; /* Scale from megabytes to kilobytes */

    *nparams = 1;
    result = 0;

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

    return result;
}



4567 4568 4569 4570 4571 4572 4573 4574
static virDriver esxDriver = {
    VIR_DRV_ESX,
    "ESX",
    esxOpen,                         /* open */
    esxClose,                        /* close */
    esxSupportsFeature,              /* supports_feature */
    esxGetType,                      /* type */
    esxGetVersion,                   /* version */
4575
    NULL,                            /* libvirtVersion (impl. in libvirt.c) */
4576
    esxGetHostname,                  /* hostname */
E
Eric Blake 已提交
4577
    NULL,                            /* getSysinfo */
4578 4579
    NULL,                            /* getMaxVcpus */
    esxNodeGetInfo,                  /* nodeGetInfo */
4580
    esxGetCapabilities,              /* getCapabilities */
4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595
    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 */
4596
    NULL,                            /* domainSetMemoryFlags */
4597 4598 4599 4600
    esxDomainSetMemoryParameters,    /* domainSetMemoryParameters */
    esxDomainGetMemoryParameters,    /* domainGetMemoryParameters */
    NULL,                            /* domainSetBlkioParameters */
    NULL,                            /* domainGetBlkioParameters */
4601 4602 4603 4604 4605
    esxDomainGetInfo,                /* domainGetInfo */
    NULL,                            /* domainSave */
    NULL,                            /* domainRestore */
    NULL,                            /* domainCoreDump */
    esxDomainSetVcpus,               /* domainSetVcpus */
4606 4607
    esxDomainSetVcpusFlags,          /* domainSetVcpusFlags */
    esxDomainGetVcpusFlags,          /* domainGetVcpusFlags */
4608 4609 4610 4611 4612 4613
    NULL,                            /* domainPinVcpu */
    NULL,                            /* domainGetVcpus */
    esxDomainGetMaxVcpus,            /* domainGetMaxVcpus */
    NULL,                            /* domainGetSecurityLabel */
    NULL,                            /* nodeGetSecurityModel */
    esxDomainDumpXML,                /* domainDumpXML */
4614
    esxDomainXMLFromNative,          /* domainXMLFromNative */
M
Matthias Bolte 已提交
4615
    esxDomainXMLToNative,            /* domainXMLToNative */
4616 4617 4618
    esxListDefinedDomains,           /* listDefinedDomains */
    esxNumberOfDefinedDomains,       /* numOfDefinedDomains */
    esxDomainCreate,                 /* domainCreate */
4619
    esxDomainCreateWithFlags,        /* domainCreateWithFlags */
M
Matthias Bolte 已提交
4620
    esxDomainDefineXML,              /* domainDefineXML */
4621
    esxDomainUndefine,               /* domainUndefine */
4622
    NULL,                            /* domainAttachDevice */
4623
    NULL,                            /* domainAttachDeviceFlags */
4624
    NULL,                            /* domainDetachDevice */
4625
    NULL,                            /* domainDetachDeviceFlags */
4626
    NULL,                            /* domainUpdateDeviceFlags */
4627 4628
    esxDomainGetAutostart,           /* domainGetAutostart */
    esxDomainSetAutostart,           /* domainSetAutostart */
4629 4630 4631 4632 4633 4634 4635 4636
    esxDomainGetSchedulerType,       /* domainGetSchedulerType */
    esxDomainGetSchedulerParameters, /* domainGetSchedulerParameters */
    esxDomainSetSchedulerParameters, /* domainSetSchedulerParameters */
    esxDomainMigratePrepare,         /* domainMigratePrepare */
    esxDomainMigratePerform,         /* domainMigratePerform */
    esxDomainMigrateFinish,          /* domainMigrateFinish */
    NULL,                            /* domainBlockStats */
    NULL,                            /* domainInterfaceStats */
4637
    NULL,                            /* domainMemoryStats */
4638 4639
    NULL,                            /* domainBlockPeek */
    NULL,                            /* domainMemoryPeek */
4640
    NULL,                            /* domainGetBlockInfo */
4641
    NULL,                            /* nodeGetCellsFreeMemory */
M
Matthias Bolte 已提交
4642
    esxNodeGetFreeMemory,            /* nodeGetFreeMemory */
4643 4644 4645 4646 4647 4648 4649
    NULL,                            /* domainEventRegister */
    NULL,                            /* domainEventDeregister */
    NULL,                            /* domainMigratePrepare2 */
    NULL,                            /* domainMigrateFinish2 */
    NULL,                            /* nodeDeviceDettach */
    NULL,                            /* nodeDeviceReAttach */
    NULL,                            /* nodeDeviceReset */
C
Chris Lalancette 已提交
4650
    NULL,                            /* domainMigratePrepareTunnel */
4651 4652 4653 4654
    esxIsEncrypted,                  /* isEncrypted */
    esxIsSecure,                     /* isSecure */
    esxDomainIsActive,               /* domainIsActive */
    esxDomainIsPersistent,           /* domainIsPersistent */
4655
    esxDomainIsUpdated,              /* domainIsUpdated */
J
Jiri Denemark 已提交
4656
    NULL,                            /* cpuCompare */
4657
    NULL,                            /* cpuBaseline */
4658 4659 4660
    NULL,                            /* domainGetJobInfo */
    NULL,                            /* domainAbortJob */
    NULL,                            /* domainMigrateSetMaxDowntime */
4661
    NULL,                            /* domainMigrateSetMaxSpeed */
4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675
    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 已提交
4676
    NULL,                            /* qemuDomainMonitorCommand */
4677
    NULL,                            /* domainOpenConsole */
4678 4679 4680 4681 4682 4683 4684
};



int
esxRegister(void)
{
4685 4686 4687 4688 4689
    if (virRegisterDriver(&esxDriver) < 0 ||
        esxInterfaceRegister() < 0 ||
        esxNetworkRegister() < 0 ||
        esxStorageRegister() < 0 ||
        esxDeviceRegister() < 0 ||
M
Matthias Bolte 已提交
4690 4691
        esxSecretRegister() < 0 ||
        esxNWFilterRegister() < 0) {
4692 4693
        return -1;
    }
4694 4695 4696

    return 0;
}