esx_driver.c 148.1 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-2011 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
static void
esxFreePrivate(esxPrivate **priv)
{
    if (priv == NULL || *priv == NULL) {
        return;
    }

    esxVI_Context_Free(&(*priv)->host);
    esxVI_Context_Free(&(*priv)->vCenter);
    esxUtil_FreeParsedUri(&(*priv)->parsedUri);
    virCapabilitiesFree((*priv)->caps);
    VIR_FREE(*priv);
}



76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
/*
 * 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
107
 * function via the opaque parameter by the caller of virVMXParseConfig.
108 109 110 111 112 113 114 115 116
 *
 * 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.
 */
117
static char *
118
esxParseVMXFileName(const char *fileName, void *opaque)
119
{
120 121
    char *datastorePath = NULL;
    esxVMX_Data *data = opaque;
122
    esxVI_String *propertyNameList = NULL;
123
    esxVI_ObjectContent *datastoreList = NULL;
124
    esxVI_ObjectContent *datastore = NULL;
125 126 127 128 129 130 131 132 133 134
    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 */
135 136
        if (virAsprintf(&datastorePath, "%s/%s",
                        data->datastorePathWithoutFileName, fileName) < 0) {
137 138 139 140 141 142 143 144 145 146
            virReportOOMError();
            goto cleanup;
        }
    } else {
        if (esxVI_String_AppendValueToList(&propertyNameList,
                                           "summary.name") < 0 ||
            esxVI_LookupDatastoreList(data->ctx, propertyNameList,
                                      &datastoreList) < 0) {
            return NULL;
        }
147

148 149 150 151 152
        /* Search for datastore by mount path */
        for (datastore = datastoreList; datastore != NULL;
             datastore = datastore->_next) {
            esxVI_DatastoreHostMount_Free(&hostMount);
            datastoreName = NULL;
153

154 155 156 157 158 159
            if (esxVI_LookupDatastoreHostMount(data->ctx, datastore->obj,
                                               &hostMount) < 0 ||
                esxVI_GetStringValue(datastore, "summary.name", &datastoreName,
                                     esxVI_Occurrence_RequiredItem) < 0) {
                goto cleanup;
            }
160

161
            tmp = (char *)STRSKIP(fileName, hostMount->mountInfo->path);
162

163 164 165
            if (tmp == NULL) {
                continue;
            }
166

167 168 169 170
            /* Found a match. Strip leading separators */
            while (*tmp == '/' || *tmp == '\\') {
                ++tmp;
            }
171

172 173 174
            if (esxVI_String_DeepCopyValue(&strippedFileName, tmp) < 0) {
                goto cleanup;
            }
175

176
            tmp = strippedFileName;
177

178 179 180 181 182
            /* Convert \ to / */
            while (*tmp != '\0') {
                if (*tmp == '\\') {
                    *tmp = '/';
                }
183

184 185
                ++tmp;
            }
186

187 188 189 190 191
            if (virAsprintf(&datastorePath, "[%s] %s", datastoreName,
                            strippedFileName) < 0) {
                virReportOOMError();
                goto cleanup;
            }
192

193 194
            break;
        }
195

196 197 198 199 200
        /* Fallback to direct datastore name match */
        if (datastorePath == NULL && STRPREFIX(fileName, "/vmfs/volumes/")) {
            if (esxVI_String_DeepCopyValue(&copyOfFileName, fileName) < 0) {
                goto cleanup;
            }
201

202 203 204 205 206 207 208 209 210
            /* 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;
            }
211

212
            esxVI_ObjectContent_Free(&datastoreList);
213

214 215 216 217 218
            if (esxVI_LookupDatastoreByName(data->ctx, datastoreName,
                                            NULL, &datastoreList,
                                            esxVI_Occurrence_OptionalItem) < 0) {
                goto cleanup;
            }
219

220 221 222 223 224 225
            if (datastoreList == NULL) {
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                          _("File name '%s' refers to non-existing datastore '%s'"),
                          fileName, datastoreName);
                goto cleanup;
            }
226

227 228 229 230 231
            if (virAsprintf(&datastorePath, "[%s] %s", datastoreName,
                            directoryAndFileName) < 0) {
                virReportOOMError();
                goto cleanup;
            }
232 233
        }

234 235 236 237
        if (datastorePath == NULL) {
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                      _("Could not find datastore for '%s'"), fileName);
            goto cleanup;
238
        }
239
    }
240

241 242 243 244 245 246
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&datastoreList);
    esxVI_DatastoreHostMount_Free(&hostMount);
    VIR_FREE(strippedFileName);
    VIR_FREE(copyOfFileName);
247

248
    return datastorePath;
249 250 251 252
}



253 254 255 256 257 258 259 260 261 262 263 264 265
/*
 * 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.
 */
266
static char *
267
esxFormatVMXFileName(const char *datastorePath, void *opaque)
268 269
{
    bool success = false;
270
    esxVMX_Data *data = opaque;
271
    char *datastoreName = NULL;
272
    char *directoryAndFileName = NULL;
273 274 275 276 277
    esxVI_ObjectContent *datastore = NULL;
    esxVI_DatastoreHostMount *hostMount = NULL;
    char separator = '/';
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    char *tmp;
278
    size_t length;
279 280
    char *absolutePath = NULL;

281
    /* Parse datastore path and lookup datastore */
282 283
    if (esxUtil_ParseDatastorePath(datastorePath, &datastoreName, NULL,
                                   &directoryAndFileName) < 0) {
284 285
        goto cleanup;
    }
286

287
    if (esxVI_LookupDatastoreByName(data->ctx, datastoreName, NULL, &datastore,
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
                                    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;
    }

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

309 310
    if (separator != '/') {
        tmp = directoryAndFileName;
311

312 313 314
        while (*tmp != '\0') {
            if (*tmp == '/') {
                *tmp = separator;
315 316
            }

317 318
            ++tmp;
        }
319 320 321
    }

    virBufferAddChar(&buffer, separator);
322
    virBufferAdd(&buffer, directoryAndFileName, -1);
323 324 325

    if (virBufferError(&buffer)) {
        virReportOOMError();
326 327 328
        goto cleanup;
    }

329 330
    absolutePath = virBufferContentAndReset(&buffer);

331 332 333 334 335 336
    /* FIXME: Check if referenced path/file really exists */

    success = true;

  cleanup:
    if (! success) {
337
        virBufferFreeAndReset(&buffer);
338 339 340 341
        VIR_FREE(absolutePath);
    }

    VIR_FREE(datastoreName);
342
    VIR_FREE(directoryAndFileName);
343 344
    esxVI_ObjectContent_Free(&datastore);
    esxVI_DatastoreHostMount_Free(&hostMount);
345 346 347 348 349 350 351 352 353 354 355 356

    return absolutePath;
}



static int
esxAutodetectSCSIControllerModel(virDomainDiskDefPtr def, int *model,
                                 void *opaque)
{
    int result = -1;
    esxVMX_Data *data = opaque;
357
    esxVI_FileInfo *fileInfo = NULL;
358 359 360 361 362 363 364 365 366 367 368 369 370 371
    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;
    }

372 373
    if (esxVI_LookupFileInfoByDatastorePath(data->ctx, def->src,
                                            false, &fileInfo,
374
                                            esxVI_Occurrence_RequiredItem) < 0) {
375 376 377
        goto cleanup;
    }

378
    vmDiskFileInfo = esxVI_VmDiskFileInfo_DynamicCast(fileInfo);
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407

    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:
408
    esxVI_FileInfo_Free(&fileInfo);
409 410 411 412

    return result;
}

413 414


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

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

430
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
431
        return esxVI_Boolean_Undefined;
432 433
    }

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

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

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

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

463
                    edxLongModeBit = parsedHostCpuIdInfo.edx[29];
464 465 466 467 468 469

                    if (edxLongModeBit == '1') {
                        priv->supportsLongMode = esxVI_Boolean_True;
                    } else if (edxLongModeBit == '0') {
                        priv->supportsLongMode = esxVI_Boolean_False;
                    } else {
470
                        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
471 472 473 474
                                  _("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 已提交
475
                        goto cleanup;
476 477 478 479 480 481 482 483 484 485 486 487 488
                    }

                    break;
                }
            }

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

  cleanup:
M
Matthias Bolte 已提交
489 490 491 492
    /*
     * 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.
     */
493 494 495 496 497 498 499 500 501
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_HostCpuIdInfo_Free(&hostCpuIdInfoList);

    return priv->supportsLongMode;
}



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

510
    if (esxVI_EnsureSession(priv->primary) < 0) {
511 512 513 514 515
        return -1;
    }

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



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

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

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

    if (caps == NULL) {
583
        virReportOOMError();
584 585 586
        return NULL;
    }

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

590 591
    caps->hasWideScsiBus = true;

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

596 597 598
    /* i686 */
    guest = virCapabilitiesAddGuest(caps, "hvm", "i686", 32, NULL, NULL, 0,
                                    NULL);
599 600 601 602 603 604 605 606 607 608

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

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

609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
    /* 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;
        }
    }

624 625 626 627 628 629 630 631 632 633
    return caps;

  failure:
    virCapabilitiesFree(caps);

    return NULL;
}



634 635 636 637 638 639 640 641 642 643
static int
esxConnectToHost(esxPrivate *priv, virConnectAuthPtr auth,
                 const char *hostname, int port,
                 const char *predefinedUsername,
                 esxVI_ProductVersion expectedProductVersion,
                 char **vCenterIpAddress)
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
M
Matthias Bolte 已提交
644
    char *unescapedPassword = NULL;
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
    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 已提交
676
    unescapedPassword = virRequestPassword(auth, username, hostname);
677

M
Matthias Bolte 已提交
678
    if (unescapedPassword == NULL) {
679 680 681 682
        ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
        goto cleanup;
    }

M
Matthias Bolte 已提交
683 684 685 686 687 688
    password = esxUtil_EscapeForXml(unescapedPassword);

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

689 690
    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->parsedUri->transport,
                    hostname, port) < 0) {
691 692 693 694 695 696
        virReportOOMError();
        goto cleanup;
    }

    if (esxVI_Context_Alloc(&priv->host) < 0 ||
        esxVI_Context_Connect(priv->host, url, ipAddress, username, password,
697 698
                              priv->parsedUri) < 0 ||
        esxVI_Context_LookupObjectsByPath(priv->host, priv->parsedUri) < 0) {
699 700 701 702 703
        goto cleanup;
    }

    if (expectedProductVersion == esxVI_ProductVersion_ESX) {
        if (priv->host->productVersion != esxVI_ProductVersion_ESX35 &&
M
Matthias Bolte 已提交
704 705 706
            priv->host->productVersion != esxVI_ProductVersion_ESX40 &&
            priv->host->productVersion != esxVI_ProductVersion_ESX41 &&
            priv->host->productVersion != esxVI_ProductVersion_ESX4x) {
707
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
M
Matthias Bolte 已提交
708
                      _("%s is neither an ESX 3.5 host nor an ESX 4.x host"),
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
                      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 ||
724 725
        esxVI_LookupHostSystemProperties(priv->host, propertyNameList,
                                         &hostSystem) < 0 ||
726 727 728 729 730 731 732 733 734 735 736
        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) {
737
        VIR_WARN("The server is in maintenance mode");
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
    }

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

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

    result = 0;

  cleanup:
    VIR_FREE(username);
M
Matthias Bolte 已提交
753 754
    VIR_FREE(unescapedPassword);
    VIR_FREE(password);
755 756 757 758 759 760 761 762 763 764 765 766 767
    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,
768
                    const char *hostSystemIpAddress)
769 770 771 772
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
M
Matthias Bolte 已提交
773
    char *unescapedPassword = NULL;
774 775 776
    char *password = NULL;
    char *url = NULL;

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

785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
    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 已提交
805
    unescapedPassword = virRequestPassword(auth, username, hostname);
806

M
Matthias Bolte 已提交
807
    if (unescapedPassword == NULL) {
808 809 810 811
        ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
        goto cleanup;
    }

M
Matthias Bolte 已提交
812 813 814 815 816 817
    password = esxUtil_EscapeForXml(unescapedPassword);

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

818 819
    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->parsedUri->transport,
                    hostname, port) < 0) {
820 821 822 823 824 825
        virReportOOMError();
        goto cleanup;
    }

    if (esxVI_Context_Alloc(&priv->vCenter) < 0 ||
        esxVI_Context_Connect(priv->vCenter, url, ipAddress, username,
826
                              password, priv->parsedUri) < 0) {
827 828 829 830
        goto cleanup;
    }

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

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

852 853 854 855
    result = 0;

  cleanup:
    VIR_FREE(username);
M
Matthias Bolte 已提交
856 857
    VIR_FREE(unescapedPassword);
    VIR_FREE(password);
858 859 860 861 862 863 864
    VIR_FREE(url);

    return result;
}



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

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

925 926 927 928 929 930 931 932 933 934 935 936
    /* Require server part */
    if (conn->uri->server == NULL) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("URI is missing the server part"));
        return VIR_DRV_OPEN_ERROR;
    }

    /* Require auth */
    if (auth == NULL || auth->cb == NULL) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Missing or invalid auth pointer"));
        return VIR_DRV_OPEN_ERROR;
937 938 939 940
    }

    /* Allocate per-connection private data */
    if (VIR_ALLOC(priv) < 0) {
941
        virReportOOMError();
M
Matthias Bolte 已提交
942
        goto cleanup;
943 944
    }

945
    if (esxUtil_ParseUri(&priv->parsedUri, conn->uri) < 0) {
946 947 948
        goto cleanup;
    }

M
Matthias Bolte 已提交
949 950
    priv->maxVcpus = -1;
    priv->supportsVMotion = esxVI_Boolean_Undefined;
951
    priv->supportsLongMode = esxVI_Boolean_Undefined;
952 953
    priv->usedCpuTimeCounterId = -1;

M
Matthias Bolte 已提交
954 955 956 957 958 959 960
    /*
     * 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) {
961 962
        if (STRCASEEQ(conn->uri->scheme, "vpx") ||
            STRCASEEQ(conn->uri->scheme, "esx")) {
963
            if (STRCASEEQ(priv->parsedUri->transport, "https")) {
M
Matthias Bolte 已提交
964 965 966 967 968
                conn->uri->port = 443;
            } else {
                conn->uri->port = 80;
            }
        } else { /* GSX */
969
            if (STRCASEEQ(priv->parsedUri->transport, "https")) {
M
Matthias Bolte 已提交
970 971 972 973
                conn->uri->port = 8333;
            } else {
                conn->uri->port = 8222;
            }
974
        }
M
Matthias Bolte 已提交
975
    }
976

977 978 979 980
    if (STRCASEEQ(conn->uri->scheme, "esx") ||
        STRCASEEQ(conn->uri->scheme, "gsx")) {
        /* Connect to host */
        if (esxConnectToHost(priv, auth, conn->uri->server, conn->uri->port,
981
                             conn->uri->user,
982 983 984 985
                             STRCASEEQ(conn->uri->scheme, "esx")
                               ? esxVI_ProductVersion_ESX
                               : esxVI_ProductVersion_GSX,
                             &potentialVCenterIpAddress) < 0) {
M
Matthias Bolte 已提交
986
            goto cleanup;
987
        }
988

989
        /* Connect to vCenter */
990 991
        if (priv->parsedUri->vCenter != NULL) {
            if (STREQ(priv->parsedUri->vCenter, "*")) {
992 993 994
                if (potentialVCenterIpAddress == NULL) {
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                              _("This host is not managed by a vCenter"));
M
Matthias Bolte 已提交
995
                    goto cleanup;
996 997
                }

998 999 1000 1001 1002 1003 1004 1005
                if (virStrcpyStatic(vCenterIpAddress,
                                    potentialVCenterIpAddress) == NULL) {
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                              _("vCenter IP address %s too big for destination"),
                              potentialVCenterIpAddress);
                    goto cleanup;
                }
            } else {
1006
                if (esxUtil_ResolveHostname(priv->parsedUri->vCenter,
1007 1008 1009
                                            vCenterIpAddress, NI_MAXHOST) < 0) {
                    goto cleanup;
                }
1010

1011 1012
                if (potentialVCenterIpAddress != NULL &&
                    STRNEQ(vCenterIpAddress, potentialVCenterIpAddress)) {
1013
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1014 1015 1016
                              _("This host is managed by a vCenter with IP "
                                "address %s, but a mismachting vCenter '%s' "
                                "(%s) has been specified"),
1017
                              potentialVCenterIpAddress, priv->parsedUri->vCenter,
1018
                              vCenterIpAddress);
M
Matthias Bolte 已提交
1019
                    goto cleanup;
1020 1021
                }
            }
1022

1023
            if (esxConnectToVCenter(priv, auth, vCenterIpAddress,
1024
                                    conn->uri->port, NULL,
1025
                                    priv->host->ipAddress) < 0) {
1026 1027
                goto cleanup;
            }
1028 1029
        }

1030 1031 1032 1033
        priv->primary = priv->host;
    } else { /* VPX */
        /* Connect to vCenter */
        if (esxConnectToVCenter(priv, auth, conn->uri->server, conn->uri->port,
1034
                                conn->uri->user, NULL) < 0) {
M
Matthias Bolte 已提交
1035
            goto cleanup;
1036 1037
        }

1038
        priv->primary = priv->vCenter;
1039 1040
    }

M
Matthias Bolte 已提交
1041
    /* Setup capabilities */
1042
    priv->caps = esxCapsInit(priv);
1043

M
Matthias Bolte 已提交
1044
    if (priv->caps == NULL) {
M
Matthias Bolte 已提交
1045
        goto cleanup;
1046 1047
    }

1048 1049
    conn->privateData = priv;

M
Matthias Bolte 已提交
1050
    result = VIR_DRV_OPEN_SUCCESS;
1051

M
Matthias Bolte 已提交
1052
  cleanup:
1053 1054
    if (result == VIR_DRV_OPEN_ERROR) {
        esxFreePrivate(&priv);
1055 1056
    }

1057
    VIR_FREE(potentialVCenterIpAddress);
1058

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



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

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

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

1084
    esxFreePrivate(&priv);
1085 1086 1087

    conn->privateData = NULL;

E
Eric Blake 已提交
1088
    return result;
1089 1090 1091 1092 1093
}



static esxVI_Boolean
1094
esxSupportsVMotion(esxPrivate *priv)
1095 1096 1097 1098
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;

M
Matthias Bolte 已提交
1099 1100
    if (priv->supportsVMotion != esxVI_Boolean_Undefined) {
        return priv->supportsVMotion;
1101 1102
    }

1103
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1104
        return esxVI_Boolean_Undefined;
1105 1106
    }

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

    if (hostSystem == NULL) {
1115 1116
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
1117
        goto cleanup;
1118 1119
    }

1120 1121 1122 1123
    if (esxVI_GetBoolean(hostSystem, "capability.vmotionSupported",
                         &priv->supportsVMotion,
                         esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
1124 1125 1126
    }

  cleanup:
M
Matthias Bolte 已提交
1127 1128 1129 1130
    /*
     * 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.
     */
1131 1132 1133
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
1134
    return priv->supportsVMotion;
1135 1136 1137 1138 1139 1140 1141
}



static int
esxSupportsFeature(virConnectPtr conn, int feature)
{
M
Matthias Bolte 已提交
1142
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1143
    esxVI_Boolean supportsVMotion = esxVI_Boolean_Undefined;
1144 1145 1146

    switch (feature) {
      case VIR_DRV_FEATURE_MIGRATION_V1:
1147
        supportsVMotion = esxSupportsVMotion(priv);
1148

M
Matthias Bolte 已提交
1149
        if (supportsVMotion == esxVI_Boolean_Undefined) {
1150 1151 1152
            return -1;
        }

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

      default:
        return 0;
    }
}



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



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

1177
    if (virParseVersionString(priv->primary->service->about->version,
1178 1179
                              version) < 0) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1180
                  _("Could not parse version number from '%s'"),
1181
                  priv->primary->service->about->version);
1182

1183
        return -1;
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
    }

    return 0;
}



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

1202
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1203
        return NULL;
1204 1205 1206
    }

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

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

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

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

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

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

M
Matthias Bolte 已提交
1250
    if (domainName == NULL || strlen(domainName) < 1) {
1251
        complete = strdup(hostName);
1252

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

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

    return complete;
}



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

1296
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1297
        return -1;
1298 1299
    }

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

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

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

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

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

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

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

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

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

            ptr = dynamicProperty->val->string;

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

                ++ptr;
            }

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

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

1419 1420 1421 1422 1423 1424 1425 1426 1427
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



1428 1429 1430
static char *
esxGetCapabilities(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1431
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1432
    char *xml = virCapabilitiesFormatXML(priv->caps);
1433 1434

    if (xml == NULL) {
1435
        virReportOOMError();
1436 1437 1438 1439 1440 1441 1442 1443
        return NULL;
    }

    return xml;
}



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

    if (ids == NULL || maxids < 0) {
1456 1457
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
1458 1459 1460 1461 1462 1463
    }

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

1464
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1465
        return -1;
1466 1467
    }

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

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

        if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

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

        count++;

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

M
Matthias Bolte 已提交
1502 1503
    success = true;

1504 1505 1506 1507
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
1508
    return success ? count : -1;
1509 1510 1511 1512 1513 1514 1515
}



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

1518
    if (esxVI_EnsureSession(priv->primary) < 0) {
1519 1520 1521
        return -1;
    }

1522
    return esxVI_LookupNumberOfDomainsByPowerState
1523
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, false);
1524 1525 1526 1527 1528 1529 1530
}



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

1541
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1542
        return NULL;
1543 1544
    }

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

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

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

M
Matthias Bolte 已提交
1567
        VIR_FREE(name_candidate);
1568

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

M
Matthias Bolte 已提交
1575
        if (id != id_candidate) {
1576 1577 1578
            continue;
        }

M
Matthias Bolte 已提交
1579
        domain = virGetDomain(conn, name_candidate, uuid_candidate);
1580 1581

        if (domain == NULL) {
M
Matthias Bolte 已提交
1582
            goto cleanup;
1583 1584 1585 1586 1587 1588 1589 1590
        }

        domain->id = id;

        break;
    }

    if (domain == NULL) {
1591
        ESX_ERROR(VIR_ERR_NO_DOMAIN, _("No domain with ID %d"), id);
1592 1593 1594 1595 1596
    }

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

    return domain;
}



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

1615
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1616
        return NULL;
1617 1618
    }

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

1630
    domain = virGetDomain(conn, name, uuid);
1631 1632

    if (domain == NULL) {
M
Matthias Bolte 已提交
1633
        goto cleanup;
1634
    }
1635

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

  cleanup:
    esxVI_String_Free(&propertyNameList);
1645 1646
    esxVI_ObjectContent_Free(&virtualMachine);
    VIR_FREE(name);
1647 1648 1649 1650 1651 1652 1653 1654 1655

    return domain;
}



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

1664
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1665
        return NULL;
1666 1667
    }

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

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

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

1688
    domain = virGetDomain(conn, name, uuid);
1689

1690
    if (domain == NULL) {
M
Matthias Bolte 已提交
1691
        goto cleanup;
1692 1693
    }

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

  cleanup:
    esxVI_String_Free(&propertyNameList);
1703
    esxVI_ObjectContent_Free(&virtualMachine);
1704 1705 1706 1707 1708 1709 1710 1711 1712

    return domain;
}



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

1722
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1723
        return -1;
1724 1725
    }

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

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

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

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

M
Matthias Bolte 已提交
1755 1756
    result = 0;

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

    return result;
}



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

1780
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1781
        return -1;
1782 1783
    }

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

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

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

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

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

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

    return result;
}



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

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

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

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

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

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

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

    return result;
}



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

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

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

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

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

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

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

    return result;
}



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

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

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

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

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

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

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

1964
    domain->id = -1;
M
Matthias Bolte 已提交
1965 1966
    result = 0;

1967 1968 1969 1970
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1971
    VIR_FREE(taskInfoErrorMessage);
1972 1973 1974 1975 1976 1977 1978

    return result;
}



static char *
1979
esxDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED)
1980
{
1981 1982 1983
    char *osType = strdup("hvm");

    if (osType == NULL) {
1984
        virReportOOMError();
1985 1986 1987 1988
        return NULL;
    }

    return osType;
1989 1990 1991 1992 1993 1994 1995
}



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

2002
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2003
        return 0;
2004 2005
    }

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

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

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

2058
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2059
        return -1;
2060 2061
    }

2062 2063 2064 2065
    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "runtime.powerState") < 0 ||
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
2066
           priv->parsedUri->autoAnswer) < 0 ||
2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077
        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 ||
2078
        esxVI_Long_Alloc(&spec->memoryMB) < 0) {
M
Matthias Bolte 已提交
2079
        goto cleanup;
2080 2081
    }

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

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

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

M
Matthias Bolte 已提交
2102 2103
    result = 0;

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

    return result;
}



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

2127
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2128
        return -1;
2129 2130
    }

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

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

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

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

M
Matthias Bolte 已提交
2159 2160
    result = 0;

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

    return result;
}



2172 2173 2174 2175 2176 2177 2178 2179 2180
/*
 * libvirt exposed virtual CPU usage in absolute time, ESX doesn't provide this
 * information in this format. It exposes it in 20 seconds slots, but it's hard
 * to get a reliable absolute time from this. Therefore, disable the code that
 * queries the performance counters here for now, but keep it as example for how
 * to query a selected performance counter for its values.
 */
#define ESX_QUERY_FOR_USED_CPU_TIME 0

2181 2182 2183
static int
esxDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info)
{
M
Matthias Bolte 已提交
2184
    int result = -1;
M
Matthias Bolte 已提交
2185
    esxPrivate *priv = domain->conn->privateData;
2186 2187 2188 2189 2190
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int64_t memory_limit = -1;
2191
#if ESX_QUERY_FOR_USED_CPU_TIME
2192 2193 2194 2195 2196 2197 2198
    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;
2199 2200
    esxVI_PerfEntityMetricBase *perfEntityMetricBase = NULL;
    esxVI_PerfEntityMetricBase *perfEntityMetricBaseList = NULL;
2201 2202 2203
    esxVI_PerfEntityMetric *perfEntityMetric = NULL;
    esxVI_PerfMetricIntSeries *perfMetricIntSeries = NULL;
    esxVI_Long *value = NULL;
2204
#endif
2205

M
Matthias Bolte 已提交
2206 2207
    memset(info, 0, sizeof (*info));

2208
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2209
        return -1;
2210 2211
    }

2212
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2213 2214 2215 2216
                                           "runtime.powerState\0"
                                           "config.hardware.memoryMB\0"
                                           "config.hardware.numCPU\0"
                                           "config.memoryAllocation.limit\0") < 0 ||
2217
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2218
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2219
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2220
        goto cleanup;
2221 2222 2223 2224 2225 2226 2227 2228
    }

    info->state = VIR_DOMAIN_NOSTATE;

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

2233 2234
            info->state = esxVI_VirtualMachinePowerState_ConvertToLibvirt
                            (powerState);
2235
        } else if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2236
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2237
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2238
                goto cleanup;
2239 2240 2241 2242
            }

            info->maxMem = dynamicProperty->val->int32 * 1024; /* Scale from megabyte to kilobyte */
        } else if (STREQ(dynamicProperty->name, "config.hardware.numCPU")) {
2243
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2244
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2245
                goto cleanup;
2246 2247 2248 2249 2250
            }

            info->nrVirtCpu = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "config.memoryAllocation.limit")) {
2251
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2252
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
2253
                goto cleanup;
2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268
            }

            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;

2269
#if ESX_QUERY_FOR_USED_CPU_TIME
2270
    /* Verify the cached 'used CPU time' performance counter ID */
2271 2272 2273 2274 2275 2276
    /* 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;
            }
2277

2278
            counterId->value = priv->usedCpuTimeCounterId;
2279

2280 2281 2282
            if (esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                goto cleanup;
            }
2283

2284 2285 2286 2287
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfo) < 0) {
                goto cleanup;
            }
2288

2289 2290 2291 2292 2293
            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);
2294

2295 2296 2297 2298 2299
                priv->usedCpuTimeCounterId = -1;
            }

            esxVI_Int_Free(&counterIdList);
            esxVI_PerfCounterInfo_Free(&perfCounterInfo);
2300 2301
        }

2302 2303 2304 2305 2306 2307 2308 2309 2310 2311
        /*
         * 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;
            }
2312

2313 2314 2315 2316
            for (perfMetricId = perfMetricIdList; perfMetricId != NULL;
                 perfMetricId = perfMetricId->_next) {
                VIR_DEBUG("perfMetricId counterId %d, instance '%s'",
                          perfMetricId->counterId->value, perfMetricId->instance);
2317

2318
                counterId = NULL;
2319

2320 2321 2322 2323 2324
                if (esxVI_Int_DeepCopy(&counterId, perfMetricId->counterId) < 0 ||
                    esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                    goto cleanup;
                }
            }
2325

2326 2327
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfoList) < 0) {
M
Matthias Bolte 已提交
2328
                goto cleanup;
2329 2330
            }

2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347
            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;
                }
2348 2349
            }

2350
            if (priv->usedCpuTimeCounterId < 0) {
2351
                VIR_WARN("Could not find 'used CPU time' performance counter");
2352
            }
2353 2354
        }

2355 2356 2357 2358 2359 2360
        /*
         * 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);
2361

2362 2363 2364 2365 2366 2367
            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;
            }
2368

2369 2370 2371 2372 2373 2374 2375 2376 2377 2378
            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) {
                goto cleanup;
            }
2379

2380 2381 2382
            for (perfEntityMetricBase = perfEntityMetricBaseList;
                 perfEntityMetricBase != NULL;
                 perfEntityMetricBase = perfEntityMetricBase->_next) {
2383
                VIR_DEBUG("perfEntityMetric ...");
2384

2385 2386
                perfEntityMetric =
                  esxVI_PerfEntityMetric_DynamicCast(perfEntityMetricBase);
2387

2388
                if (perfEntityMetric == NULL) {
2389 2390
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                              _("QueryPerf returned object with unexpected type '%s'"),
2391
                              esxVI_Type_ToString(perfEntityMetricBase->_type));
2392
                    goto cleanup;
2393
                }
2394

2395 2396
                perfMetricIntSeries =
                  esxVI_PerfMetricIntSeries_DynamicCast(perfEntityMetric->value);
2397

2398
                if (perfMetricIntSeries == NULL) {
2399 2400
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                              _("QueryPerf returned object with unexpected type '%s'"),
2401
                              esxVI_Type_ToString(perfEntityMetric->value->_type));
2402
                    goto cleanup;
2403
                }
2404

2405 2406
                for (; perfMetricIntSeries != NULL;
                     perfMetricIntSeries = perfMetricIntSeries->_next) {
2407
                    VIR_DEBUG("perfMetricIntSeries ...");
2408

2409 2410 2411 2412 2413
                    for (value = perfMetricIntSeries->value;
                         value != NULL;
                         value = value->_next) {
                        VIR_DEBUG("value %lld", (long long int)value->value);
                    }
2414 2415 2416
                }
            }

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

2419
            /*
E
Eric Blake 已提交
2420
             * FIXME: Cannot map between relative used-cpu-time and absolute
2421 2422 2423
             *        info->cpuTime
             */
        }
2424
    }
2425
#endif
2426

M
Matthias Bolte 已提交
2427 2428
    result = 0;

2429
  cleanup:
2430
#if ESX_QUERY_FOR_USED_CPU_TIME
2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442
    /*
     * Remove values owned by data structures to prevent them from being freed
     * by the call to esxVI_PerfQuerySpec_Free().
     */
    if (querySpec != NULL) {
        querySpec->entity = NULL;
        querySpec->format = NULL;

        if (querySpec->metricId != NULL) {
            querySpec->metricId->instance = NULL;
        }
    }
2443
#endif
2444

2445 2446
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2447
#if ESX_QUERY_FOR_USED_CPU_TIME
2448 2449 2450 2451
    esxVI_PerfMetricId_Free(&perfMetricIdList);
    esxVI_Int_Free(&counterIdList);
    esxVI_PerfCounterInfo_Free(&perfCounterInfoList);
    esxVI_PerfQuerySpec_Free(&querySpec);
2452
    esxVI_PerfEntityMetricBase_Free(&perfEntityMetricBaseList);
2453
#endif
2454 2455 2456 2457 2458 2459

    return result;
}



2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502
static int
esxDomainGetState(virDomainPtr domain,
                  int *state,
                  int *reason,
                  unsigned int flags)
{
    int result = -1;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;

    virCheckFlags(0, -1);

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

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "runtime.powerState") < 0 ||
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
                                         propertyNameList, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
    }

    *state = esxVI_VirtualMachinePowerState_ConvertToLibvirt(powerState);

    if (reason)
        *reason = 0;

    result = 0;

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

    return result;
}



2503
static int
2504 2505
esxDomainSetVcpusFlags(virDomainPtr domain, unsigned int nvcpus,
                       unsigned int flags)
2506
{
M
Matthias Bolte 已提交
2507
    int result = -1;
M
Matthias Bolte 已提交
2508
    esxPrivate *priv = domain->conn->privateData;
M
Matthias Bolte 已提交
2509
    int maxVcpus;
2510 2511 2512 2513
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2514
    char *taskInfoErrorMessage = NULL;
2515

2516 2517 2518 2519 2520
    if (flags != VIR_DOMAIN_VCPU_LIVE) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
        return -1;
    }

2521
    if (nvcpus < 1) {
2522 2523
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Requested number of virtual CPUs must at least be 1"));
M
Matthias Bolte 已提交
2524
        return -1;
2525 2526
    }

2527
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2528
        return -1;
2529 2530
    }

M
Matthias Bolte 已提交
2531
    maxVcpus = esxDomainGetMaxVcpus(domain);
2532

M
Matthias Bolte 已提交
2533
    if (maxVcpus < 0) {
M
Matthias Bolte 已提交
2534
        return -1;
2535 2536
    }

M
Matthias Bolte 已提交
2537
    if (nvcpus > maxVcpus) {
2538
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2539 2540
                  _("Requested number of virtual CPUs is greater than max "
                    "allowable number of virtual CPUs for the domain: %d > %d"),
M
Matthias Bolte 已提交
2541
                  nvcpus, maxVcpus);
M
Matthias Bolte 已提交
2542
        return -1;
2543 2544
    }

2545
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2546
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2547
           priv->parsedUri->autoAnswer) < 0 ||
2548 2549
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Int_Alloc(&spec->numCPUs) < 0) {
M
Matthias Bolte 已提交
2550
        goto cleanup;
2551 2552 2553 2554
    }

    spec->numCPUs->value = nvcpus;

2555
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2556
                              &task) < 0 ||
2557
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2558
                                    esxVI_Occurrence_RequiredItem,
2559
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2560
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2561
        goto cleanup;
2562 2563 2564
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2565
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2566 2567
                  _("Could not set number of virtual CPUs to %d: %s"), nvcpus,
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
2568
        goto cleanup;
2569 2570
    }

M
Matthias Bolte 已提交
2571 2572
    result = 0;

2573 2574 2575 2576
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2577
    VIR_FREE(taskInfoErrorMessage);
2578 2579 2580 2581 2582

    return result;
}


M
Matthias Bolte 已提交
2583

2584 2585 2586 2587 2588 2589
static int
esxDomainSetVcpus(virDomainPtr domain, unsigned int nvcpus)
{
    return esxDomainSetVcpusFlags(domain, nvcpus, VIR_DOMAIN_VCPU_LIVE);
}

2590

M
Matthias Bolte 已提交
2591

2592
static int
2593
esxDomainGetVcpusFlags(virDomainPtr domain, unsigned int flags)
2594
{
M
Matthias Bolte 已提交
2595
    esxPrivate *priv = domain->conn->privateData;
2596 2597 2598 2599
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

2600 2601 2602 2603 2604
    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 已提交
2605 2606
    if (priv->maxVcpus > 0) {
        return priv->maxVcpus;
2607 2608
    }

M
Matthias Bolte 已提交
2609 2610
    priv->maxVcpus = -1;

2611
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2612
        return -1;
2613 2614
    }

2615
    if (esxVI_String_AppendValueToList(&propertyNameList,
2616
                                       "capability.maxSupportedVcpus") < 0 ||
2617 2618
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
2619
        goto cleanup;
2620 2621 2622
    }

    if (hostSystem == NULL) {
2623 2624
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
2625
        goto cleanup;
2626 2627 2628 2629 2630
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "capability.maxSupportedVcpus")) {
2631
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2632
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2633
                goto cleanup;
2634 2635
            }

M
Matthias Bolte 已提交
2636
            priv->maxVcpus = dynamicProperty->val->int32;
2637 2638 2639 2640 2641 2642 2643 2644 2645 2646
            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

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

M
Matthias Bolte 已提交
2647
    return priv->maxVcpus;
2648 2649
}

M
Matthias Bolte 已提交
2650 2651


2652 2653 2654 2655 2656 2657
static int
esxDomainGetMaxVcpus(virDomainPtr domain)
{
    return esxDomainGetVcpusFlags(domain, (VIR_DOMAIN_VCPU_LIVE |
                                           VIR_DOMAIN_VCPU_MAXIMUM));
}
2658

M
Matthias Bolte 已提交
2659 2660


2661
static char *
2662
esxDomainGetXMLDesc(virDomainPtr domain, int flags)
2663
{
M
Matthias Bolte 已提交
2664
    esxPrivate *priv = domain->conn->privateData;
2665 2666
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
2667 2668
    esxVI_VirtualMachinePowerState powerState;
    int id;
2669
    char *vmPathName = NULL;
2670
    char *datastoreName = NULL;
M
Matthias Bolte 已提交
2671
    char *directoryName = NULL;
2672
    char *directoryAndFileName = NULL;
2673
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
2674 2675
    char *url = NULL;
    char *vmx = NULL;
2676
    virVMXContext ctx;
2677
    esxVMX_Data data;
2678 2679 2680
    virDomainDefPtr def = NULL;
    char *xml = NULL;

2681
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2682
        return NULL;
2683 2684
    }

2685 2686 2687
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "config.files.vmPathName\0"
                                           "runtime.powerState\0") < 0 ||
2688
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2689
                                         propertyNameList, &virtualMachine,
2690
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2691 2692
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0 ||
2693 2694
        esxVI_GetStringValue(virtualMachine, "config.files.vmPathName",
                             &vmPathName, esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2695
        goto cleanup;
2696 2697
    }

2698
    if (esxUtil_ParseDatastorePath(vmPathName, &datastoreName, &directoryName,
2699
                                   &directoryAndFileName) < 0) {
M
Matthias Bolte 已提交
2700
        goto cleanup;
2701 2702
    }

2703
    virBufferAsprintf(&buffer, "%s://%s:%d/folder/", priv->parsedUri->transport,
2704
                      domain->conn->uri->server, domain->conn->uri->port);
2705
    virBufferURIEncodeString(&buffer, directoryAndFileName);
2706
    virBufferAddLit(&buffer, "?dcPath=");
2707
    virBufferURIEncodeString(&buffer, priv->primary->datacenter->name);
2708 2709 2710 2711
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
2712
        virReportOOMError();
M
Matthias Bolte 已提交
2713
        goto cleanup;
2714 2715
    }

2716 2717
    url = virBufferContentAndReset(&buffer);

2718
    if (esxVI_CURL_Download(priv->primary->curl, url, &vmx) < 0) {
M
Matthias Bolte 已提交
2719
        goto cleanup;
2720 2721
    }

2722
    data.ctx = priv->primary;
2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736

    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;
        }
    }
2737 2738 2739 2740 2741 2742

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

2743
    def = virVMXParseConfig(&ctx, priv->caps, vmx);
2744 2745

    if (def != NULL) {
2746 2747 2748 2749
        if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
            def->id = id;
        }

2750
        xml = virDomainDefFormat(def, flags);
2751 2752 2753
    }

  cleanup:
M
Matthias Bolte 已提交
2754 2755 2756 2757
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

2758 2759
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2760
    VIR_FREE(datastoreName);
M
Matthias Bolte 已提交
2761
    VIR_FREE(directoryName);
2762
    VIR_FREE(directoryAndFileName);
2763
    VIR_FREE(url);
2764
    VIR_FREE(data.datastorePathWithoutFileName);
2765
    VIR_FREE(vmx);
2766
    virDomainDefFree(def);
2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777

    return xml;
}



static char *
esxDomainXMLFromNative(virConnectPtr conn, const char *nativeFormat,
                       const char *nativeConfig,
                       unsigned int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2778
    esxPrivate *priv = conn->privateData;
2779
    virVMXContext ctx;
2780
    esxVMX_Data data;
2781 2782 2783 2784
    virDomainDefPtr def = NULL;
    char *xml = NULL;

    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2785
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2786
                  _("Unsupported config format '%s'"), nativeFormat);
2787
        return NULL;
2788 2789
    }

2790
    data.ctx = priv->primary;
2791
    data.datastorePathWithoutFileName = (char *)"[?] ?";
2792 2793 2794 2795 2796 2797

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

2798
    def = virVMXParseConfig(&ctx, priv->caps, nativeConfig);
2799 2800

    if (def != NULL) {
2801
        xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
2802 2803 2804 2805 2806 2807 2808 2809 2810
    }

    virDomainDefFree(def);

    return xml;
}



M
Matthias Bolte 已提交
2811 2812 2813 2814 2815
static char *
esxDomainXMLToNative(virConnectPtr conn, const char *nativeFormat,
                     const char *domainXml,
                     unsigned int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2816
    esxPrivate *priv = conn->privateData;
2817 2818
    int virtualHW_version;
    virVMXContext ctx;
2819
    esxVMX_Data data;
M
Matthias Bolte 已提交
2820 2821 2822 2823
    virDomainDefPtr def = NULL;
    char *vmx = NULL;

    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2824
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2825
                  _("Unsupported config format '%s'"), nativeFormat);
M
Matthias Bolte 已提交
2826 2827 2828
        return NULL;
    }

2829 2830 2831 2832 2833 2834 2835
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        return NULL;
    }

2836
    def = virDomainDefParseString(priv->caps, domainXml, 0);
M
Matthias Bolte 已提交
2837 2838 2839 2840 2841

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

2842
    data.ctx = priv->primary;
2843
    data.datastorePathWithoutFileName = NULL;
2844 2845 2846 2847 2848 2849

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

2850
    vmx = virVMXFormatConfig(&ctx, priv->caps, def, virtualHW_version);
M
Matthias Bolte 已提交
2851 2852 2853 2854 2855 2856 2857 2858

    virDomainDefFree(def);

    return vmx;
}



2859 2860 2861
static int
esxListDefinedDomains(virConnectPtr conn, char **const names, int maxnames)
{
M
Matthias Bolte 已提交
2862
    bool success = false;
M
Matthias Bolte 已提交
2863
    esxPrivate *priv = conn->privateData;
2864 2865 2866 2867 2868
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;
2869
    int i;
2870 2871

    if (names == NULL || maxnames < 0) {
2872 2873
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
2874 2875 2876 2877 2878 2879
    }

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

2880
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2881
        return -1;
2882 2883
    }

2884
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2885 2886
                                           "name\0"
                                           "runtime.powerState\0") < 0 ||
2887 2888
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2889
        goto cleanup;
2890 2891 2892 2893
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
2894
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
2895
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
2896
            goto cleanup;
2897 2898 2899 2900 2901 2902
        }

        if (powerState == esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

2903
        names[count] = NULL;
2904

2905 2906 2907
        if (esxVI_GetVirtualMachineIdentity(virtualMachine, NULL, &names[count],
                                            NULL) < 0) {
            goto cleanup;
2908 2909
        }

2910 2911
        ++count;

2912 2913 2914 2915 2916
        if (count >= maxnames) {
            break;
        }
    }

M
Matthias Bolte 已提交
2917
    success = true;
2918

M
Matthias Bolte 已提交
2919 2920 2921 2922 2923
  cleanup:
    if (! success) {
        for (i = 0; i < count; ++i) {
            VIR_FREE(names[i]);
        }
2924

M
Matthias Bolte 已提交
2925
        count = -1;
2926 2927
    }

M
Matthias Bolte 已提交
2928 2929
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
2930

M
Matthias Bolte 已提交
2931
    return count;
2932 2933 2934 2935 2936 2937 2938
}



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

2941
    if (esxVI_EnsureSession(priv->primary) < 0) {
2942 2943 2944
        return -1;
    }

2945
    return esxVI_LookupNumberOfDomainsByPowerState
2946
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, true);
2947 2948 2949 2950 2951
}



static int
2952
esxDomainCreateWithFlags(virDomainPtr domain, unsigned int flags)
2953
{
M
Matthias Bolte 已提交
2954
    int result = -1;
M
Matthias Bolte 已提交
2955
    esxPrivate *priv = domain->conn->privateData;
2956 2957 2958
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
2959
    int id = -1;
2960 2961
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2962
    char *taskInfoErrorMessage = NULL;
2963

2964 2965
    virCheckFlags(0, -1);

2966
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2967
        return -1;
2968 2969
    }

2970
    if (esxVI_String_AppendValueToList(&propertyNameList,
2971
                                       "runtime.powerState") < 0 ||
2972
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2973
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
2974
           priv->parsedUri->autoAnswer) < 0 ||
2975 2976
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0) {
M
Matthias Bolte 已提交
2977
        goto cleanup;
2978 2979 2980
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2981 2982
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered off"));
M
Matthias Bolte 已提交
2983
        goto cleanup;
2984 2985
    }

2986
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
2987
                             &task) < 0 ||
2988
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2989
                                    esxVI_Occurrence_RequiredItem,
2990
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2991
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2992
        goto cleanup;
2993 2994 2995
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2996 2997
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not start domain: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
2998
        goto cleanup;
2999 3000
    }

3001
    domain->id = id;
M
Matthias Bolte 已提交
3002 3003
    result = 0;

3004 3005 3006 3007
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
3008
    VIR_FREE(taskInfoErrorMessage);
3009 3010 3011 3012

    return result;
}

3013 3014


3015 3016 3017 3018 3019
static int
esxDomainCreate(virDomainPtr domain)
{
    return esxDomainCreateWithFlags(domain, 0);
}
3020

3021 3022


M
Matthias Bolte 已提交
3023
static virDomainPtr
3024
esxDomainDefineXML(virConnectPtr conn, const char *xml)
M
Matthias Bolte 已提交
3025
{
M
Matthias Bolte 已提交
3026
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
3027 3028
    virDomainDefPtr def = NULL;
    char *vmx = NULL;
3029 3030
    int i;
    virDomainDiskDefPtr disk = NULL;
M
Matthias Bolte 已提交
3031
    esxVI_ObjectContent *virtualMachine = NULL;
3032 3033
    int virtualHW_version;
    virVMXContext ctx;
3034
    esxVMX_Data data;
M
Matthias Bolte 已提交
3035 3036
    char *datastoreName = NULL;
    char *directoryName = NULL;
3037
    char *escapedName = NULL;
M
Matthias Bolte 已提交
3038 3039 3040 3041 3042 3043 3044 3045
    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;
3046
    char *taskInfoErrorMessage = NULL;
M
Matthias Bolte 已提交
3047 3048
    virDomainPtr domain = NULL;

3049
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3050
        return NULL;
M
Matthias Bolte 已提交
3051 3052 3053
    }

    /* Parse domain XML */
3054
    def = virDomainDefParseString(priv->caps, xml,
M
Matthias Bolte 已提交
3055 3056 3057
                                  VIR_DOMAIN_XML_INACTIVE);

    if (def == NULL) {
M
Matthias Bolte 已提交
3058
        return NULL;
M
Matthias Bolte 已提交
3059 3060 3061
    }

    /* Check if an existing domain should be edited */
3062
    if (esxVI_LookupVirtualMachineByUuid(priv->primary, def->uuid, NULL,
M
Matthias Bolte 已提交
3063
                                         &virtualMachine,
M
Matthias Bolte 已提交
3064
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
3065
        goto cleanup;
M
Matthias Bolte 已提交
3066 3067
    }

3068 3069 3070 3071 3072 3073 3074
    if (virtualMachine == NULL &&
        esxVI_LookupVirtualMachineByName(priv->primary, def->name, NULL,
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
    }

M
Matthias Bolte 已提交
3075 3076
    if (virtualMachine != NULL) {
        /* FIXME */
3077 3078 3079
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Domain already exists, editing existing domains is not "
                    "supported yet"));
M
Matthias Bolte 已提交
3080
        goto cleanup;
M
Matthias Bolte 已提交
3081 3082 3083
    }

    /* Build VMX from domain XML */
3084 3085 3086 3087 3088 3089 3090
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        goto cleanup;
    }

3091
    data.ctx = priv->primary;
3092
    data.datastorePathWithoutFileName = NULL;
3093 3094 3095 3096 3097 3098

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

3099
    vmx = virVMXFormatConfig(&ctx, priv->caps, def, virtualHW_version);
M
Matthias Bolte 已提交
3100 3101

    if (vmx == NULL) {
M
Matthias Bolte 已提交
3102
        goto cleanup;
M
Matthias Bolte 已提交
3103 3104
    }

3105 3106 3107 3108 3109 3110 3111
    /*
     * 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 已提交
3112
    if (def->ndisks < 1) {
3113 3114 3115
        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 已提交
3116
        goto cleanup;
3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127
    }

    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) {
3128 3129 3130
        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 已提交
3131
        goto cleanup;
M
Matthias Bolte 已提交
3132 3133
    }

3134
    if (disk->src == NULL) {
3135 3136 3137
        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 已提交
3138
        goto cleanup;
M
Matthias Bolte 已提交
3139 3140
    }

3141
    if (esxUtil_ParseDatastorePath(disk->src, &datastoreName, &directoryName,
3142
                                   NULL) < 0) {
M
Matthias Bolte 已提交
3143
        goto cleanup;
M
Matthias Bolte 已提交
3144 3145
    }

3146
    if (! virFileHasSuffix(disk->src, ".vmdk")) {
3147
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3148 3149
                  _("Expecting source '%s' of first file-based harddisk to "
                    "be a VMDK image"), disk->src);
M
Matthias Bolte 已提交
3150
        goto cleanup;
M
Matthias Bolte 已提交
3151 3152
    }

3153
    virBufferAsprintf(&buffer, "%s://%s:%d/folder/", priv->parsedUri->transport,
M
Matthias Bolte 已提交
3154 3155 3156 3157 3158 3159 3160
                      conn->uri->server, conn->uri->port);

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

3161 3162 3163 3164 3165 3166 3167
    escapedName = esxUtil_EscapeDatastoreItem(def->name);

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

    virBufferURIEncodeString(&buffer, escapedName);
M
Matthias Bolte 已提交
3168
    virBufferAddLit(&buffer, ".vmx?dcPath=");
3169
    virBufferURIEncodeString(&buffer, priv->primary->datacenter->name);
M
Matthias Bolte 已提交
3170 3171 3172 3173
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
3174
        virReportOOMError();
M
Matthias Bolte 已提交
3175
        goto cleanup;
M
Matthias Bolte 已提交
3176 3177 3178 3179
    }

    url = virBufferContentAndReset(&buffer);

3180 3181 3182 3183 3184 3185
    /* Check, if VMX file already exists */
    /* FIXME */

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

3186
    if (esxVI_CURL_Upload(priv->primary->curl, url, vmx) < 0) {
3187 3188 3189 3190
        goto cleanup;
    }

    /* Register the domain */
M
Matthias Bolte 已提交
3191 3192
    if (directoryName != NULL) {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s/%s.vmx", datastoreName,
3193
                        directoryName, escapedName) < 0) {
3194
            virReportOOMError();
M
Matthias Bolte 已提交
3195
            goto cleanup;
M
Matthias Bolte 已提交
3196 3197 3198
        }
    } else {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s.vmx", datastoreName,
3199
                        escapedName) < 0) {
3200
            virReportOOMError();
M
Matthias Bolte 已提交
3201
            goto cleanup;
M
Matthias Bolte 已提交
3202 3203 3204
        }
    }

3205
    if (esxVI_RegisterVM_Task(priv->primary, priv->primary->datacenter->vmFolder,
M
Matthias Bolte 已提交
3206
                              datastoreRelatedPath, NULL, esxVI_Boolean_False,
3207 3208 3209 3210
                              priv->primary->computeResource->resourcePool,
                              priv->primary->hostSystem->_reference,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, def->uuid,
3211
                                    esxVI_Occurrence_OptionalItem,
3212
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3213
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3214
        goto cleanup;
M
Matthias Bolte 已提交
3215 3216 3217
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3218 3219
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not define domain: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
3220
        goto cleanup;
M
Matthias Bolte 已提交
3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231
    }

    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 已提交
3232 3233 3234 3235
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

M
Matthias Bolte 已提交
3236 3237 3238 3239
    virDomainDefFree(def);
    VIR_FREE(vmx);
    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
3240
    VIR_FREE(escapedName);
M
Matthias Bolte 已提交
3241 3242 3243 3244 3245 3246 3247
    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);
3248
    VIR_FREE(taskInfoErrorMessage);
M
Matthias Bolte 已提交
3249 3250 3251 3252 3253 3254

    return domain;
}



3255 3256 3257
static int
esxDomainUndefine(virDomainPtr domain)
{
M
Matthias Bolte 已提交
3258
    int result = -1;
M
Matthias Bolte 已提交
3259
    esxPrivate *priv = domain->conn->privateData;
3260
    esxVI_Context *ctx = NULL;
3261 3262 3263 3264
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

3265 3266 3267 3268 3269 3270
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

3271
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
3272
        return -1;
3273 3274
    }

3275
    if (esxVI_String_AppendValueToList(&propertyNameList,
3276
                                       "runtime.powerState") < 0 ||
3277 3278
        esxVI_LookupVirtualMachineByUuid(ctx, domain->uuid, propertyNameList,
                                         &virtualMachine,
M
Matthias Bolte 已提交
3279
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3280
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
3281
        goto cleanup;
3282 3283 3284 3285
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended &&
        powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
3286 3287
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not suspended or powered off"));
M
Matthias Bolte 已提交
3288
        goto cleanup;
3289 3290
    }

3291
    if (esxVI_UnregisterVM(ctx, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
3292
        goto cleanup;
3293 3294
    }

M
Matthias Bolte 已提交
3295 3296
    result = 0;

3297 3298 3299 3300 3301 3302 3303 3304 3305
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



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 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484
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;
}



3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496
/*
 * 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)
 *
3497
 *   The amount of CPU resource that is guaranteed to be available to the domain.
3498 3499 3500 3501
 *
 *
 * - limit (VIR_DOMAIN_SCHED_FIELD_LLONG >= 0, or -1, in megaherz)
 *
3502 3503
 *   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
3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514
 *   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'.
 */
3515
static char *
3516
esxDomainGetSchedulerType(virDomainPtr domain ATTRIBUTE_UNUSED, int *nparams)
3517 3518 3519 3520
{
    char *type = strdup("allocation");

    if (type == NULL) {
3521
        virReportOOMError();
3522
        return NULL;
3523 3524
    }

3525 3526 3527
    if (nparams != NULL) {
        *nparams = 3; /* reservation, limit, shares */
    }
3528 3529 3530 3531 3532 3533 3534 3535 3536 3537

    return type;
}



static int
esxDomainGetSchedulerParameters(virDomainPtr domain,
                                virSchedParameterPtr params, int *nparams)
{
M
Matthias Bolte 已提交
3538
    int result = -1;
M
Matthias Bolte 已提交
3539
    esxPrivate *priv = domain->conn->privateData;
3540 3541 3542 3543 3544 3545 3546 3547
    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) {
3548 3549
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Parameter array must have space for 3 items"));
M
Matthias Bolte 已提交
3550
        return -1;
3551 3552
    }

3553
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3554
        return -1;
3555 3556
    }

3557
    if (esxVI_String_AppendValueListToList(&propertyNameList,
3558 3559 3560
                                           "config.cpuAllocation.reservation\0"
                                           "config.cpuAllocation.limit\0"
                                           "config.cpuAllocation.shares\0") < 0 ||
3561
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
3562
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3563
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3564
        goto cleanup;
3565 3566 3567 3568 3569 3570
    }

    for (dynamicProperty = virtualMachine->propSet;
         dynamicProperty != NULL && mask != 7 && i < 3;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.cpuAllocation.reservation") &&
M
Matthias Bolte 已提交
3571
            ! (mask & (1 << 0))) {
3572 3573 3574 3575 3576
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "reservation");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_LLONG;

3577
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3578
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3579
                goto cleanup;
3580 3581 3582 3583 3584 3585 3586
            }

            params[i].value.l = dynamicProperty->val->int64;
            mask |= 1 << 0;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.limit") &&
M
Matthias Bolte 已提交
3587
                   ! (mask & (1 << 1))) {
3588 3589 3590 3591 3592
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "limit");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_LLONG;

3593
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3594
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3595
                goto cleanup;
3596 3597 3598 3599 3600 3601 3602
            }

            params[i].value.l = dynamicProperty->val->int64;
            mask |= 1 << 1;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.shares") &&
M
Matthias Bolte 已提交
3603
                   ! (mask & (1 << 2))) {
3604 3605 3606 3607 3608
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "shares");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_INT;

3609
            if (esxVI_SharesInfo_CastFromAnyType(dynamicProperty->val,
3610
                                                 &sharesInfo) < 0) {
M
Matthias Bolte 已提交
3611
                goto cleanup;
3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631
            }

            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:
3632
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3633
                          _("Shares level has unknown value %d"),
3634
                          (int)sharesInfo->level);
M
Matthias Bolte 已提交
3635
                goto cleanup;
3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647
            }

            esxVI_SharesInfo_Free(&sharesInfo);

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

    *nparams = i;
M
Matthias Bolte 已提交
3648
    result = 0;
3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662

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

    return result;
}



static int
esxDomainSetSchedulerParameters(virDomainPtr domain,
                                virSchedParameterPtr params, int nparams)
{
M
Matthias Bolte 已提交
3663
    int result = -1;
M
Matthias Bolte 已提交
3664
    esxPrivate *priv = domain->conn->privateData;
3665 3666 3667 3668 3669
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3670
    char *taskInfoErrorMessage = NULL;
3671 3672
    int i;

3673
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3674
        return -1;
3675 3676
    }

3677
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3678
          (priv->primary, domain->uuid, NULL, &virtualMachine,
3679
           priv->parsedUri->autoAnswer) < 0 ||
3680 3681
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->cpuAllocation) < 0) {
M
Matthias Bolte 已提交
3682
        goto cleanup;
3683 3684 3685 3686 3687
    }

    for (i = 0; i < nparams; ++i) {
        if (STREQ (params[i].field, "reservation") &&
            params[i].type == VIR_DOMAIN_SCHED_FIELD_LLONG) {
3688
            if (esxVI_Long_Alloc(&spec->cpuAllocation->reservation) < 0) {
M
Matthias Bolte 已提交
3689
                goto cleanup;
3690 3691 3692
            }

            if (params[i].value.l < 0) {
3693
                ESX_ERROR(VIR_ERR_INVALID_ARG,
3694 3695
                          _("Could not set reservation to %lld MHz, expecting "
                            "positive value"), params[i].value.l);
M
Matthias Bolte 已提交
3696
                goto cleanup;
3697 3698 3699 3700 3701
            }

            spec->cpuAllocation->reservation->value = params[i].value.l;
        } else if (STREQ (params[i].field, "limit") &&
                   params[i].type == VIR_DOMAIN_SCHED_FIELD_LLONG) {
3702
            if (esxVI_Long_Alloc(&spec->cpuAllocation->limit) < 0) {
M
Matthias Bolte 已提交
3703
                goto cleanup;
3704 3705 3706
            }

            if (params[i].value.l < -1) {
3707
                ESX_ERROR(VIR_ERR_INVALID_ARG,
3708 3709
                          _("Could not set limit to %lld MHz, expecting "
                            "positive value or -1 (unlimited)"),
3710
                          params[i].value.l);
M
Matthias Bolte 已提交
3711
                goto cleanup;
3712 3713 3714 3715
            }

            spec->cpuAllocation->limit->value = params[i].value.l;
        } else if (STREQ (params[i].field, "shares") &&
3716
                   params[i].type == VIR_DOMAIN_SCHED_FIELD_INT) {
3717 3718
            if (esxVI_SharesInfo_Alloc(&sharesInfo) < 0 ||
                esxVI_Int_Alloc(&sharesInfo->shares) < 0) {
M
Matthias Bolte 已提交
3719
                goto cleanup;
3720 3721 3722 3723
            }

            spec->cpuAllocation->shares = sharesInfo;

3724
            if (params[i].value.i >= 0) {
3725
                spec->cpuAllocation->shares->level = esxVI_SharesLevel_Custom;
3726
                spec->cpuAllocation->shares->shares->value = params[i].value.i;
3727
            } else {
3728
                switch (params[i].value.i) {
3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746
                  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:
3747
                    ESX_ERROR(VIR_ERR_INVALID_ARG,
3748 3749
                              _("Could not set shares to %d, expecting positive "
                                "value or -1 (low), -2 (normal) or -3 (high)"),
3750
                              params[i].value.i);
M
Matthias Bolte 已提交
3751
                    goto cleanup;
3752 3753 3754
                }
            }
        } else {
3755
            ESX_ERROR(VIR_ERR_INVALID_ARG, _("Unknown field '%s'"),
3756
                      params[i].field);
M
Matthias Bolte 已提交
3757
            goto cleanup;
3758 3759 3760
        }
    }

3761
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
3762
                              &task) < 0 ||
3763
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3764
                                    esxVI_Occurrence_RequiredItem,
3765
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3766
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3767
        goto cleanup;
3768 3769 3770
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3771 3772 3773
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not change scheduler parameters: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
3774
        goto cleanup;
3775 3776
    }

M
Matthias Bolte 已提交
3777 3778
    result = 0;

3779 3780 3781 3782
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
3783
    VIR_FREE(taskInfoErrorMessage);
3784 3785 3786 3787 3788 3789 3790 3791 3792 3793

    return result;
}



static int
esxDomainMigratePrepare(virConnectPtr dconn,
                        char **cookie ATTRIBUTE_UNUSED,
                        int *cookielen ATTRIBUTE_UNUSED,
3794 3795
                        const char *uri_in ATTRIBUTE_UNUSED,
                        char **uri_out,
3796 3797 3798 3799
                        unsigned long flags ATTRIBUTE_UNUSED,
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
3800
    esxPrivate *priv = dconn->privateData;
3801 3802

    if (uri_in == NULL) {
3803 3804 3805 3806
        if (virAsprintf(uri_out, "vpxmigr://%s/%s/%s",
                        priv->vCenter->ipAddress,
                        priv->vCenter->computeResource->resourcePool->value,
                        priv->vCenter->hostSystem->_reference->value) < 0) {
3807
            virReportOOMError();
3808
            return -1;
3809 3810 3811
        }
    }

3812
    return 0;
3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825
}



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 已提交
3826
    int result = -1;
M
Matthias Bolte 已提交
3827
    esxPrivate *priv = domain->conn->privateData;
3828 3829 3830 3831
    xmlURIPtr parsedUri = NULL;
    char *saveptr;
    char *path_resourcePool;
    char *path_hostSystem;
3832
    esxVI_ObjectContent *virtualMachine = NULL;
3833 3834
    esxVI_ManagedObjectReference resourcePool;
    esxVI_ManagedObjectReference hostSystem;
3835 3836 3837
    esxVI_Event *eventList = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3838
    char *taskInfoErrorMessage = NULL;
3839

M
Matthias Bolte 已提交
3840
    if (priv->vCenter == NULL) {
3841 3842
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Migration not possible without a vCenter"));
M
Matthias Bolte 已提交
3843
        return -1;
3844 3845 3846
    }

    if (dname != NULL) {
3847 3848
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Renaming domains on migration not supported"));
M
Matthias Bolte 已提交
3849
        return -1;
3850 3851
    }

3852
    if (esxVI_EnsureSession(priv->vCenter) < 0) {
M
Matthias Bolte 已提交
3853
        return -1;
3854 3855
    }

3856 3857
    /* Parse migration URI */
    parsedUri = xmlParseURI(uri);
3858

3859
    if (parsedUri == NULL) {
3860
        virReportOOMError();
M
Matthias Bolte 已提交
3861
        return -1;
3862 3863
    }

3864 3865 3866
    if (parsedUri->scheme == NULL || STRCASENEQ(parsedUri->scheme, "vpxmigr")) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Only vpxmigr:// migration URIs are supported"));
M
Matthias Bolte 已提交
3867
        goto cleanup;
3868 3869
    }

3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882
    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 已提交
3883
        goto cleanup;
3884 3885
    }

3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898
    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,
3899
           priv->parsedUri->autoAnswer) < 0) {
M
Matthias Bolte 已提交
3900
        goto cleanup;
3901 3902 3903
    }

    /* Validate the purposed migration */
3904
    if (esxVI_ValidateMigration(priv->vCenter, virtualMachine->obj,
3905 3906
                                esxVI_VirtualMachinePowerState_Undefined, NULL,
                                &resourcePool, &hostSystem, &eventList) < 0) {
M
Matthias Bolte 已提交
3907
        goto cleanup;
3908 3909 3910 3911 3912 3913 3914 3915
    }

    if (eventList != NULL) {
        /*
         * FIXME: Need to report the complete list of events. Limit reporting
         *        to the first event for now.
         */
        if (eventList->fullFormattedMessage != NULL) {
3916
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3917 3918
                      _("Could not migrate domain, validation reported a "
                        "problem: %s"), eventList->fullFormattedMessage);
3919
        } else {
3920 3921 3922
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                      _("Could not migrate domain, validation reported a "
                        "problem"));
3923 3924
        }

M
Matthias Bolte 已提交
3925
        goto cleanup;
3926 3927 3928
    }

    /* Perform the purposed migration */
3929 3930
    if (esxVI_MigrateVM_Task(priv->vCenter, virtualMachine->obj,
                             &resourcePool, &hostSystem,
3931 3932 3933
                             esxVI_VirtualMachineMovePriority_DefaultPriority,
                             esxVI_VirtualMachinePowerState_Undefined,
                             &task) < 0 ||
3934
        esxVI_WaitForTaskCompletion(priv->vCenter, task, domain->uuid,
3935
                                    esxVI_Occurrence_RequiredItem,
3936
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3937
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3938
        goto cleanup;
3939 3940 3941
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3942
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3943
                  _("Could not migrate domain, migration task finished with "
3944 3945
                    "an error: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
3946
        goto cleanup;
3947 3948
    }

M
Matthias Bolte 已提交
3949 3950
    result = 0;

3951
  cleanup:
3952
    xmlFreeURI(parsedUri);
3953 3954 3955
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Event_Free(&eventList);
    esxVI_ManagedObjectReference_Free(&task);
3956
    VIR_FREE(taskInfoErrorMessage);
3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974

    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 已提交
3975 3976 3977 3978
static unsigned long long
esxNodeGetFreeMemory(virConnectPtr conn)
{
    unsigned long long result = 0;
M
Matthias Bolte 已提交
3979
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
3980 3981 3982 3983 3984
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *resourcePool = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ResourcePoolResourceUsage *resourcePoolResourceUsage = NULL;

3985
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3986
        return 0;
M
Matthias Bolte 已提交
3987 3988 3989
    }

    /* Get memory usage of resource pool */
3990
    if (esxVI_String_AppendValueToList(&propertyNameList,
M
Matthias Bolte 已提交
3991
                                       "runtime.memory") < 0 ||
3992 3993
        esxVI_LookupObjectContentByType(priv->primary,
                                        priv->primary->computeResource->resourcePool,
3994
                                        "ResourcePool", propertyNameList,
3995 3996
                                        &resourcePool,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3997
        goto cleanup;
M
Matthias Bolte 已提交
3998 3999 4000 4001 4002 4003
    }

    for (dynamicProperty = resourcePool->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.memory")) {
            if (esxVI_ResourcePoolResourceUsage_CastFromAnyType
4004
                  (dynamicProperty->val, &resourcePoolResourceUsage) < 0) {
M
Matthias Bolte 已提交
4005
                goto cleanup;
M
Matthias Bolte 已提交
4006 4007 4008 4009 4010 4011 4012 4013 4014
            }

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

    if (resourcePoolResourceUsage == NULL) {
4015 4016
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve memory usage of resource pool"));
M
Matthias Bolte 已提交
4017
        goto cleanup;
M
Matthias Bolte 已提交
4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031
    }

    result = resourcePoolResourceUsage->unreservedForVm->value;

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

    return result;
}



4032 4033 4034
static int
esxIsEncrypted(virConnectPtr conn)
{
M
Matthias Bolte 已提交
4035
    esxPrivate *priv = conn->privateData;
4036

4037
    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048
        return 1;
    } else {
        return 0;
    }
}



static int
esxIsSecure(virConnectPtr conn)
{
M
Matthias Bolte 已提交
4049
    esxPrivate *priv = conn->privateData;
4050

4051
    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062
        return 1;
    } else {
        return 0;
    }
}



static int
esxDomainIsActive(virDomainPtr domain)
{
M
Matthias Bolte 已提交
4063
    int result = -1;
M
Matthias Bolte 已提交
4064
    esxPrivate *priv = domain->conn->privateData;
4065 4066 4067 4068
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

4069
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4070
        return -1;
4071 4072
    }

4073
    if (esxVI_String_AppendValueToList(&propertyNameList,
4074
                                       "runtime.powerState") < 0 ||
4075
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
4076
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
4077
                                         esxVI_Occurrence_RequiredItem) < 0 ||
4078
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
4079
        goto cleanup;
4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103
    }

    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 已提交
4104 4105


4106 4107 4108 4109 4110
static int
esxDomainIsUpdated(virDomainPtr domain ATTRIBUTE_UNUSED)
{
    return 0;
}
4111

M
Matthias Bolte 已提交
4112 4113


4114 4115
static virDomainSnapshotPtr
esxDomainSnapshotCreateXML(virDomainPtr domain, const char *xmlDesc,
4116
                           unsigned int flags)
4117 4118 4119 4120 4121 4122 4123 4124 4125
{
    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;
4126
    char *taskInfoErrorMessage = NULL;
4127 4128
    virDomainSnapshotPtr snapshot = NULL;

4129 4130
    virCheckFlags(0, NULL);

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

    def = virDomainSnapshotDefParseString(xmlDesc, 1);

    if (def == NULL) {
M
Matthias Bolte 已提交
4138
        return NULL;
4139 4140 4141
    }

    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
4142
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4143
           priv->parsedUri->autoAnswer) < 0 ||
4144
        esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4145 4146 4147 4148
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, def->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4149
        goto cleanup;
4150 4151 4152 4153 4154
    }

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

4158
    if (esxVI_CreateSnapshot_Task(priv->primary, virtualMachine->obj,
4159 4160 4161
                                  def->name, def->description,
                                  esxVI_Boolean_True,
                                  esxVI_Boolean_False, &task) < 0 ||
4162
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
4163
                                    esxVI_Occurrence_RequiredItem,
4164
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4165
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4166
        goto cleanup;
4167 4168 4169
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4170 4171
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not create snapshot: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
4172
        goto cleanup;
4173 4174 4175 4176 4177 4178 4179 4180 4181
    }

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

  cleanup:
    virDomainSnapshotDefFree(def);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4182
    VIR_FREE(taskInfoErrorMessage);
4183 4184 4185 4186 4187 4188 4189

    return snapshot;
}



static char *
4190 4191
esxDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                            unsigned int flags)
4192 4193 4194 4195 4196 4197 4198 4199 4200
{
    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;

4201 4202
    virCheckFlags(0, NULL);

M
Matthias Bolte 已提交
4203
    memset(&def, 0, sizeof (def));
4204

4205
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4206
        return NULL;
4207 4208
    }

4209
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4210 4211 4212 4213
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4214
        goto cleanup;
4215 4216 4217 4218 4219 4220 4221 4222
    }

    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 已提交
4223
        goto cleanup;
4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241
    }

    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
4242
esxDomainSnapshotNum(virDomainPtr domain, unsigned int flags)
4243
{
M
Matthias Bolte 已提交
4244
    int count;
4245 4246 4247
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;

4248 4249
    virCheckFlags(0, -1);

4250
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4251
        return -1;
4252 4253
    }

4254
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4255
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4256
        return -1;
4257 4258
    }

M
Matthias Bolte 已提交
4259
    count = esxVI_GetNumberOfSnapshotTrees(rootSnapshotTreeList);
4260 4261 4262

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

M
Matthias Bolte 已提交
4263
    return count;
4264 4265 4266 4267 4268 4269
}



static int
esxDomainSnapshotListNames(virDomainPtr domain, char **names, int nameslen,
4270
                           unsigned int flags)
4271
{
M
Matthias Bolte 已提交
4272
    int result;
4273 4274 4275
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;

4276 4277
    virCheckFlags(0, -1);

4278 4279 4280 4281 4282 4283 4284 4285 4286
    if (names == NULL || nameslen < 0) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
    }

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

4287
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4288
        return -1;
4289 4290
    }

4291
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4292
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4293
        return -1;
4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306
    }

    result = esxVI_GetSnapshotTreeNames(rootSnapshotTreeList, names, nameslen);

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



static virDomainSnapshotPtr
esxDomainSnapshotLookupByName(virDomainPtr domain, const char *name,
4307
                              unsigned int flags)
4308 4309 4310 4311 4312 4313 4314
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    virDomainSnapshotPtr snapshot = NULL;

4315 4316
    virCheckFlags(0, NULL);

4317
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4318
        return NULL;
4319 4320
    }

4321
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344
                                         &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;

4345
    virCheckFlags(0, -1);
4346

4347
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4348
        return -1;
4349 4350
    }

4351
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4352 4353
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4354
        return -1;
4355 4356 4357
    }

    if (currentSnapshotTree != NULL) {
M
Matthias Bolte 已提交
4358 4359
        esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);
        return 1;
4360 4361
    }

M
Matthias Bolte 已提交
4362
    return 0;
4363 4364 4365 4366 4367 4368 4369 4370 4371
}



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

4374
    virCheckFlags(0, NULL);
4375

4376
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4377
        return NULL;
4378 4379
    }

4380
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4381 4382
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4383
        return NULL;
4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397
    }

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

    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return snapshot;
}



static int
esxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4398
    int result = -1;
4399 4400 4401 4402 4403 4404
    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;
4405
    char *taskInfoErrorMessage = NULL;
4406

4407
    virCheckFlags(0, -1);
4408

4409
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4410
        return -1;
4411 4412
    }

4413
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4414 4415 4416 4417
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4418
        goto cleanup;
4419 4420
    }

4421
    if (esxVI_RevertToSnapshot_Task(priv->primary, snapshotTree->snapshot, NULL,
4422
                                    &task) < 0 ||
4423
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4424
                                    esxVI_Occurrence_RequiredItem,
4425
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4426
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4427
        goto cleanup;
4428 4429 4430 4431
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
4432 4433
                  _("Could not revert to snapshot '%s': %s"), snapshot->name,
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
4434
        goto cleanup;
4435 4436
    }

M
Matthias Bolte 已提交
4437 4438
    result = 0;

4439 4440 4441
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4442
    VIR_FREE(taskInfoErrorMessage);
4443 4444 4445 4446 4447 4448 4449 4450 4451

    return result;
}



static int
esxDomainSnapshotDelete(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4452
    int result = -1;
4453 4454 4455 4456 4457 4458 4459
    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;
4460
    char *taskInfoErrorMessage = NULL;
4461

4462 4463
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN, -1);

4464
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4465
        return -1;
4466 4467 4468 4469 4470 4471
    }

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

4472
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4473 4474 4475 4476
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4477
        goto cleanup;
4478 4479
    }

4480
    if (esxVI_RemoveSnapshot_Task(priv->primary, snapshotTree->snapshot,
4481
                                  removeChildren, &task) < 0 ||
4482
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4483
                                    esxVI_Occurrence_RequiredItem,
4484
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4485
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4486
        goto cleanup;
4487 4488 4489 4490
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
4491 4492
                  _("Could not delete snapshot '%s': %s"), snapshot->name,
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
4493
        goto cleanup;
4494 4495
    }

M
Matthias Bolte 已提交
4496 4497
    result = 0;

4498 4499 4500
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4501
    VIR_FREE(taskInfoErrorMessage);
4502 4503 4504 4505 4506 4507

    return result;
}



4508 4509 4510 4511 4512 4513 4514 4515 4516 4517
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;
4518
    char *taskInfoErrorMessage = NULL;
4519 4520 4521 4522 4523 4524 4525 4526 4527 4528
    int i;

    virCheckFlags(0, -1);

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

    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4529
           priv->parsedUri->autoAnswer) < 0 ||
4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542
        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 =
4543
              VIR_DIV_UP(params[i].value.ul, 1024); /* Scale from kilobytes to megabytes */
4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554
        } 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,
4555
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4556
                                    &taskInfoErrorMessage) < 0) {
4557 4558 4559 4560
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4561 4562 4563
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not change memory parameters: %s"),
                  taskInfoErrorMessage);
4564 4565 4566 4567 4568 4569 4570 4571 4572
        goto cleanup;
    }

    result = 0;

  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
4573
    VIR_FREE(taskInfoErrorMessage);
4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640

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



4641
static virDriver esxDriver = {
4642 4643
    .no = VIR_DRV_ESX,
    .name = "ESX",
4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705
    .open = esxOpen, /* 0.7.0 */
    .close = esxClose, /* 0.7.0 */
    .supports_feature = esxSupportsFeature, /* 0.7.0 */
    .type = esxGetType, /* 0.7.0 */
    .version = esxGetVersion, /* 0.7.0 */
    .getHostname = esxGetHostname, /* 0.7.0 */
    .nodeGetInfo = esxNodeGetInfo, /* 0.7.0 */
    .getCapabilities = esxGetCapabilities, /* 0.7.1 */
    .listDomains = esxListDomains, /* 0.7.0 */
    .numOfDomains = esxNumberOfDomains, /* 0.7.0 */
    .domainLookupByID = esxDomainLookupByID, /* 0.7.0 */
    .domainLookupByUUID = esxDomainLookupByUUID, /* 0.7.0 */
    .domainLookupByName = esxDomainLookupByName, /* 0.7.0 */
    .domainSuspend = esxDomainSuspend, /* 0.7.0 */
    .domainResume = esxDomainResume, /* 0.7.0 */
    .domainShutdown = esxDomainShutdown, /* 0.7.0 */
    .domainReboot = esxDomainReboot, /* 0.7.0 */
    .domainDestroy = esxDomainDestroy, /* 0.7.0 */
    .domainGetOSType = esxDomainGetOSType, /* 0.7.0 */
    .domainGetMaxMemory = esxDomainGetMaxMemory, /* 0.7.0 */
    .domainSetMaxMemory = esxDomainSetMaxMemory, /* 0.7.0 */
    .domainSetMemory = esxDomainSetMemory, /* 0.7.0 */
    .domainSetMemoryParameters = esxDomainSetMemoryParameters, /* 0.8.6 */
    .domainGetMemoryParameters = esxDomainGetMemoryParameters, /* 0.8.6 */
    .domainGetInfo = esxDomainGetInfo, /* 0.7.0 */
    .domainGetState = esxDomainGetState, /* 0.9.2 */
    .domainSetVcpus = esxDomainSetVcpus, /* 0.7.0 */
    .domainSetVcpusFlags = esxDomainSetVcpusFlags, /* 0.8.5 */
    .domainGetVcpusFlags = esxDomainGetVcpusFlags, /* 0.8.5 */
    .domainGetMaxVcpus = esxDomainGetMaxVcpus, /* 0.7.0 */
    .domainGetXMLDesc = esxDomainGetXMLDesc, /* 0.7.0 */
    .domainXMLFromNative = esxDomainXMLFromNative, /* 0.7.0 */
    .domainXMLToNative = esxDomainXMLToNative, /* 0.7.2 */
    .listDefinedDomains = esxListDefinedDomains, /* 0.7.0 */
    .numOfDefinedDomains = esxNumberOfDefinedDomains, /* 0.7.0 */
    .domainCreate = esxDomainCreate, /* 0.7.0 */
    .domainCreateWithFlags = esxDomainCreateWithFlags, /* 0.8.2 */
    .domainDefineXML = esxDomainDefineXML, /* 0.7.2 */
    .domainUndefine = esxDomainUndefine, /* 0.7.1 */
    .domainGetAutostart = esxDomainGetAutostart, /* 0.9.0 */
    .domainSetAutostart = esxDomainSetAutostart, /* 0.9.0 */
    .domainGetSchedulerType = esxDomainGetSchedulerType, /* 0.7.0 */
    .domainGetSchedulerParameters = esxDomainGetSchedulerParameters, /* 0.7.0 */
    .domainSetSchedulerParameters = esxDomainSetSchedulerParameters, /* 0.7.0 */
    .domainMigratePrepare = esxDomainMigratePrepare, /* 0.7.0 */
    .domainMigratePerform = esxDomainMigratePerform, /* 0.7.0 */
    .domainMigrateFinish = esxDomainMigrateFinish, /* 0.7.0 */
    .nodeGetFreeMemory = esxNodeGetFreeMemory, /* 0.7.2 */
    .isEncrypted = esxIsEncrypted, /* 0.7.3 */
    .isSecure = esxIsSecure, /* 0.7.3 */
    .domainIsActive = esxDomainIsActive, /* 0.7.3 */
    .domainIsPersistent = esxDomainIsPersistent, /* 0.7.3 */
    .domainIsUpdated = esxDomainIsUpdated, /* 0.8.6 */
    .domainSnapshotCreateXML = esxDomainSnapshotCreateXML, /* 0.8.0 */
    .domainSnapshotGetXMLDesc = esxDomainSnapshotGetXMLDesc, /* 0.8.0 */
    .domainSnapshotNum = esxDomainSnapshotNum, /* 0.8.0 */
    .domainSnapshotListNames = esxDomainSnapshotListNames, /* 0.8.0 */
    .domainSnapshotLookupByName = esxDomainSnapshotLookupByName, /* 0.8.0 */
    .domainHasCurrentSnapshot = esxDomainHasCurrentSnapshot, /* 0.8.0 */
    .domainSnapshotCurrent = esxDomainSnapshotCurrent, /* 0.8.0 */
    .domainRevertToSnapshot = esxDomainRevertToSnapshot, /* 0.8.0 */
    .domainSnapshotDelete = esxDomainSnapshotDelete, /* 0.8.0 */
4706 4707 4708 4709 4710 4711 4712
};



int
esxRegister(void)
{
4713 4714 4715 4716 4717
    if (virRegisterDriver(&esxDriver) < 0 ||
        esxInterfaceRegister() < 0 ||
        esxNetworkRegister() < 0 ||
        esxStorageRegister() < 0 ||
        esxDeviceRegister() < 0 ||
M
Matthias Bolte 已提交
4718 4719
        esxSecretRegister() < 0 ||
        esxNWFilterRegister() < 0) {
4720 4721
        return -1;
    }
4722 4723 4724

    return 0;
}