esx_driver.c 150.4 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
 * Parse a file name from a .vmx file and convert it to datastore path format
 * if possbile. A .vmx file can contain file names in various formats:
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
 *
 * - 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
 *
100 101 102 103 104 105 106 107
 * - There might also be absolute file names referencing files outside of a
 *   datastore:
 *
 *     /usr/lib/vmware/isoimages/linux.iso
 *
 *   Such file names are left as is and are not converted to datastore path
 *   format because this is not possible.
 *
108 109 110 111 112 113 114
 * 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
115
 * function via the opaque parameter by the caller of virVMXParseConfig.
116 117 118 119 120 121 122 123 124
 *
 * 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.
 */
125
static char *
126
esxParseVMXFileName(const char *fileName, void *opaque)
127
{
128
    char *result = NULL;
129
    esxVMX_Data *data = opaque;
130
    esxVI_String *propertyNameList = NULL;
131
    esxVI_ObjectContent *datastoreList = NULL;
132
    esxVI_ObjectContent *datastore = NULL;
133 134 135 136 137 138 139 140 141 142
    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 */
143
        if (virAsprintf(&result, "%s/%s",
144
                        data->datastorePathWithoutFileName, fileName) < 0) {
145 146 147 148 149 150 151 152 153 154
            virReportOOMError();
            goto cleanup;
        }
    } else {
        if (esxVI_String_AppendValueToList(&propertyNameList,
                                           "summary.name") < 0 ||
            esxVI_LookupDatastoreList(data->ctx, propertyNameList,
                                      &datastoreList) < 0) {
            return NULL;
        }
155

156 157 158 159 160
        /* Search for datastore by mount path */
        for (datastore = datastoreList; datastore != NULL;
             datastore = datastore->_next) {
            esxVI_DatastoreHostMount_Free(&hostMount);
            datastoreName = NULL;
161

162 163 164 165 166 167
            if (esxVI_LookupDatastoreHostMount(data->ctx, datastore->obj,
                                               &hostMount) < 0 ||
                esxVI_GetStringValue(datastore, "summary.name", &datastoreName,
                                     esxVI_Occurrence_RequiredItem) < 0) {
                goto cleanup;
            }
168

169
            tmp = (char *)STRSKIP(fileName, hostMount->mountInfo->path);
170

171 172 173
            if (tmp == NULL) {
                continue;
            }
174

175 176 177 178
            /* Found a match. Strip leading separators */
            while (*tmp == '/' || *tmp == '\\') {
                ++tmp;
            }
179

180 181 182
            if (esxVI_String_DeepCopyValue(&strippedFileName, tmp) < 0) {
                goto cleanup;
            }
183

184
            tmp = strippedFileName;
185

186 187 188 189 190
            /* Convert \ to / */
            while (*tmp != '\0') {
                if (*tmp == '\\') {
                    *tmp = '/';
                }
191

192 193
                ++tmp;
            }
194

195
            if (virAsprintf(&result, "[%s] %s", datastoreName,
196 197 198 199
                            strippedFileName) < 0) {
                virReportOOMError();
                goto cleanup;
            }
200

201 202
            break;
        }
203

204
        /* Fallback to direct datastore name match */
205
        if (result == NULL && STRPREFIX(fileName, "/vmfs/volumes/")) {
206 207 208
            if (esxVI_String_DeepCopyValue(&copyOfFileName, fileName) < 0) {
                goto cleanup;
            }
209

210 211 212 213 214 215 216 217 218
            /* 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;
            }
219

220
            esxVI_ObjectContent_Free(&datastoreList);
221

222 223 224 225 226
            if (esxVI_LookupDatastoreByName(data->ctx, datastoreName,
                                            NULL, &datastoreList,
                                            esxVI_Occurrence_OptionalItem) < 0) {
                goto cleanup;
            }
227

228 229 230 231 232 233
            if (datastoreList == NULL) {
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                          _("File name '%s' refers to non-existing datastore '%s'"),
                          fileName, datastoreName);
                goto cleanup;
            }
234

235
            if (virAsprintf(&result, "[%s] %s", datastoreName,
236 237 238 239
                            directoryAndFileName) < 0) {
                virReportOOMError();
                goto cleanup;
            }
240 241
        }

242 243 244 245 246 247 248 249 250
        /* If it's an absolute path outside of a datastore just use it as is */
        if (result == NULL && *fileName == '/') {
            /* FIXME: need to deal with Windows paths here too */
            if (esxVI_String_DeepCopyValue(&result, fileName) < 0) {
                goto cleanup;
            }
        }

        if (result == NULL) {
251
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
252
                      _("Could not handle file name '%s'"), fileName);
253
            goto cleanup;
254
        }
255
    }
256

257 258 259 260 261 262
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&datastoreList);
    esxVI_DatastoreHostMount_Free(&hostMount);
    VIR_FREE(strippedFileName);
    VIR_FREE(copyOfFileName);
263

264
    return result;
265 266 267 268
}



269 270
/*
 * This function does the inverse of esxParseVMXFileName. It takes an file name
271 272
 * in datastore path format or in absolute format and converts it to a file
 * name that can be used in a .vmx file.
273 274 275 276 277 278 279 280 281
 *
 * 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.
 */
282
static char *
283
esxFormatVMXFileName(const char *fileName, void *opaque)
284 285
{
    bool success = false;
286
    char *result = NULL;
287
    esxVMX_Data *data = opaque;
288
    char *datastoreName = NULL;
289
    char *directoryAndFileName = NULL;
290 291 292 293 294
    esxVI_ObjectContent *datastore = NULL;
    esxVI_DatastoreHostMount *hostMount = NULL;
    char separator = '/';
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    char *tmp;
295
    size_t length;
296

297 298 299 300 301 302
    if (*fileName == '[') {
        /* Parse datastore path and lookup datastore */
        if (esxUtil_ParseDatastorePath(fileName, &datastoreName, NULL,
                                       &directoryAndFileName) < 0) {
            goto cleanup;
        }
303

304 305 306 307 308 309
        if (esxVI_LookupDatastoreByName(data->ctx, datastoreName, NULL, &datastore,
                                        esxVI_Occurrence_RequiredItem) < 0 ||
            esxVI_LookupDatastoreHostMount(data->ctx, datastore->obj,
                                           &hostMount) < 0) {
            goto cleanup;
        }
310

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

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

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

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

326 327
        if (separator != '/') {
            tmp = directoryAndFileName;
328

329 330 331 332
            while (*tmp != '\0') {
                if (*tmp == '/') {
                    *tmp = separator;
                }
333

334 335
                ++tmp;
            }
336
        }
337

338 339
        virBufferAddChar(&buffer, separator);
        virBufferAdd(&buffer, directoryAndFileName, -1);
340

341 342 343 344 345 346 347 348 349 350 351 352 353 354
        if (virBufferError(&buffer)) {
            virReportOOMError();
            goto cleanup;
        }

        result = virBufferContentAndReset(&buffer);
    } else if (*fileName == '/') {
        /* FIXME: need to deal with Windows paths here too */
        if (esxVI_String_DeepCopyValue(&result, fileName) < 0) {
            goto cleanup;
        }
    } else {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not handle file name '%s'"), fileName);
355 356 357 358 359 360 361 362 363
        goto cleanup;
    }

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

    success = true;

  cleanup:
    if (! success) {
364
        virBufferFreeAndReset(&buffer);
365
        VIR_FREE(result);
366 367 368
    }

    VIR_FREE(datastoreName);
369
    VIR_FREE(directoryAndFileName);
370 371
    esxVI_ObjectContent_Free(&datastore);
    esxVI_DatastoreHostMount_Free(&hostMount);
372

373
    return result;
374 375 376 377 378 379 380 381 382 383
}



static int
esxAutodetectSCSIControllerModel(virDomainDiskDefPtr def, int *model,
                                 void *opaque)
{
    int result = -1;
    esxVMX_Data *data = opaque;
384
    esxVI_FileInfo *fileInfo = NULL;
385 386 387 388 389 390 391 392 393 394 395 396 397 398
    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;
    }

399 400
    if (esxVI_LookupFileInfoByDatastorePath(data->ctx, def->src,
                                            false, &fileInfo,
401
                                            esxVI_Occurrence_RequiredItem) < 0) {
402 403 404
        goto cleanup;
    }

405
    vmDiskFileInfo = esxVI_VmDiskFileInfo_DynamicCast(fileInfo);
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434

    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:
435
    esxVI_FileInfo_Free(&fileInfo);
436 437 438 439

    return result;
}

440 441


442
static esxVI_Boolean
443
esxSupportsLongMode(esxPrivate *priv)
444 445 446 447 448 449
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_HostCpuIdInfo *hostCpuIdInfoList = NULL;
    esxVI_HostCpuIdInfo *hostCpuIdInfo = NULL;
450
    esxVI_ParsedHostCpuIdInfo parsedHostCpuIdInfo;
451 452 453 454 455 456
    char edxLongModeBit = '?';

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

457
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
458
        return esxVI_Boolean_Undefined;
459 460
    }

461
    if (esxVI_String_AppendValueToList(&propertyNameList,
462
                                       "hardware.cpuFeature") < 0 ||
463 464
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
465
        goto cleanup;
466 467 468
    }

    if (hostSystem == NULL) {
469 470
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
471
        goto cleanup;
472 473 474 475 476 477
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuFeature")) {
            if (esxVI_HostCpuIdInfo_CastListFromAnyType
478
                  (dynamicProperty->val, &hostCpuIdInfoList) < 0) {
M
Matthias Bolte 已提交
479
                goto cleanup;
480 481 482 483 484
            }

            for (hostCpuIdInfo = hostCpuIdInfoList; hostCpuIdInfo != NULL;
                 hostCpuIdInfo = hostCpuIdInfo->_next) {
                if (hostCpuIdInfo->level->value == -2147483647) { /* 0x80000001 */
485 486
                    if (esxVI_ParseHostCpuIdInfo(&parsedHostCpuIdInfo,
                                                 hostCpuIdInfo) < 0) {
M
Matthias Bolte 已提交
487
                        goto cleanup;
488 489
                    }

490
                    edxLongModeBit = parsedHostCpuIdInfo.edx[29];
491 492 493 494 495 496

                    if (edxLongModeBit == '1') {
                        priv->supportsLongMode = esxVI_Boolean_True;
                    } else if (edxLongModeBit == '0') {
                        priv->supportsLongMode = esxVI_Boolean_False;
                    } else {
497
                        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
498 499 500 501
                                  _("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 已提交
502
                        goto cleanup;
503 504 505 506 507 508 509 510 511 512 513 514 515
                    }

                    break;
                }
            }

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

  cleanup:
M
Matthias Bolte 已提交
516 517 518 519
    /*
     * 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.
     */
520 521 522 523 524 525 526 527 528
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_HostCpuIdInfo_Free(&hostCpuIdInfoList);

    return priv->supportsLongMode;
}



529 530 531 532 533 534 535 536
static int
esxLookupHostSystemBiosUuid(esxPrivate *priv, unsigned char *uuid)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

537
    if (esxVI_EnsureSession(priv->primary) < 0) {
538 539 540 541 542
        return -1;
    }

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "hardware.systemInfo.uuid") < 0 ||
543 544
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
        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) {
564 565 566 567 568
                    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);
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
                }
            } 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;
}



592
static virCapsPtr
593
esxCapsInit(esxPrivate *priv)
594
{
595
    esxVI_Boolean supportsLongMode = esxSupportsLongMode(priv);
596 597 598
    virCapsPtr caps = NULL;
    virCapsGuestPtr guest = NULL;

599 600 601 602 603 604 605 606 607
    if (supportsLongMode == esxVI_Boolean_Undefined) {
        return NULL;
    }

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

    if (caps == NULL) {
610
        virReportOOMError();
611 612 613
        return NULL;
    }

614
    virCapabilitiesSetMacPrefix(caps, (unsigned char[]){ 0x00, 0x0c, 0x29 });
615
    virCapabilitiesAddHostMigrateTransport(caps, "vpxmigr");
616

617 618
    caps->hasWideScsiBus = true;

619 620 621 622
    if (esxLookupHostSystemBiosUuid(priv, caps->host.host_uuid) < 0) {
        goto failure;
    }

623 624 625
    /* i686 */
    guest = virCapabilitiesAddGuest(caps, "hvm", "i686", 32, NULL, NULL, 0,
                                    NULL);
626 627 628 629 630 631 632 633 634 635

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

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

636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
    /* 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;
        }
    }

651 652 653 654 655 656 657 658 659 660
    return caps;

  failure:
    virCapabilitiesFree(caps);

    return NULL;
}



661 662 663 664 665 666 667 668 669 670
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 已提交
671
    char *unescapedPassword = NULL;
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
    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 已提交
703
    unescapedPassword = virRequestPassword(auth, username, hostname);
704

M
Matthias Bolte 已提交
705
    if (unescapedPassword == NULL) {
706 707 708 709
        ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
        goto cleanup;
    }

M
Matthias Bolte 已提交
710 711 712 713 714 715
    password = esxUtil_EscapeForXml(unescapedPassword);

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

716 717
    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->parsedUri->transport,
                    hostname, port) < 0) {
718 719 720 721 722 723
        virReportOOMError();
        goto cleanup;
    }

    if (esxVI_Context_Alloc(&priv->host) < 0 ||
        esxVI_Context_Connect(priv->host, url, ipAddress, username, password,
724 725
                              priv->parsedUri) < 0 ||
        esxVI_Context_LookupObjectsByPath(priv->host, priv->parsedUri) < 0) {
726 727 728 729 730
        goto cleanup;
    }

    if (expectedProductVersion == esxVI_ProductVersion_ESX) {
        if (priv->host->productVersion != esxVI_ProductVersion_ESX35 &&
M
Matthias Bolte 已提交
731 732 733
            priv->host->productVersion != esxVI_ProductVersion_ESX40 &&
            priv->host->productVersion != esxVI_ProductVersion_ESX41 &&
            priv->host->productVersion != esxVI_ProductVersion_ESX4x) {
734
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
M
Matthias Bolte 已提交
735
                      _("%s is neither an ESX 3.5 host nor an ESX 4.x host"),
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
                      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 ||
751 752
        esxVI_LookupHostSystemProperties(priv->host, propertyNameList,
                                         &hostSystem) < 0 ||
753 754 755 756 757 758 759 760 761 762 763
        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) {
764
        VIR_WARN("The server is in maintenance mode");
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
    }

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

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

    result = 0;

  cleanup:
    VIR_FREE(username);
M
Matthias Bolte 已提交
780 781
    VIR_FREE(unescapedPassword);
    VIR_FREE(password);
782 783 784 785 786 787 788 789 790 791 792 793 794
    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,
795
                    const char *hostSystemIpAddress)
796 797 798 799
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
M
Matthias Bolte 已提交
800
    char *unescapedPassword = NULL;
801 802 803
    char *password = NULL;
    char *url = NULL;

804
    if (hostSystemIpAddress == NULL &&
805 806
        (priv->parsedUri->path_datacenter == NULL ||
         priv->parsedUri->path_computeResource == NULL)) {
807 808 809 810 811
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Path has to specify the datacenter and compute resource"));
        return -1;
    }

812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
    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 已提交
832
    unescapedPassword = virRequestPassword(auth, username, hostname);
833

M
Matthias Bolte 已提交
834
    if (unescapedPassword == NULL) {
835 836 837 838
        ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
        goto cleanup;
    }

M
Matthias Bolte 已提交
839 840 841 842 843 844
    password = esxUtil_EscapeForXml(unescapedPassword);

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

845 846
    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->parsedUri->transport,
                    hostname, port) < 0) {
847 848 849 850 851 852
        virReportOOMError();
        goto cleanup;
    }

    if (esxVI_Context_Alloc(&priv->vCenter) < 0 ||
        esxVI_Context_Connect(priv->vCenter, url, ipAddress, username,
853
                              password, priv->parsedUri) < 0) {
854 855 856 857
        goto cleanup;
    }

    if (priv->vCenter->productVersion != esxVI_ProductVersion_VPX25 &&
M
Matthias Bolte 已提交
858 859 860
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX40 &&
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX41 &&
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX4x) {
861 862
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("%s is neither a vCenter 2.5 server nor a vCenter "
M
Matthias Bolte 已提交
863
                    "4.x server"), hostname);
864 865 866
        goto cleanup;
    }

867 868 869 870 871 872
    if (hostSystemIpAddress != NULL) {
        if (esxVI_Context_LookupObjectsByHostSystemIp(priv->vCenter,
                                                      hostSystemIpAddress) < 0) {
            goto cleanup;
        }
    } else {
873 874
        if (esxVI_Context_LookupObjectsByPath(priv->vCenter,
                                              priv->parsedUri) < 0) {
875 876 877 878
            goto cleanup;
        }
    }

879 880 881 882
    result = 0;

  cleanup:
    VIR_FREE(username);
M
Matthias Bolte 已提交
883 884
    VIR_FREE(unescapedPassword);
    VIR_FREE(password);
885 886 887 888 889 890 891
    VIR_FREE(url);

    return result;
}



892
/*
893 894
 * URI format: {vpx|esx|gsx}://[<username>@]<hostname>[:<port>]/[<path>][?<query parameter> ...]
 *             <path> = <datacenter>/<computeresource>[/<hostsystem>]
895
 *
896 897
 * If no port is specified the default port is set dependent on the scheme and
 * transport parameter:
898 899
 * - vpx+http  80
 * - vpx+https 443
900
 * - esx+http  80
901
 * - esx+https 443
902 903 904
 * - gsx+http  8222
 * - gsx+https 8333
 *
905 906 907 908 909
 * 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.
 *
910 911
 * Optional query parameters:
 * - transport={http|https}
912
 * - vcenter={<vcenter>|*}             only useful for an esx:// connection
913 914
 * - no_verify={0|1}
 * - auto_answer={0|1}
M
Matthias Bolte 已提交
915
 * - proxy=[{http|socks|socks4|socks4a|socks5}://]<hostname>[:<port>]
916
 *
917 918 919
 * If no transport parameter is specified https is used.
 *
 * The vcenter parameter is only necessary for migration, because the vCenter
920
 * server is in charge to initiate a migration between two ESX hosts. The
921
 * vcenter parameter can be set to an explicitly hostname or to *. If set to *,
922 923
 * 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.
924 925
 *
 * If the no_verify parameter is set to 1, this disables libcurl client checks
926
 * of the server's certificate. The default value it 0.
927 928 929 930
 *
 * 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 已提交
931 932 933 934
 *
 * 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.
935 936
 */
static virDrvOpenStatus
937
esxOpen(virConnectPtr conn, virConnectAuthPtr auth,
E
Eric Blake 已提交
938
        unsigned int flags)
939
{
M
Matthias Bolte 已提交
940
    virDrvOpenStatus result = VIR_DRV_OPEN_ERROR;
941
    esxPrivate *priv = NULL;
942
    char *potentialVCenterIpAddress = NULL;
M
Matthias Bolte 已提交
943
    char vCenterIpAddress[NI_MAXHOST] = "";
944

E
Eric Blake 已提交
945 946
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

947
    /* Decline if the URI is NULL or the scheme is not one of {vpx|esx|gsx} */
948
    if (conn->uri == NULL || conn->uri->scheme == NULL ||
949 950
        (STRCASENEQ(conn->uri->scheme, "vpx") &&
         STRCASENEQ(conn->uri->scheme, "esx") &&
951
         STRCASENEQ(conn->uri->scheme, "gsx"))) {
952 953 954
        return VIR_DRV_OPEN_DECLINED;
    }

955 956 957 958 959 960 961 962 963 964 965 966
    /* 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;
967 968 969 970
    }

    /* Allocate per-connection private data */
    if (VIR_ALLOC(priv) < 0) {
971
        virReportOOMError();
M
Matthias Bolte 已提交
972
        goto cleanup;
973 974
    }

975
    if (esxUtil_ParseUri(&priv->parsedUri, conn->uri) < 0) {
976 977 978
        goto cleanup;
    }

M
Matthias Bolte 已提交
979 980
    priv->maxVcpus = -1;
    priv->supportsVMotion = esxVI_Boolean_Undefined;
981
    priv->supportsLongMode = esxVI_Boolean_Undefined;
982 983
    priv->usedCpuTimeCounterId = -1;

M
Matthias Bolte 已提交
984 985 986 987 988 989 990
    /*
     * 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) {
991 992
        if (STRCASEEQ(conn->uri->scheme, "vpx") ||
            STRCASEEQ(conn->uri->scheme, "esx")) {
993
            if (STRCASEEQ(priv->parsedUri->transport, "https")) {
M
Matthias Bolte 已提交
994 995 996 997 998
                conn->uri->port = 443;
            } else {
                conn->uri->port = 80;
            }
        } else { /* GSX */
999
            if (STRCASEEQ(priv->parsedUri->transport, "https")) {
M
Matthias Bolte 已提交
1000 1001 1002 1003
                conn->uri->port = 8333;
            } else {
                conn->uri->port = 8222;
            }
1004
        }
M
Matthias Bolte 已提交
1005
    }
1006

1007 1008 1009 1010
    if (STRCASEEQ(conn->uri->scheme, "esx") ||
        STRCASEEQ(conn->uri->scheme, "gsx")) {
        /* Connect to host */
        if (esxConnectToHost(priv, auth, conn->uri->server, conn->uri->port,
1011
                             conn->uri->user,
1012 1013 1014 1015
                             STRCASEEQ(conn->uri->scheme, "esx")
                               ? esxVI_ProductVersion_ESX
                               : esxVI_ProductVersion_GSX,
                             &potentialVCenterIpAddress) < 0) {
M
Matthias Bolte 已提交
1016
            goto cleanup;
1017
        }
1018

1019
        /* Connect to vCenter */
1020 1021
        if (priv->parsedUri->vCenter != NULL) {
            if (STREQ(priv->parsedUri->vCenter, "*")) {
1022 1023 1024
                if (potentialVCenterIpAddress == NULL) {
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                              _("This host is not managed by a vCenter"));
M
Matthias Bolte 已提交
1025
                    goto cleanup;
1026 1027
                }

1028 1029 1030 1031 1032 1033 1034 1035
                if (virStrcpyStatic(vCenterIpAddress,
                                    potentialVCenterIpAddress) == NULL) {
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                              _("vCenter IP address %s too big for destination"),
                              potentialVCenterIpAddress);
                    goto cleanup;
                }
            } else {
1036
                if (esxUtil_ResolveHostname(priv->parsedUri->vCenter,
1037 1038 1039
                                            vCenterIpAddress, NI_MAXHOST) < 0) {
                    goto cleanup;
                }
1040

1041 1042
                if (potentialVCenterIpAddress != NULL &&
                    STRNEQ(vCenterIpAddress, potentialVCenterIpAddress)) {
1043
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1044 1045 1046
                              _("This host is managed by a vCenter with IP "
                                "address %s, but a mismachting vCenter '%s' "
                                "(%s) has been specified"),
1047
                              potentialVCenterIpAddress, priv->parsedUri->vCenter,
1048
                              vCenterIpAddress);
M
Matthias Bolte 已提交
1049
                    goto cleanup;
1050 1051
                }
            }
1052

1053
            if (esxConnectToVCenter(priv, auth, vCenterIpAddress,
1054
                                    conn->uri->port, NULL,
1055
                                    priv->host->ipAddress) < 0) {
1056 1057
                goto cleanup;
            }
1058 1059
        }

1060 1061 1062 1063
        priv->primary = priv->host;
    } else { /* VPX */
        /* Connect to vCenter */
        if (esxConnectToVCenter(priv, auth, conn->uri->server, conn->uri->port,
1064
                                conn->uri->user, NULL) < 0) {
M
Matthias Bolte 已提交
1065
            goto cleanup;
1066 1067
        }

1068
        priv->primary = priv->vCenter;
1069 1070
    }

M
Matthias Bolte 已提交
1071
    /* Setup capabilities */
1072
    priv->caps = esxCapsInit(priv);
1073

M
Matthias Bolte 已提交
1074
    if (priv->caps == NULL) {
M
Matthias Bolte 已提交
1075
        goto cleanup;
1076 1077
    }

1078 1079
    conn->privateData = priv;

M
Matthias Bolte 已提交
1080
    result = VIR_DRV_OPEN_SUCCESS;
1081

M
Matthias Bolte 已提交
1082
  cleanup:
1083 1084
    if (result == VIR_DRV_OPEN_ERROR) {
        esxFreePrivate(&priv);
1085 1086
    }

1087
    VIR_FREE(potentialVCenterIpAddress);
1088

M
Matthias Bolte 已提交
1089
    return result;
1090 1091 1092 1093 1094 1095 1096
}



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

1100 1101 1102 1103 1104 1105
    if (priv->host != NULL) {
        if (esxVI_EnsureSession(priv->host) < 0 ||
            esxVI_Logout(priv->host) < 0) {
            result = -1;
        }
    }
1106

M
Matthias Bolte 已提交
1107
    if (priv->vCenter != NULL) {
E
Eric Blake 已提交
1108 1109 1110 1111
        if (esxVI_EnsureSession(priv->vCenter) < 0 ||
            esxVI_Logout(priv->vCenter) < 0) {
            result = -1;
        }
1112 1113
    }

1114
    esxFreePrivate(&priv);
1115 1116 1117

    conn->privateData = NULL;

E
Eric Blake 已提交
1118
    return result;
1119 1120 1121 1122 1123
}



static esxVI_Boolean
1124
esxSupportsVMotion(esxPrivate *priv)
1125 1126 1127 1128
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;

M
Matthias Bolte 已提交
1129 1130
    if (priv->supportsVMotion != esxVI_Boolean_Undefined) {
        return priv->supportsVMotion;
1131 1132
    }

1133
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1134
        return esxVI_Boolean_Undefined;
1135 1136
    }

1137
    if (esxVI_String_AppendValueToList(&propertyNameList,
1138
                                       "capability.vmotionSupported") < 0 ||
1139 1140
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1141
        goto cleanup;
1142 1143 1144
    }

    if (hostSystem == NULL) {
1145 1146
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
1147
        goto cleanup;
1148 1149
    }

1150 1151 1152 1153
    if (esxVI_GetBoolean(hostSystem, "capability.vmotionSupported",
                         &priv->supportsVMotion,
                         esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
1154 1155 1156
    }

  cleanup:
M
Matthias Bolte 已提交
1157 1158 1159 1160
    /*
     * 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.
     */
1161 1162 1163
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
1164
    return priv->supportsVMotion;
1165 1166 1167 1168 1169 1170 1171
}



static int
esxSupportsFeature(virConnectPtr conn, int feature)
{
M
Matthias Bolte 已提交
1172
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1173
    esxVI_Boolean supportsVMotion = esxVI_Boolean_Undefined;
1174 1175 1176

    switch (feature) {
      case VIR_DRV_FEATURE_MIGRATION_V1:
1177
        supportsVMotion = esxSupportsVMotion(priv);
1178

M
Matthias Bolte 已提交
1179
        if (supportsVMotion == esxVI_Boolean_Undefined) {
1180 1181 1182
            return -1;
        }

M
Matthias Bolte 已提交
1183 1184 1185
        /* Migration is only possible via a vCenter and if VMotion is enabled */
        return priv->vCenter != NULL &&
               supportsVMotion == esxVI_Boolean_True ? 1 : 0;
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204

      default:
        return 0;
    }
}



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



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

1207
    if (virParseVersionString(priv->primary->service->about->version,
1208
                              version, false) < 0) {
1209
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1210
                  _("Could not parse version number from '%s'"),
1211
                  priv->primary->service->about->version);
1212

1213
        return -1;
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
    }

    return 0;
}



static char *
esxGetHostname(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1224
    esxPrivate *priv = conn->privateData;
1225 1226 1227 1228 1229 1230 1231
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    const char *hostName = NULL;
    const char *domainName = NULL;
    char *complete = NULL;

1232
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1233
        return NULL;
1234 1235 1236
    }

    if (esxVI_String_AppendValueListToList
1237
          (&propertyNameList,
1238 1239
           "config.network.dnsConfig.hostName\0"
           "config.network.dnsConfig.domainName\0") < 0 ||
1240 1241
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1242
        goto cleanup;
1243 1244 1245
    }

    if (hostSystem == NULL) {
1246 1247
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
1248
        goto cleanup;
1249 1250 1251 1252 1253 1254
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name,
                  "config.network.dnsConfig.hostName")) {
1255
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1256
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1257
                goto cleanup;
1258 1259 1260 1261 1262
            }

            hostName = dynamicProperty->val->string;
        } else if (STREQ(dynamicProperty->name,
                         "config.network.dnsConfig.domainName")) {
1263
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1264
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1265
                goto cleanup;
1266 1267 1268 1269 1270 1271 1272 1273
            }

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

M
Matthias Bolte 已提交
1274
    if (hostName == NULL || strlen(hostName) < 1) {
1275 1276
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Missing or empty 'hostName' property"));
M
Matthias Bolte 已提交
1277
        goto cleanup;
1278 1279
    }

M
Matthias Bolte 已提交
1280
    if (domainName == NULL || strlen(domainName) < 1) {
1281
        complete = strdup(hostName);
1282

1283
        if (complete == NULL) {
1284
            virReportOOMError();
M
Matthias Bolte 已提交
1285
            goto cleanup;
1286 1287 1288
        }
    } else {
        if (virAsprintf(&complete, "%s.%s", hostName, domainName) < 0) {
1289
            virReportOOMError();
M
Matthias Bolte 已提交
1290
            goto cleanup;
1291
        }
1292 1293 1294
    }

  cleanup:
M
Matthias Bolte 已提交
1295 1296 1297 1298 1299
    /*
     * 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
     */
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return complete;
}



static int
esxNodeGetInfo(virConnectPtr conn, virNodeInfoPtr nodeinfo)
{
M
Matthias Bolte 已提交
1311
    int result = -1;
M
Matthias Bolte 已提交
1312
    esxPrivate *priv = conn->privateData;
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
    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 已提交
1324
    memset(nodeinfo, 0, sizeof (*nodeinfo));
1325

1326
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1327
        return -1;
1328 1329
    }

1330
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1331 1332 1333 1334 1335 1336 1337
                                           "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 ||
1338 1339
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1340
        goto cleanup;
1341 1342 1343
    }

    if (hostSystem == NULL) {
1344 1345
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
1346
        goto cleanup;
1347 1348 1349 1350 1351
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuInfo.hz")) {
1352
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1353
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1354
                goto cleanup;
1355 1356 1357 1358 1359
            }

            cpuInfo_hz = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuCores")) {
1360
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1361
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1362
                goto cleanup;
1363 1364 1365 1366 1367
            }

            cpuInfo_numCpuCores = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuPackages")) {
1368
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1369
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1370
                goto cleanup;
1371 1372 1373 1374 1375
            }

            cpuInfo_numCpuPackages = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuThreads")) {
1376
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1377
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1378
                goto cleanup;
1379 1380 1381 1382
            }

            cpuInfo_numCpuThreads = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name, "hardware.memorySize")) {
1383
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1384
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1385
                goto cleanup;
1386 1387 1388 1389 1390
            }

            memorySize = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.numaInfo.numNodes")) {
1391
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1392
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1393
                goto cleanup;
1394 1395 1396 1397 1398
            }

            numaInfo_numNodes = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "summary.hardware.cpuModel")) {
1399
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1400
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1401
                goto cleanup;
1402 1403 1404 1405 1406 1407
            }

            ptr = dynamicProperty->val->string;

            /* Strip the string to fit more relevant information in 32 chars */
            while (*ptr != '\0') {
M
Matthias Bolte 已提交
1408 1409
                if (STRPREFIX(ptr, "  ")) {
                    memmove(ptr, ptr + 1, strlen(ptr + 1) + 1);
1410
                    continue;
1411
                } else if (STRPREFIX(ptr, "(R)") || STRPREFIX(ptr, "(C)")) {
M
Matthias Bolte 已提交
1412
                    memmove(ptr, ptr + 3, strlen(ptr + 3) + 1);
1413
                    continue;
1414 1415 1416
                } else if (STRPREFIX(ptr, "(TM)")) {
                    memmove(ptr, ptr + 4, strlen(ptr + 4) + 1);
                    continue;
1417 1418 1419 1420 1421
                }

                ++ptr;
            }

C
Chris Lalancette 已提交
1422 1423 1424
            if (virStrncpy(nodeinfo->model, dynamicProperty->val->string,
                           sizeof(nodeinfo->model) - 1,
                           sizeof(nodeinfo->model)) == NULL) {
1425
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1426
                          _("CPU Model %s too long for destination"),
C
Chris Lalancette 已提交
1427
                          dynamicProperty->val->string);
M
Matthias Bolte 已提交
1428
                goto cleanup;
C
Chris Lalancette 已提交
1429
            }
1430 1431 1432 1433 1434 1435 1436
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    nodeinfo->memory = memorySize / 1024; /* Scale from bytes to kilobytes */
    nodeinfo->cpus = cpuInfo_numCpuCores;
1437
    nodeinfo->mhz = cpuInfo_hz / (1000 * 1000); /* Scale from hz to mhz */
1438 1439 1440 1441 1442 1443 1444 1445 1446
    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 已提交
1447 1448
    result = 0;

1449 1450 1451 1452 1453 1454 1455 1456 1457
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



1458 1459 1460
static char *
esxGetCapabilities(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1461
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1462
    char *xml = virCapabilitiesFormatXML(priv->caps);
1463 1464

    if (xml == NULL) {
1465
        virReportOOMError();
1466 1467 1468 1469 1470 1471 1472 1473
        return NULL;
    }

    return xml;
}



1474 1475 1476
static int
esxListDomains(virConnectPtr conn, int *ids, int maxids)
{
M
Matthias Bolte 已提交
1477
    bool success = false;
M
Matthias Bolte 已提交
1478
    esxPrivate *priv = conn->privateData;
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;

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

1489
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1490
        return -1;
1491 1492
    }

1493
    if (esxVI_String_AppendValueToList(&propertyNameList,
1494
                                       "runtime.powerState") < 0 ||
1495 1496
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1497
        goto cleanup;
1498 1499 1500 1501
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
1502
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1503
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1504
            goto cleanup;
1505 1506 1507 1508 1509 1510 1511 1512 1513
        }

        if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

        if (esxUtil_ParseVirtualMachineIDString(virtualMachine->obj->value,
                                                &ids[count]) < 0 ||
            ids[count] <= 0) {
1514
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1515
                      _("Failed to parse positive integer from '%s'"),
1516
                      virtualMachine->obj->value);
M
Matthias Bolte 已提交
1517
            goto cleanup;
1518 1519 1520 1521 1522 1523 1524 1525 1526
        }

        count++;

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

M
Matthias Bolte 已提交
1527 1528
    success = true;

1529 1530 1531 1532
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
1533
    return success ? count : -1;
1534 1535 1536 1537 1538 1539 1540
}



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

1543
    if (esxVI_EnsureSession(priv->primary) < 0) {
1544 1545 1546
        return -1;
    }

1547
    return esxVI_LookupNumberOfDomainsByPowerState
1548
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, false);
1549 1550 1551 1552 1553 1554 1555
}



static virDomainPtr
esxDomainLookupByID(virConnectPtr conn, int id)
{
M
Matthias Bolte 已提交
1556
    esxPrivate *priv = conn->privateData;
1557 1558 1559 1560
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
M
Matthias Bolte 已提交
1561 1562 1563
    int id_candidate = -1;
    char *name_candidate = NULL;
    unsigned char uuid_candidate[VIR_UUID_BUFLEN];
1564 1565
    virDomainPtr domain = NULL;

1566
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1567
        return NULL;
1568 1569
    }

1570
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1571
                                           "configStatus\0"
1572 1573
                                           "name\0"
                                           "runtime.powerState\0"
1574
                                           "config.uuid\0") < 0 ||
1575 1576
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1577
        goto cleanup;
1578 1579 1580 1581
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
1582
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1583
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1584
            goto cleanup;
1585 1586 1587 1588 1589 1590 1591
        }

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

M
Matthias Bolte 已提交
1592
        VIR_FREE(name_candidate);
1593

1594
        if (esxVI_GetVirtualMachineIdentity(virtualMachine,
M
Matthias Bolte 已提交
1595 1596
                                            &id_candidate, &name_candidate,
                                            uuid_candidate) < 0) {
M
Matthias Bolte 已提交
1597
            goto cleanup;
1598 1599
        }

M
Matthias Bolte 已提交
1600
        if (id != id_candidate) {
1601 1602 1603
            continue;
        }

M
Matthias Bolte 已提交
1604
        domain = virGetDomain(conn, name_candidate, uuid_candidate);
1605 1606

        if (domain == NULL) {
M
Matthias Bolte 已提交
1607
            goto cleanup;
1608 1609 1610 1611 1612 1613 1614 1615
        }

        domain->id = id;

        break;
    }

    if (domain == NULL) {
1616
        ESX_ERROR(VIR_ERR_NO_DOMAIN, _("No domain with ID %d"), id);
1617 1618 1619 1620 1621
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
M
Matthias Bolte 已提交
1622
    VIR_FREE(name_candidate);
1623 1624 1625 1626 1627 1628 1629 1630 1631

    return domain;
}



static virDomainPtr
esxDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
M
Matthias Bolte 已提交
1632
    esxPrivate *priv = conn->privateData;
1633 1634 1635
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1636 1637
    int id = -1;
    char *name = NULL;
1638 1639
    virDomainPtr domain = NULL;

1640
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1641
        return NULL;
1642 1643
    }

1644
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1645
                                           "name\0"
1646
                                           "runtime.powerState\0") < 0 ||
1647
        esxVI_LookupVirtualMachineByUuid(priv->primary, uuid, propertyNameList,
1648
                                         &virtualMachine,
M
Matthias Bolte 已提交
1649
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1650 1651
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, &name, NULL) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1652
        goto cleanup;
1653 1654
    }

1655
    domain = virGetDomain(conn, name, uuid);
1656 1657

    if (domain == NULL) {
M
Matthias Bolte 已提交
1658
        goto cleanup;
1659
    }
1660

1661 1662 1663 1664 1665
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1666 1667 1668 1669
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1670 1671
    esxVI_ObjectContent_Free(&virtualMachine);
    VIR_FREE(name);
1672 1673 1674 1675 1676 1677 1678 1679 1680

    return domain;
}



static virDomainPtr
esxDomainLookupByName(virConnectPtr conn, const char *name)
{
M
Matthias Bolte 已提交
1681
    esxPrivate *priv = conn->privateData;
1682 1683 1684
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1685 1686
    int id = -1;
    unsigned char uuid[VIR_UUID_BUFLEN];
1687 1688
    virDomainPtr domain = NULL;

1689
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1690
        return NULL;
1691 1692
    }

1693
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1694
                                           "configStatus\0"
1695
                                           "runtime.powerState\0"
1696
                                           "config.uuid\0") < 0 ||
1697
        esxVI_LookupVirtualMachineByName(priv->primary, name, propertyNameList,
1698 1699
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
1700
        goto cleanup;
1701 1702
    }

1703
    if (virtualMachine == NULL) {
1704
        ESX_ERROR(VIR_ERR_NO_DOMAIN, _("No domain with name '%s'"), name);
M
Matthias Bolte 已提交
1705
        goto cleanup;
1706
    }
1707

M
Matthias Bolte 已提交
1708 1709 1710
    if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, uuid) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
1711
    }
1712

1713
    domain = virGetDomain(conn, name, uuid);
1714

1715
    if (domain == NULL) {
M
Matthias Bolte 已提交
1716
        goto cleanup;
1717 1718
    }

1719 1720 1721 1722 1723
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1724 1725 1726 1727
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1728
    esxVI_ObjectContent_Free(&virtualMachine);
1729 1730 1731 1732 1733 1734 1735 1736 1737

    return domain;
}



static int
esxDomainSuspend(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1738
    int result = -1;
M
Matthias Bolte 已提交
1739
    esxPrivate *priv = domain->conn->privateData;
1740 1741 1742 1743 1744
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1745
    char *taskInfoErrorMessage = NULL;
1746

1747
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1748
        return -1;
1749 1750
    }

1751
    if (esxVI_String_AppendValueToList(&propertyNameList,
1752
                                       "runtime.powerState") < 0 ||
1753
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1754
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1755
           priv->parsedUri->autoAnswer) < 0 ||
1756
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1757
        goto cleanup;
1758 1759 1760
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1761 1762
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1763
        goto cleanup;
1764 1765
    }

1766 1767
    if (esxVI_SuspendVM_Task(priv->primary, virtualMachine->obj, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1768
                                    esxVI_Occurrence_RequiredItem,
1769
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1770
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1771
        goto cleanup;
1772 1773 1774
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1775 1776
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not suspend domain: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
1777
        goto cleanup;
1778 1779
    }

M
Matthias Bolte 已提交
1780 1781
    result = 0;

1782 1783 1784 1785
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1786
    VIR_FREE(taskInfoErrorMessage);
1787 1788 1789 1790 1791 1792 1793 1794 1795

    return result;
}



static int
esxDomainResume(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1796
    int result = -1;
M
Matthias Bolte 已提交
1797
    esxPrivate *priv = domain->conn->privateData;
1798 1799 1800 1801 1802
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1803
    char *taskInfoErrorMessage = NULL;
1804

1805
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1806
        return -1;
1807 1808
    }

1809
    if (esxVI_String_AppendValueToList(&propertyNameList,
1810
                                       "runtime.powerState") < 0 ||
1811
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1812
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1813
           priv->parsedUri->autoAnswer) < 0 ||
1814
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1815
        goto cleanup;
1816 1817 1818
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended) {
1819
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not suspended"));
M
Matthias Bolte 已提交
1820
        goto cleanup;
1821 1822
    }

1823
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
1824
                             &task) < 0 ||
1825
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1826
                                    esxVI_Occurrence_RequiredItem,
1827
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1828
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1829
        goto cleanup;
1830 1831 1832
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1833 1834
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not resume domain: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
1835
        goto cleanup;
1836 1837
    }

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

1840 1841 1842 1843
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1844
    VIR_FREE(taskInfoErrorMessage);
1845 1846 1847 1848 1849 1850 1851 1852 1853

    return result;
}



static int
esxDomainShutdown(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1854
    int result = -1;
M
Matthias Bolte 已提交
1855
    esxPrivate *priv = domain->conn->privateData;
1856 1857 1858 1859
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

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

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

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

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

M
Matthias Bolte 已提交
1883 1884
    result = 0;

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

    return result;
}



static int
E
Eric Blake 已提交
1895
esxDomainReboot(virDomainPtr domain, unsigned int flags)
1896
{
M
Matthias Bolte 已提交
1897
    int result = -1;
M
Matthias Bolte 已提交
1898
    esxPrivate *priv = domain->conn->privateData;
1899 1900 1901 1902
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

E
Eric Blake 已提交
1903 1904
    virCheckFlags(0, -1);

1905
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1906
        return -1;
1907 1908
    }

1909
    if (esxVI_String_AppendValueToList(&propertyNameList,
1910
                                       "runtime.powerState") < 0 ||
1911
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1912
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1913
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1914
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1915
        goto cleanup;
1916 1917 1918
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1919 1920
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1921
        goto cleanup;
1922 1923
    }

1924
    if (esxVI_RebootGuest(priv->primary, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1925
        goto cleanup;
1926 1927
    }

M
Matthias Bolte 已提交
1928 1929
    result = 0;

1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
esxDomainDestroy(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1942
    int result = -1;
M
Matthias Bolte 已提交
1943
    esxPrivate *priv = domain->conn->privateData;
1944
    esxVI_Context *ctx = NULL;
1945 1946 1947 1948 1949
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1950
    char *taskInfoErrorMessage = NULL;
1951

1952 1953 1954 1955 1956 1957
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

1958
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
1959
        return -1;
1960 1961
    }

1962
    if (esxVI_String_AppendValueToList(&propertyNameList,
1963
                                       "runtime.powerState") < 0 ||
1964
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1965
          (ctx, domain->uuid, propertyNameList, &virtualMachine,
1966
           priv->parsedUri->autoAnswer) < 0 ||
1967
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1968
        goto cleanup;
1969 1970 1971
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1972 1973
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1974
        goto cleanup;
1975 1976
    }

1977
    if (esxVI_PowerOffVM_Task(ctx, virtualMachine->obj, &task) < 0 ||
1978 1979
        esxVI_WaitForTaskCompletion(ctx, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
1980
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1981
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1982
        goto cleanup;
1983 1984 1985
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1986 1987
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not destroy domain: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
1988
        goto cleanup;
1989 1990
    }

1991
    domain->id = -1;
M
Matthias Bolte 已提交
1992 1993
    result = 0;

1994 1995 1996 1997
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1998
    VIR_FREE(taskInfoErrorMessage);
1999 2000 2001 2002 2003 2004 2005

    return result;
}



static char *
2006
esxDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED)
2007
{
2008 2009 2010
    char *osType = strdup("hvm");

    if (osType == NULL) {
2011
        virReportOOMError();
2012 2013 2014 2015
        return NULL;
    }

    return osType;
2016 2017 2018 2019 2020 2021 2022
}



static unsigned long
esxDomainGetMaxMemory(virDomainPtr domain)
{
M
Matthias Bolte 已提交
2023
    esxPrivate *priv = domain->conn->privateData;
2024 2025 2026 2027 2028
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    unsigned long memoryMB = 0;

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

2033
    if (esxVI_String_AppendValueToList(&propertyNameList,
2034
                                       "config.hardware.memoryMB") < 0 ||
2035
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2036
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2037
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2038
        goto cleanup;
2039 2040 2041 2042 2043
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2044
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2045
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2046
                goto cleanup;
2047 2048 2049
            }

            if (dynamicProperty->val->int32 < 0) {
2050 2051
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                          _("Got invalid memory size %d"),
2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074
                          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 已提交
2075
    int result = -1;
M
Matthias Bolte 已提交
2076
    esxPrivate *priv = domain->conn->privateData;
2077
    esxVI_String *propertyNameList = NULL;
2078
    esxVI_ObjectContent *virtualMachine = NULL;
2079
    esxVI_VirtualMachinePowerState powerState;
2080 2081 2082
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2083
    char *taskInfoErrorMessage = NULL;
2084

2085
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2086
        return -1;
2087 2088
    }

2089 2090 2091 2092
    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "runtime.powerState") < 0 ||
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
2093
           priv->parsedUri->autoAnswer) < 0 ||
2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104
        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 ||
2105
        esxVI_Long_Alloc(&spec->memoryMB) < 0) {
M
Matthias Bolte 已提交
2106
        goto cleanup;
2107 2108
    }

2109
    /* max-memory must be a multiple of 4096 kilobyte */
2110
    spec->memoryMB->value =
2111
      VIR_DIV_UP(memory, 4096) * 4; /* Scale from kilobytes to megabytes */
2112

2113
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2114
                              &task) < 0 ||
2115
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2116
                                    esxVI_Occurrence_RequiredItem,
2117
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2118
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2119
        goto cleanup;
2120 2121 2122
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2123
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2124 2125
                  _("Could not set max-memory to %lu kilobytes: %s"), memory,
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
2126
        goto cleanup;
2127 2128
    }

M
Matthias Bolte 已提交
2129 2130
    result = 0;

2131
  cleanup:
2132
    esxVI_String_Free(&propertyNameList);
2133 2134 2135
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2136
    VIR_FREE(taskInfoErrorMessage);
2137 2138 2139 2140 2141 2142 2143 2144 2145

    return result;
}



static int
esxDomainSetMemory(virDomainPtr domain, unsigned long memory)
{
M
Matthias Bolte 已提交
2146
    int result = -1;
M
Matthias Bolte 已提交
2147
    esxPrivate *priv = domain->conn->privateData;
2148 2149 2150 2151
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2152
    char *taskInfoErrorMessage = NULL;
2153

2154
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2155
        return -1;
2156 2157
    }

2158
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2159
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2160
           priv->parsedUri->autoAnswer) < 0 ||
2161 2162 2163
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0 ||
        esxVI_Long_Alloc(&spec->memoryAllocation->limit) < 0) {
M
Matthias Bolte 已提交
2164
        goto cleanup;
2165 2166 2167
    }

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

2170
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2171
                              &task) < 0 ||
2172
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2173
                                    esxVI_Occurrence_RequiredItem,
2174
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2175
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2176
        goto cleanup;
2177 2178 2179
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2180
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2181 2182
                  _("Could not set memory to %lu kilobytes: %s"), memory,
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
2183
        goto cleanup;
2184 2185
    }

M
Matthias Bolte 已提交
2186 2187
    result = 0;

2188 2189 2190 2191
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2192
    VIR_FREE(taskInfoErrorMessage);
2193 2194 2195 2196 2197 2198

    return result;
}



2199 2200 2201 2202 2203 2204 2205 2206 2207
/*
 * 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

2208 2209 2210
static int
esxDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info)
{
M
Matthias Bolte 已提交
2211
    int result = -1;
M
Matthias Bolte 已提交
2212
    esxPrivate *priv = domain->conn->privateData;
2213 2214 2215 2216 2217
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int64_t memory_limit = -1;
2218
#if ESX_QUERY_FOR_USED_CPU_TIME
2219 2220 2221 2222 2223 2224 2225
    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;
2226 2227
    esxVI_PerfEntityMetricBase *perfEntityMetricBase = NULL;
    esxVI_PerfEntityMetricBase *perfEntityMetricBaseList = NULL;
2228 2229 2230
    esxVI_PerfEntityMetric *perfEntityMetric = NULL;
    esxVI_PerfMetricIntSeries *perfMetricIntSeries = NULL;
    esxVI_Long *value = NULL;
2231
#endif
2232

M
Matthias Bolte 已提交
2233 2234
    memset(info, 0, sizeof (*info));

2235
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2236
        return -1;
2237 2238
    }

2239
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2240 2241 2242 2243
                                           "runtime.powerState\0"
                                           "config.hardware.memoryMB\0"
                                           "config.hardware.numCPU\0"
                                           "config.memoryAllocation.limit\0") < 0 ||
2244
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2245
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2246
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2247
        goto cleanup;
2248 2249 2250 2251 2252 2253 2254 2255
    }

    info->state = VIR_DOMAIN_NOSTATE;

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

2260 2261
            info->state = esxVI_VirtualMachinePowerState_ConvertToLibvirt
                            (powerState);
2262
        } else if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2263
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2264
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2265
                goto cleanup;
2266 2267 2268 2269
            }

            info->maxMem = dynamicProperty->val->int32 * 1024; /* Scale from megabyte to kilobyte */
        } else if (STREQ(dynamicProperty->name, "config.hardware.numCPU")) {
2270
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2271
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2272
                goto cleanup;
2273 2274 2275 2276 2277
            }

            info->nrVirtCpu = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "config.memoryAllocation.limit")) {
2278
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2279
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
2280
                goto cleanup;
2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295
            }

            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;

2296
#if ESX_QUERY_FOR_USED_CPU_TIME
2297
    /* Verify the cached 'used CPU time' performance counter ID */
2298 2299 2300 2301 2302 2303
    /* 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;
            }
2304

2305
            counterId->value = priv->usedCpuTimeCounterId;
2306

2307 2308 2309
            if (esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                goto cleanup;
            }
2310

2311 2312 2313 2314
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfo) < 0) {
                goto cleanup;
            }
2315

2316 2317 2318 2319 2320
            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);
2321

2322 2323 2324 2325 2326
                priv->usedCpuTimeCounterId = -1;
            }

            esxVI_Int_Free(&counterIdList);
            esxVI_PerfCounterInfo_Free(&perfCounterInfo);
2327 2328
        }

2329 2330 2331 2332 2333 2334 2335 2336 2337 2338
        /*
         * 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;
            }
2339

2340 2341 2342 2343
            for (perfMetricId = perfMetricIdList; perfMetricId != NULL;
                 perfMetricId = perfMetricId->_next) {
                VIR_DEBUG("perfMetricId counterId %d, instance '%s'",
                          perfMetricId->counterId->value, perfMetricId->instance);
2344

2345
                counterId = NULL;
2346

2347 2348 2349 2350 2351
                if (esxVI_Int_DeepCopy(&counterId, perfMetricId->counterId) < 0 ||
                    esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                    goto cleanup;
                }
            }
2352

2353 2354
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfoList) < 0) {
M
Matthias Bolte 已提交
2355
                goto cleanup;
2356 2357
            }

2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374
            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;
                }
2375 2376
            }

2377
            if (priv->usedCpuTimeCounterId < 0) {
2378
                VIR_WARN("Could not find 'used CPU time' performance counter");
2379
            }
2380 2381
        }

2382 2383 2384 2385 2386 2387
        /*
         * 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);
2388

2389 2390 2391 2392 2393 2394
            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;
            }
2395

2396 2397 2398 2399 2400 2401 2402 2403 2404 2405
            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;
            }
2406

2407 2408 2409
            for (perfEntityMetricBase = perfEntityMetricBaseList;
                 perfEntityMetricBase != NULL;
                 perfEntityMetricBase = perfEntityMetricBase->_next) {
2410
                VIR_DEBUG("perfEntityMetric ...");
2411

2412 2413
                perfEntityMetric =
                  esxVI_PerfEntityMetric_DynamicCast(perfEntityMetricBase);
2414

2415
                if (perfEntityMetric == NULL) {
2416 2417
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                              _("QueryPerf returned object with unexpected type '%s'"),
2418
                              esxVI_Type_ToString(perfEntityMetricBase->_type));
2419
                    goto cleanup;
2420
                }
2421

2422 2423
                perfMetricIntSeries =
                  esxVI_PerfMetricIntSeries_DynamicCast(perfEntityMetric->value);
2424

2425
                if (perfMetricIntSeries == NULL) {
2426 2427
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                              _("QueryPerf returned object with unexpected type '%s'"),
2428
                              esxVI_Type_ToString(perfEntityMetric->value->_type));
2429
                    goto cleanup;
2430
                }
2431

2432 2433
                for (; perfMetricIntSeries != NULL;
                     perfMetricIntSeries = perfMetricIntSeries->_next) {
2434
                    VIR_DEBUG("perfMetricIntSeries ...");
2435

2436 2437 2438 2439 2440
                    for (value = perfMetricIntSeries->value;
                         value != NULL;
                         value = value->_next) {
                        VIR_DEBUG("value %lld", (long long int)value->value);
                    }
2441 2442 2443
                }
            }

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

2446
            /*
E
Eric Blake 已提交
2447
             * FIXME: Cannot map between relative used-cpu-time and absolute
2448 2449 2450
             *        info->cpuTime
             */
        }
2451
    }
2452
#endif
2453

M
Matthias Bolte 已提交
2454 2455
    result = 0;

2456
  cleanup:
2457
#if ESX_QUERY_FOR_USED_CPU_TIME
2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469
    /*
     * 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;
        }
    }
2470
#endif
2471

2472 2473
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2474
#if ESX_QUERY_FOR_USED_CPU_TIME
2475 2476 2477 2478
    esxVI_PerfMetricId_Free(&perfMetricIdList);
    esxVI_Int_Free(&counterIdList);
    esxVI_PerfCounterInfo_Free(&perfCounterInfoList);
    esxVI_PerfQuerySpec_Free(&querySpec);
2479
    esxVI_PerfEntityMetricBase_Free(&perfEntityMetricBaseList);
2480
#endif
2481 2482 2483 2484 2485 2486

    return result;
}



2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529
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;
}



2530
static int
2531 2532
esxDomainSetVcpusFlags(virDomainPtr domain, unsigned int nvcpus,
                       unsigned int flags)
2533
{
M
Matthias Bolte 已提交
2534
    int result = -1;
M
Matthias Bolte 已提交
2535
    esxPrivate *priv = domain->conn->privateData;
M
Matthias Bolte 已提交
2536
    int maxVcpus;
2537 2538 2539 2540
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2541
    char *taskInfoErrorMessage = NULL;
2542

2543
    if (flags != VIR_DOMAIN_AFFECT_LIVE) {
2544 2545 2546 2547
        ESX_ERROR(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
        return -1;
    }

2548
    if (nvcpus < 1) {
2549 2550
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Requested number of virtual CPUs must at least be 1"));
M
Matthias Bolte 已提交
2551
        return -1;
2552 2553
    }

2554
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2555
        return -1;
2556 2557
    }

M
Matthias Bolte 已提交
2558
    maxVcpus = esxDomainGetMaxVcpus(domain);
2559

M
Matthias Bolte 已提交
2560
    if (maxVcpus < 0) {
M
Matthias Bolte 已提交
2561
        return -1;
2562 2563
    }

M
Matthias Bolte 已提交
2564
    if (nvcpus > maxVcpus) {
2565
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2566 2567
                  _("Requested number of virtual CPUs is greater than max "
                    "allowable number of virtual CPUs for the domain: %d > %d"),
M
Matthias Bolte 已提交
2568
                  nvcpus, maxVcpus);
M
Matthias Bolte 已提交
2569
        return -1;
2570 2571
    }

2572
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2573
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2574
           priv->parsedUri->autoAnswer) < 0 ||
2575 2576
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Int_Alloc(&spec->numCPUs) < 0) {
M
Matthias Bolte 已提交
2577
        goto cleanup;
2578 2579 2580 2581
    }

    spec->numCPUs->value = nvcpus;

2582
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2583
                              &task) < 0 ||
2584
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2585
                                    esxVI_Occurrence_RequiredItem,
2586
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2587
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2588
        goto cleanup;
2589 2590 2591
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2592
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2593 2594
                  _("Could not set number of virtual CPUs to %d: %s"), nvcpus,
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
2595
        goto cleanup;
2596 2597
    }

M
Matthias Bolte 已提交
2598 2599
    result = 0;

2600 2601 2602 2603
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2604
    VIR_FREE(taskInfoErrorMessage);
2605 2606 2607 2608 2609

    return result;
}


M
Matthias Bolte 已提交
2610

2611 2612 2613
static int
esxDomainSetVcpus(virDomainPtr domain, unsigned int nvcpus)
{
2614
    return esxDomainSetVcpusFlags(domain, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
2615 2616
}

2617

M
Matthias Bolte 已提交
2618

2619
static int
2620
esxDomainGetVcpusFlags(virDomainPtr domain, unsigned int flags)
2621
{
M
Matthias Bolte 已提交
2622
    esxPrivate *priv = domain->conn->privateData;
2623 2624 2625 2626
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

2627
    if (flags != (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_VCPU_MAXIMUM)) {
2628 2629 2630 2631
        ESX_ERROR(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
        return -1;
    }

M
Matthias Bolte 已提交
2632 2633
    if (priv->maxVcpus > 0) {
        return priv->maxVcpus;
2634 2635
    }

M
Matthias Bolte 已提交
2636 2637
    priv->maxVcpus = -1;

2638
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2639
        return -1;
2640 2641
    }

2642
    if (esxVI_String_AppendValueToList(&propertyNameList,
2643
                                       "capability.maxSupportedVcpus") < 0 ||
2644 2645
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
2646
        goto cleanup;
2647 2648 2649
    }

    if (hostSystem == NULL) {
2650 2651
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
2652
        goto cleanup;
2653 2654 2655 2656 2657
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "capability.maxSupportedVcpus")) {
2658
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2659
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2660
                goto cleanup;
2661 2662
            }

M
Matthias Bolte 已提交
2663
            priv->maxVcpus = dynamicProperty->val->int32;
2664 2665 2666 2667 2668 2669 2670 2671 2672 2673
            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

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

M
Matthias Bolte 已提交
2674
    return priv->maxVcpus;
2675 2676
}

M
Matthias Bolte 已提交
2677 2678


2679 2680 2681
static int
esxDomainGetMaxVcpus(virDomainPtr domain)
{
2682
    return esxDomainGetVcpusFlags(domain, (VIR_DOMAIN_AFFECT_LIVE |
2683 2684
                                           VIR_DOMAIN_VCPU_MAXIMUM));
}
2685

M
Matthias Bolte 已提交
2686 2687


2688
static char *
2689
esxDomainGetXMLDesc(virDomainPtr domain, unsigned int flags)
2690
{
M
Matthias Bolte 已提交
2691
    esxPrivate *priv = domain->conn->privateData;
2692 2693
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
2694 2695
    esxVI_VirtualMachinePowerState powerState;
    int id;
2696
    char *vmPathName = NULL;
2697
    char *datastoreName = NULL;
M
Matthias Bolte 已提交
2698
    char *directoryName = NULL;
2699
    char *directoryAndFileName = NULL;
2700
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
2701 2702
    char *url = NULL;
    char *vmx = NULL;
2703
    virVMXContext ctx;
2704
    esxVMX_Data data;
2705 2706 2707
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2708 2709
    /* Flags checked by virDomainDefFormat */

2710 2711
    memset(&data, 0, sizeof (data));

2712
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2713
        return NULL;
2714 2715
    }

2716 2717 2718
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "config.files.vmPathName\0"
                                           "runtime.powerState\0") < 0 ||
2719
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2720
                                         propertyNameList, &virtualMachine,
2721
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2722 2723
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0 ||
2724 2725
        esxVI_GetStringValue(virtualMachine, "config.files.vmPathName",
                             &vmPathName, esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2726
        goto cleanup;
2727 2728
    }

2729
    if (esxUtil_ParseDatastorePath(vmPathName, &datastoreName, &directoryName,
2730
                                   &directoryAndFileName) < 0) {
M
Matthias Bolte 已提交
2731
        goto cleanup;
2732 2733
    }

2734
    virBufferAsprintf(&buffer, "%s://%s:%d/folder/", priv->parsedUri->transport,
2735
                      domain->conn->uri->server, domain->conn->uri->port);
2736
    virBufferURIEncodeString(&buffer, directoryAndFileName);
2737
    virBufferAddLit(&buffer, "?dcPath=");
2738
    virBufferURIEncodeString(&buffer, priv->primary->datacenter->name);
2739 2740 2741 2742
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
2743
        virReportOOMError();
M
Matthias Bolte 已提交
2744
        goto cleanup;
2745 2746
    }

2747 2748
    url = virBufferContentAndReset(&buffer);

2749
    if (esxVI_CURL_Download(priv->primary->curl, url, &vmx) < 0) {
M
Matthias Bolte 已提交
2750
        goto cleanup;
2751 2752
    }

2753
    data.ctx = priv->primary;
2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767

    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;
        }
    }
2768 2769 2770 2771 2772 2773

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

2774
    def = virVMXParseConfig(&ctx, priv->caps, vmx);
2775 2776

    if (def != NULL) {
2777 2778 2779 2780
        if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
            def->id = id;
        }

2781
        xml = virDomainDefFormat(def, flags);
2782 2783 2784
    }

  cleanup:
M
Matthias Bolte 已提交
2785 2786 2787 2788
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

2789 2790
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2791
    VIR_FREE(datastoreName);
M
Matthias Bolte 已提交
2792
    VIR_FREE(directoryName);
2793
    VIR_FREE(directoryAndFileName);
2794
    VIR_FREE(url);
2795
    VIR_FREE(data.datastorePathWithoutFileName);
2796
    VIR_FREE(vmx);
2797
    virDomainDefFree(def);
2798 2799 2800 2801 2802 2803 2804 2805 2806

    return xml;
}



static char *
esxDomainXMLFromNative(virConnectPtr conn, const char *nativeFormat,
                       const char *nativeConfig,
E
Eric Blake 已提交
2807
                       unsigned int flags)
2808
{
M
Matthias Bolte 已提交
2809
    esxPrivate *priv = conn->privateData;
2810
    virVMXContext ctx;
2811
    esxVMX_Data data;
2812 2813 2814
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2815 2816
    virCheckFlags(0, NULL);

2817 2818
    memset(&data, 0, sizeof (data));

2819
    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2820
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2821
                  _("Unsupported config format '%s'"), nativeFormat);
2822
        return NULL;
2823 2824
    }

2825
    data.ctx = priv->primary;
2826
    data.datastorePathWithoutFileName = (char *)"[?] ?";
2827 2828 2829 2830 2831 2832

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

2833
    def = virVMXParseConfig(&ctx, priv->caps, nativeConfig);
2834 2835

    if (def != NULL) {
2836
        xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
2837 2838 2839 2840 2841 2842 2843 2844 2845
    }

    virDomainDefFree(def);

    return xml;
}



M
Matthias Bolte 已提交
2846 2847 2848
static char *
esxDomainXMLToNative(virConnectPtr conn, const char *nativeFormat,
                     const char *domainXml,
E
Eric Blake 已提交
2849
                     unsigned int flags)
M
Matthias Bolte 已提交
2850
{
M
Matthias Bolte 已提交
2851
    esxPrivate *priv = conn->privateData;
2852 2853
    int virtualHW_version;
    virVMXContext ctx;
2854
    esxVMX_Data data;
M
Matthias Bolte 已提交
2855 2856 2857
    virDomainDefPtr def = NULL;
    char *vmx = NULL;

E
Eric Blake 已提交
2858 2859
    virCheckFlags(0, NULL);

2860 2861
    memset(&data, 0, sizeof (data));

M
Matthias Bolte 已提交
2862
    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2863
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2864
                  _("Unsupported config format '%s'"), nativeFormat);
M
Matthias Bolte 已提交
2865 2866 2867
        return NULL;
    }

2868 2869 2870 2871 2872 2873 2874
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        return NULL;
    }

M
Matthias Bolte 已提交
2875 2876
    def = virDomainDefParseString(priv->caps, domainXml,
                                  1 << VIR_DOMAIN_VIRT_VMWARE, 0);
M
Matthias Bolte 已提交
2877 2878 2879 2880 2881

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

2882
    data.ctx = priv->primary;
2883
    data.datastorePathWithoutFileName = NULL;
2884 2885 2886 2887 2888 2889

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

2890
    vmx = virVMXFormatConfig(&ctx, priv->caps, def, virtualHW_version);
M
Matthias Bolte 已提交
2891 2892 2893 2894 2895 2896 2897 2898

    virDomainDefFree(def);

    return vmx;
}



2899 2900 2901
static int
esxListDefinedDomains(virConnectPtr conn, char **const names, int maxnames)
{
M
Matthias Bolte 已提交
2902
    bool success = false;
M
Matthias Bolte 已提交
2903
    esxPrivate *priv = conn->privateData;
2904 2905 2906 2907 2908
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;
2909
    int i;
2910 2911 2912 2913 2914

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

2915
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2916
        return -1;
2917 2918
    }

2919
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2920 2921
                                           "name\0"
                                           "runtime.powerState\0") < 0 ||
2922 2923
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2924
        goto cleanup;
2925 2926 2927 2928
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
2929
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
2930
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
2931
            goto cleanup;
2932 2933 2934 2935 2936 2937
        }

        if (powerState == esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

2938
        names[count] = NULL;
2939

2940 2941 2942
        if (esxVI_GetVirtualMachineIdentity(virtualMachine, NULL, &names[count],
                                            NULL) < 0) {
            goto cleanup;
2943 2944
        }

2945 2946
        ++count;

2947 2948 2949 2950 2951
        if (count >= maxnames) {
            break;
        }
    }

M
Matthias Bolte 已提交
2952
    success = true;
2953

M
Matthias Bolte 已提交
2954 2955 2956 2957 2958
  cleanup:
    if (! success) {
        for (i = 0; i < count; ++i) {
            VIR_FREE(names[i]);
        }
2959

M
Matthias Bolte 已提交
2960
        count = -1;
2961 2962
    }

M
Matthias Bolte 已提交
2963 2964
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
2965

M
Matthias Bolte 已提交
2966
    return count;
2967 2968 2969 2970 2971 2972 2973
}



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

2976
    if (esxVI_EnsureSession(priv->primary) < 0) {
2977 2978 2979
        return -1;
    }

2980
    return esxVI_LookupNumberOfDomainsByPowerState
2981
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, true);
2982 2983 2984 2985 2986
}



static int
2987
esxDomainCreateWithFlags(virDomainPtr domain, unsigned int flags)
2988
{
M
Matthias Bolte 已提交
2989
    int result = -1;
M
Matthias Bolte 已提交
2990
    esxPrivate *priv = domain->conn->privateData;
2991 2992 2993
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
2994
    int id = -1;
2995 2996
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2997
    char *taskInfoErrorMessage = NULL;
2998

2999 3000
    virCheckFlags(0, -1);

3001
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3002
        return -1;
3003 3004
    }

3005
    if (esxVI_String_AppendValueToList(&propertyNameList,
3006
                                       "runtime.powerState") < 0 ||
3007
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3008
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
3009
           priv->parsedUri->autoAnswer) < 0 ||
3010 3011
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0) {
M
Matthias Bolte 已提交
3012
        goto cleanup;
3013 3014 3015
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
3016 3017
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered off"));
M
Matthias Bolte 已提交
3018
        goto cleanup;
3019 3020
    }

3021
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
3022
                             &task) < 0 ||
3023
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3024
                                    esxVI_Occurrence_RequiredItem,
3025
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3026
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3027
        goto cleanup;
3028 3029 3030
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3031 3032
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not start domain: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
3033
        goto cleanup;
3034 3035
    }

3036
    domain->id = id;
M
Matthias Bolte 已提交
3037 3038
    result = 0;

3039 3040 3041 3042
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
3043
    VIR_FREE(taskInfoErrorMessage);
3044 3045 3046 3047

    return result;
}

3048 3049


3050 3051 3052 3053 3054
static int
esxDomainCreate(virDomainPtr domain)
{
    return esxDomainCreateWithFlags(domain, 0);
}
3055

3056 3057


M
Matthias Bolte 已提交
3058
static virDomainPtr
3059
esxDomainDefineXML(virConnectPtr conn, const char *xml)
M
Matthias Bolte 已提交
3060
{
M
Matthias Bolte 已提交
3061
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
3062 3063
    virDomainDefPtr def = NULL;
    char *vmx = NULL;
3064 3065
    int i;
    virDomainDiskDefPtr disk = NULL;
M
Matthias Bolte 已提交
3066
    esxVI_ObjectContent *virtualMachine = NULL;
3067 3068
    int virtualHW_version;
    virVMXContext ctx;
3069
    esxVMX_Data data;
M
Matthias Bolte 已提交
3070 3071
    char *datastoreName = NULL;
    char *directoryName = NULL;
3072
    char *escapedName = NULL;
M
Matthias Bolte 已提交
3073 3074 3075 3076 3077 3078 3079 3080
    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;
3081
    char *taskInfoErrorMessage = NULL;
M
Matthias Bolte 已提交
3082 3083
    virDomainPtr domain = NULL;

3084 3085
    memset(&data, 0, sizeof (data));

3086
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3087
        return NULL;
M
Matthias Bolte 已提交
3088 3089 3090
    }

    /* Parse domain XML */
M
Matthias Bolte 已提交
3091
    def = virDomainDefParseString(priv->caps, xml, 1 << VIR_DOMAIN_VIRT_VMWARE,
M
Matthias Bolte 已提交
3092 3093 3094
                                  VIR_DOMAIN_XML_INACTIVE);

    if (def == NULL) {
M
Matthias Bolte 已提交
3095
        return NULL;
M
Matthias Bolte 已提交
3096 3097 3098
    }

    /* Check if an existing domain should be edited */
3099
    if (esxVI_LookupVirtualMachineByUuid(priv->primary, def->uuid, NULL,
M
Matthias Bolte 已提交
3100
                                         &virtualMachine,
M
Matthias Bolte 已提交
3101
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
3102
        goto cleanup;
M
Matthias Bolte 已提交
3103 3104
    }

3105 3106 3107 3108 3109 3110 3111
    if (virtualMachine == NULL &&
        esxVI_LookupVirtualMachineByName(priv->primary, def->name, NULL,
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
    }

M
Matthias Bolte 已提交
3112 3113
    if (virtualMachine != NULL) {
        /* FIXME */
3114 3115 3116
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Domain already exists, editing existing domains is not "
                    "supported yet"));
M
Matthias Bolte 已提交
3117
        goto cleanup;
M
Matthias Bolte 已提交
3118 3119 3120
    }

    /* Build VMX from domain XML */
3121 3122 3123 3124 3125 3126 3127
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        goto cleanup;
    }

3128
    data.ctx = priv->primary;
3129
    data.datastorePathWithoutFileName = NULL;
3130 3131 3132 3133 3134 3135

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

3136
    vmx = virVMXFormatConfig(&ctx, priv->caps, def, virtualHW_version);
M
Matthias Bolte 已提交
3137 3138

    if (vmx == NULL) {
M
Matthias Bolte 已提交
3139
        goto cleanup;
M
Matthias Bolte 已提交
3140 3141
    }

3142 3143 3144 3145 3146 3147 3148
    /*
     * 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 已提交
3149
    if (def->ndisks < 1) {
3150 3151 3152
        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 已提交
3153
        goto cleanup;
3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164
    }

    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) {
3165 3166 3167
        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 已提交
3168
        goto cleanup;
M
Matthias Bolte 已提交
3169 3170
    }

3171
    if (disk->src == NULL) {
3172 3173 3174
        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 已提交
3175
        goto cleanup;
M
Matthias Bolte 已提交
3176 3177
    }

3178
    if (esxUtil_ParseDatastorePath(disk->src, &datastoreName, &directoryName,
3179
                                   NULL) < 0) {
M
Matthias Bolte 已提交
3180
        goto cleanup;
M
Matthias Bolte 已提交
3181 3182
    }

3183
    if (! virFileHasSuffix(disk->src, ".vmdk")) {
3184
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3185 3186
                  _("Expecting source '%s' of first file-based harddisk to "
                    "be a VMDK image"), disk->src);
M
Matthias Bolte 已提交
3187
        goto cleanup;
M
Matthias Bolte 已提交
3188 3189
    }

3190
    virBufferAsprintf(&buffer, "%s://%s:%d/folder/", priv->parsedUri->transport,
M
Matthias Bolte 已提交
3191 3192 3193 3194 3195 3196 3197
                      conn->uri->server, conn->uri->port);

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

3198 3199 3200 3201 3202 3203 3204
    escapedName = esxUtil_EscapeDatastoreItem(def->name);

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

    virBufferURIEncodeString(&buffer, escapedName);
M
Matthias Bolte 已提交
3205
    virBufferAddLit(&buffer, ".vmx?dcPath=");
3206
    virBufferURIEncodeString(&buffer, priv->primary->datacenter->name);
M
Matthias Bolte 已提交
3207 3208 3209 3210
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
3211
        virReportOOMError();
M
Matthias Bolte 已提交
3212
        goto cleanup;
M
Matthias Bolte 已提交
3213 3214 3215 3216
    }

    url = virBufferContentAndReset(&buffer);

3217 3218 3219 3220 3221 3222
    /* Check, if VMX file already exists */
    /* FIXME */

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

3223
    if (esxVI_CURL_Upload(priv->primary->curl, url, vmx) < 0) {
3224 3225 3226 3227
        goto cleanup;
    }

    /* Register the domain */
M
Matthias Bolte 已提交
3228 3229
    if (directoryName != NULL) {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s/%s.vmx", datastoreName,
3230
                        directoryName, escapedName) < 0) {
3231
            virReportOOMError();
M
Matthias Bolte 已提交
3232
            goto cleanup;
M
Matthias Bolte 已提交
3233 3234 3235
        }
    } else {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s.vmx", datastoreName,
3236
                        escapedName) < 0) {
3237
            virReportOOMError();
M
Matthias Bolte 已提交
3238
            goto cleanup;
M
Matthias Bolte 已提交
3239 3240 3241
        }
    }

3242
    if (esxVI_RegisterVM_Task(priv->primary, priv->primary->datacenter->vmFolder,
M
Matthias Bolte 已提交
3243
                              datastoreRelatedPath, NULL, esxVI_Boolean_False,
3244 3245 3246 3247
                              priv->primary->computeResource->resourcePool,
                              priv->primary->hostSystem->_reference,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, def->uuid,
3248
                                    esxVI_Occurrence_OptionalItem,
3249
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3250
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3251
        goto cleanup;
M
Matthias Bolte 已提交
3252 3253 3254
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3255 3256
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not define domain: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
3257
        goto cleanup;
M
Matthias Bolte 已提交
3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268
    }

    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 已提交
3269 3270 3271 3272
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

M
Matthias Bolte 已提交
3273 3274 3275 3276
    virDomainDefFree(def);
    VIR_FREE(vmx);
    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
3277
    VIR_FREE(escapedName);
M
Matthias Bolte 已提交
3278 3279 3280 3281 3282 3283 3284
    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);
3285
    VIR_FREE(taskInfoErrorMessage);
M
Matthias Bolte 已提交
3286 3287 3288 3289 3290 3291

    return domain;
}



3292 3293 3294
static int
esxDomainUndefine(virDomainPtr domain)
{
M
Matthias Bolte 已提交
3295
    int result = -1;
M
Matthias Bolte 已提交
3296
    esxPrivate *priv = domain->conn->privateData;
3297
    esxVI_Context *ctx = NULL;
3298 3299 3300 3301
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

3302 3303 3304 3305 3306 3307
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

3308
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
3309
        return -1;
3310 3311
    }

3312
    if (esxVI_String_AppendValueToList(&propertyNameList,
3313
                                       "runtime.powerState") < 0 ||
3314 3315
        esxVI_LookupVirtualMachineByUuid(ctx, domain->uuid, propertyNameList,
                                         &virtualMachine,
M
Matthias Bolte 已提交
3316
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3317
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
3318
        goto cleanup;
3319 3320 3321 3322
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended &&
        powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
3323 3324
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not suspended or powered off"));
M
Matthias Bolte 已提交
3325
        goto cleanup;
3326 3327
    }

3328
    if (esxVI_UnregisterVM(ctx, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
3329
        goto cleanup;
3330 3331
    }

M
Matthias Bolte 已提交
3332 3333
    result = 0;

3334 3335 3336 3337 3338 3339 3340 3341 3342
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



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 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521
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;
}



3522 3523 3524 3525 3526 3527 3528 3529 3530 3531
/*
 * 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:
 *
3532
 * - reservation (VIR_TYPED_PARAM_LLONG >= 0, in megaherz)
3533
 *
3534
 *   The amount of CPU resource that is guaranteed to be available to the domain.
3535 3536
 *
 *
3537
 * - limit (VIR_TYPED_PARAM_LLONG >= 0, or -1, in megaherz)
3538
 *
3539 3540
 *   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
3541 3542 3543 3544
 *   utilization of the domain is unlimited. If the limit is not set to -1, it
 *   must be greater than or equal to the reservation.
 *
 *
3545
 * - shares (VIR_TYPED_PARAM_INT >= 0, or in {-1, -2, -3}, no unit)
3546 3547 3548 3549 3550 3551
 *
 *   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'.
 */
3552
static char *
3553
esxDomainGetSchedulerType(virDomainPtr domain ATTRIBUTE_UNUSED, int *nparams)
3554 3555 3556 3557
{
    char *type = strdup("allocation");

    if (type == NULL) {
3558
        virReportOOMError();
3559
        return NULL;
3560 3561
    }

3562 3563 3564
    if (nparams != NULL) {
        *nparams = 3; /* reservation, limit, shares */
    }
3565 3566 3567 3568 3569 3570 3571

    return type;
}



static int
3572 3573 3574
esxDomainGetSchedulerParametersFlags(virDomainPtr domain,
                                     virTypedParameterPtr params, int *nparams,
                                     unsigned int flags)
3575
{
M
Matthias Bolte 已提交
3576
    int result = -1;
M
Matthias Bolte 已提交
3577
    esxPrivate *priv = domain->conn->privateData;
3578 3579 3580 3581 3582 3583 3584
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    unsigned int mask = 0;
    int i = 0;

3585 3586
    virCheckFlags(0, -1);

3587
    if (*nparams < 3) {
3588 3589
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Parameter array must have space for 3 items"));
M
Matthias Bolte 已提交
3590
        return -1;
3591 3592
    }

3593
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3594
        return -1;
3595 3596
    }

3597
    if (esxVI_String_AppendValueListToList(&propertyNameList,
3598 3599 3600
                                           "config.cpuAllocation.reservation\0"
                                           "config.cpuAllocation.limit\0"
                                           "config.cpuAllocation.shares\0") < 0 ||
3601
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
3602
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3603
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3604
        goto cleanup;
3605 3606 3607 3608 3609 3610
    }

    for (dynamicProperty = virtualMachine->propSet;
         dynamicProperty != NULL && mask != 7 && i < 3;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.cpuAllocation.reservation") &&
M
Matthias Bolte 已提交
3611
            ! (mask & (1 << 0))) {
3612
            snprintf (params[i].field, VIR_TYPED_PARAM_FIELD_LENGTH, "%s",
3613 3614
                      "reservation");

3615
            params[i].type = VIR_TYPED_PARAM_LLONG;
3616

3617
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3618
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3619
                goto cleanup;
3620 3621 3622 3623 3624 3625 3626
            }

            params[i].value.l = dynamicProperty->val->int64;
            mask |= 1 << 0;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.limit") &&
M
Matthias Bolte 已提交
3627
                   ! (mask & (1 << 1))) {
3628
            snprintf (params[i].field, VIR_TYPED_PARAM_FIELD_LENGTH, "%s",
3629 3630
                      "limit");

3631
            params[i].type = VIR_TYPED_PARAM_LLONG;
3632

3633
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3634
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3635
                goto cleanup;
3636 3637 3638 3639 3640 3641 3642
            }

            params[i].value.l = dynamicProperty->val->int64;
            mask |= 1 << 1;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.shares") &&
M
Matthias Bolte 已提交
3643
                   ! (mask & (1 << 2))) {
3644
            snprintf (params[i].field, VIR_TYPED_PARAM_FIELD_LENGTH, "%s",
3645 3646
                      "shares");

3647
            params[i].type = VIR_TYPED_PARAM_INT;
3648

3649
            if (esxVI_SharesInfo_CastFromAnyType(dynamicProperty->val,
3650
                                                 &sharesInfo) < 0) {
M
Matthias Bolte 已提交
3651
                goto cleanup;
3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671
            }

            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:
3672
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3673
                          _("Shares level has unknown value %d"),
3674
                          (int)sharesInfo->level);
M
Matthias Bolte 已提交
3675
                goto cleanup;
3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687
            }

            esxVI_SharesInfo_Free(&sharesInfo);

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

    *nparams = i;
M
Matthias Bolte 已提交
3688
    result = 0;
3689 3690 3691 3692 3693 3694 3695 3696

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

    return result;
}

3697 3698 3699 3700 3701 3702
static int
esxDomainGetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int *nparams)
{
    return esxDomainGetSchedulerParametersFlags(domain, params, nparams, 0);
}
3703 3704 3705


static int
3706 3707 3708
esxDomainSetSchedulerParametersFlags(virDomainPtr domain,
                                     virTypedParameterPtr params, int nparams,
                                     unsigned int flags)
3709
{
M
Matthias Bolte 已提交
3710
    int result = -1;
M
Matthias Bolte 已提交
3711
    esxPrivate *priv = domain->conn->privateData;
3712 3713 3714 3715 3716
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3717
    char *taskInfoErrorMessage = NULL;
3718 3719
    int i;

3720 3721
    virCheckFlags(0, -1);

3722
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3723
        return -1;
3724 3725
    }

3726
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3727
          (priv->primary, domain->uuid, NULL, &virtualMachine,
3728
           priv->parsedUri->autoAnswer) < 0 ||
3729 3730
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->cpuAllocation) < 0) {
M
Matthias Bolte 已提交
3731
        goto cleanup;
3732 3733 3734 3735
    }

    for (i = 0; i < nparams; ++i) {
        if (STREQ (params[i].field, "reservation") &&
3736
            params[i].type == VIR_TYPED_PARAM_LLONG) {
3737
            if (esxVI_Long_Alloc(&spec->cpuAllocation->reservation) < 0) {
M
Matthias Bolte 已提交
3738
                goto cleanup;
3739 3740 3741
            }

            if (params[i].value.l < 0) {
3742
                ESX_ERROR(VIR_ERR_INVALID_ARG,
3743 3744
                          _("Could not set reservation to %lld MHz, expecting "
                            "positive value"), params[i].value.l);
M
Matthias Bolte 已提交
3745
                goto cleanup;
3746 3747 3748 3749
            }

            spec->cpuAllocation->reservation->value = params[i].value.l;
        } else if (STREQ (params[i].field, "limit") &&
3750
                   params[i].type == VIR_TYPED_PARAM_LLONG) {
3751
            if (esxVI_Long_Alloc(&spec->cpuAllocation->limit) < 0) {
M
Matthias Bolte 已提交
3752
                goto cleanup;
3753 3754 3755
            }

            if (params[i].value.l < -1) {
3756
                ESX_ERROR(VIR_ERR_INVALID_ARG,
3757 3758
                          _("Could not set limit to %lld MHz, expecting "
                            "positive value or -1 (unlimited)"),
3759
                          params[i].value.l);
M
Matthias Bolte 已提交
3760
                goto cleanup;
3761 3762 3763 3764
            }

            spec->cpuAllocation->limit->value = params[i].value.l;
        } else if (STREQ (params[i].field, "shares") &&
3765
                   params[i].type == VIR_TYPED_PARAM_INT) {
3766 3767
            if (esxVI_SharesInfo_Alloc(&sharesInfo) < 0 ||
                esxVI_Int_Alloc(&sharesInfo->shares) < 0) {
M
Matthias Bolte 已提交
3768
                goto cleanup;
3769 3770 3771 3772
            }

            spec->cpuAllocation->shares = sharesInfo;

3773
            if (params[i].value.i >= 0) {
3774
                spec->cpuAllocation->shares->level = esxVI_SharesLevel_Custom;
3775
                spec->cpuAllocation->shares->shares->value = params[i].value.i;
3776
            } else {
3777
                switch (params[i].value.i) {
3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795
                  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:
3796
                    ESX_ERROR(VIR_ERR_INVALID_ARG,
3797 3798
                              _("Could not set shares to %d, expecting positive "
                                "value or -1 (low), -2 (normal) or -3 (high)"),
3799
                              params[i].value.i);
M
Matthias Bolte 已提交
3800
                    goto cleanup;
3801 3802 3803
                }
            }
        } else {
3804
            ESX_ERROR(VIR_ERR_INVALID_ARG, _("Unknown field '%s'"),
3805
                      params[i].field);
M
Matthias Bolte 已提交
3806
            goto cleanup;
3807 3808 3809
        }
    }

3810
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
3811
                              &task) < 0 ||
3812
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3813
                                    esxVI_Occurrence_RequiredItem,
3814
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3815
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3816
        goto cleanup;
3817 3818 3819
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3820 3821 3822
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not change scheduler parameters: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
3823
        goto cleanup;
3824 3825
    }

M
Matthias Bolte 已提交
3826 3827
    result = 0;

3828 3829 3830 3831
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
3832
    VIR_FREE(taskInfoErrorMessage);
3833 3834 3835 3836

    return result;
}

3837 3838 3839 3840 3841 3842
static int
esxDomainSetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int nparams)
{
    return esxDomainSetSchedulerParametersFlags(domain, params, nparams, 0);
}
3843

E
Eric Blake 已提交
3844 3845 3846 3847 3848 3849
/* The subset of migration flags we are able to support.  */
#define ESX_MIGRATION_FLAGS                     \
    (VIR_MIGRATE_PERSIST_DEST |                 \
     VIR_MIGRATE_UNDEFINE_SOURCE |              \
     VIR_MIGRATE_LIVE |                         \
     VIR_MIGRATE_PAUSED)
3850 3851 3852 3853 3854

static int
esxDomainMigratePrepare(virConnectPtr dconn,
                        char **cookie ATTRIBUTE_UNUSED,
                        int *cookielen ATTRIBUTE_UNUSED,
3855 3856
                        const char *uri_in ATTRIBUTE_UNUSED,
                        char **uri_out,
E
Eric Blake 已提交
3857
                        unsigned long flags,
3858 3859 3860
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
3861
    esxPrivate *priv = dconn->privateData;
3862

E
Eric Blake 已提交
3863 3864
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

3865
    if (uri_in == NULL) {
3866 3867 3868 3869
        if (virAsprintf(uri_out, "vpxmigr://%s/%s/%s",
                        priv->vCenter->ipAddress,
                        priv->vCenter->computeResource->resourcePool->value,
                        priv->vCenter->hostSystem->_reference->value) < 0) {
3870
            virReportOOMError();
3871
            return -1;
3872 3873 3874
        }
    }

3875
    return 0;
3876 3877 3878 3879 3880 3881 3882 3883 3884
}



static int
esxDomainMigratePerform(virDomainPtr domain,
                        const char *cookie ATTRIBUTE_UNUSED,
                        int cookielen ATTRIBUTE_UNUSED,
                        const char *uri,
E
Eric Blake 已提交
3885
                        unsigned long flags,
3886 3887 3888
                        const char *dname,
                        unsigned long bandwidth ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
3889
    int result = -1;
M
Matthias Bolte 已提交
3890
    esxPrivate *priv = domain->conn->privateData;
3891 3892 3893 3894
    xmlURIPtr parsedUri = NULL;
    char *saveptr;
    char *path_resourcePool;
    char *path_hostSystem;
3895
    esxVI_ObjectContent *virtualMachine = NULL;
3896 3897
    esxVI_ManagedObjectReference resourcePool;
    esxVI_ManagedObjectReference hostSystem;
3898 3899 3900
    esxVI_Event *eventList = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3901
    char *taskInfoErrorMessage = NULL;
3902

E
Eric Blake 已提交
3903 3904
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

M
Matthias Bolte 已提交
3905
    if (priv->vCenter == NULL) {
3906 3907
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Migration not possible without a vCenter"));
M
Matthias Bolte 已提交
3908
        return -1;
3909 3910 3911
    }

    if (dname != NULL) {
3912 3913
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Renaming domains on migration not supported"));
M
Matthias Bolte 已提交
3914
        return -1;
3915 3916
    }

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

3921 3922
    /* Parse migration URI */
    parsedUri = xmlParseURI(uri);
3923

3924
    if (parsedUri == NULL) {
3925
        virReportOOMError();
M
Matthias Bolte 已提交
3926
        return -1;
3927 3928
    }

3929 3930 3931
    if (parsedUri->scheme == NULL || STRCASENEQ(parsedUri->scheme, "vpxmigr")) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Only vpxmigr:// migration URIs are supported"));
M
Matthias Bolte 已提交
3932
        goto cleanup;
3933 3934
    }

3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947
    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 已提交
3948
        goto cleanup;
3949 3950
    }

3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963
    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,
3964
           priv->parsedUri->autoAnswer) < 0) {
M
Matthias Bolte 已提交
3965
        goto cleanup;
3966 3967 3968
    }

    /* Validate the purposed migration */
3969
    if (esxVI_ValidateMigration(priv->vCenter, virtualMachine->obj,
3970 3971
                                esxVI_VirtualMachinePowerState_Undefined, NULL,
                                &resourcePool, &hostSystem, &eventList) < 0) {
M
Matthias Bolte 已提交
3972
        goto cleanup;
3973 3974 3975 3976 3977 3978 3979 3980
    }

    if (eventList != NULL) {
        /*
         * FIXME: Need to report the complete list of events. Limit reporting
         *        to the first event for now.
         */
        if (eventList->fullFormattedMessage != NULL) {
3981
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3982 3983
                      _("Could not migrate domain, validation reported a "
                        "problem: %s"), eventList->fullFormattedMessage);
3984
        } else {
3985 3986 3987
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                      _("Could not migrate domain, validation reported a "
                        "problem"));
3988 3989
        }

M
Matthias Bolte 已提交
3990
        goto cleanup;
3991 3992 3993
    }

    /* Perform the purposed migration */
3994 3995
    if (esxVI_MigrateVM_Task(priv->vCenter, virtualMachine->obj,
                             &resourcePool, &hostSystem,
3996 3997 3998
                             esxVI_VirtualMachineMovePriority_DefaultPriority,
                             esxVI_VirtualMachinePowerState_Undefined,
                             &task) < 0 ||
3999
        esxVI_WaitForTaskCompletion(priv->vCenter, task, domain->uuid,
4000
                                    esxVI_Occurrence_RequiredItem,
4001
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4002
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4003
        goto cleanup;
4004 4005 4006
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4007
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
4008
                  _("Could not migrate domain, migration task finished with "
4009 4010
                    "an error: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
4011
        goto cleanup;
4012 4013
    }

M
Matthias Bolte 已提交
4014 4015
    result = 0;

4016
  cleanup:
4017
    xmlFreeURI(parsedUri);
4018 4019 4020
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Event_Free(&eventList);
    esxVI_ManagedObjectReference_Free(&task);
4021
    VIR_FREE(taskInfoErrorMessage);
4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032

    return result;
}



static virDomainPtr
esxDomainMigrateFinish(virConnectPtr dconn, const char *dname,
                       const char *cookie ATTRIBUTE_UNUSED,
                       int cookielen ATTRIBUTE_UNUSED,
                       const char *uri ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
4033
                       unsigned long flags)
4034
{
E
Eric Blake 已提交
4035 4036
    virCheckFlags(ESX_MIGRATION_FLAGS, NULL);

4037 4038 4039 4040 4041
    return esxDomainLookupByName(dconn, dname);
}



M
Matthias Bolte 已提交
4042 4043 4044 4045
static unsigned long long
esxNodeGetFreeMemory(virConnectPtr conn)
{
    unsigned long long result = 0;
M
Matthias Bolte 已提交
4046
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
4047 4048 4049 4050 4051
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *resourcePool = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ResourcePoolResourceUsage *resourcePoolResourceUsage = NULL;

4052
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4053
        return 0;
M
Matthias Bolte 已提交
4054 4055 4056
    }

    /* Get memory usage of resource pool */
4057
    if (esxVI_String_AppendValueToList(&propertyNameList,
M
Matthias Bolte 已提交
4058
                                       "runtime.memory") < 0 ||
4059 4060
        esxVI_LookupObjectContentByType(priv->primary,
                                        priv->primary->computeResource->resourcePool,
4061
                                        "ResourcePool", propertyNameList,
4062 4063
                                        &resourcePool,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4064
        goto cleanup;
M
Matthias Bolte 已提交
4065 4066 4067 4068 4069 4070
    }

    for (dynamicProperty = resourcePool->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.memory")) {
            if (esxVI_ResourcePoolResourceUsage_CastFromAnyType
4071
                  (dynamicProperty->val, &resourcePoolResourceUsage) < 0) {
M
Matthias Bolte 已提交
4072
                goto cleanup;
M
Matthias Bolte 已提交
4073 4074 4075 4076 4077 4078 4079 4080 4081
            }

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

    if (resourcePoolResourceUsage == NULL) {
4082 4083
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve memory usage of resource pool"));
M
Matthias Bolte 已提交
4084
        goto cleanup;
M
Matthias Bolte 已提交
4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098
    }

    result = resourcePoolResourceUsage->unreservedForVm->value;

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

    return result;
}



4099 4100 4101
static int
esxIsEncrypted(virConnectPtr conn)
{
M
Matthias Bolte 已提交
4102
    esxPrivate *priv = conn->privateData;
4103

4104
    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115
        return 1;
    } else {
        return 0;
    }
}



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

4118
    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129
        return 1;
    } else {
        return 0;
    }
}



static int
esxDomainIsActive(virDomainPtr domain)
{
M
Matthias Bolte 已提交
4130
    int result = -1;
M
Matthias Bolte 已提交
4131
    esxPrivate *priv = domain->conn->privateData;
4132 4133 4134 4135
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

4136
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4137
        return -1;
4138 4139
    }

4140
    if (esxVI_String_AppendValueToList(&propertyNameList,
4141
                                       "runtime.powerState") < 0 ||
4142
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
4143
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
4144
                                         esxVI_Occurrence_RequiredItem) < 0 ||
4145
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
4146
        goto cleanup;
4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170
    }

    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 已提交
4171 4172


4173 4174 4175 4176 4177
static int
esxDomainIsUpdated(virDomainPtr domain ATTRIBUTE_UNUSED)
{
    return 0;
}
4178

M
Matthias Bolte 已提交
4179 4180


4181 4182
static virDomainSnapshotPtr
esxDomainSnapshotCreateXML(virDomainPtr domain, const char *xmlDesc,
4183
                           unsigned int flags)
4184 4185 4186 4187 4188 4189 4190 4191 4192
{
    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;
4193
    char *taskInfoErrorMessage = NULL;
4194 4195
    virDomainSnapshotPtr snapshot = NULL;

4196 4197
    virCheckFlags(0, NULL);

4198
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4199
        return NULL;
4200 4201 4202 4203 4204
    }

    def = virDomainSnapshotDefParseString(xmlDesc, 1);

    if (def == NULL) {
M
Matthias Bolte 已提交
4205
        return NULL;
4206 4207 4208
    }

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

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

4225
    if (esxVI_CreateSnapshot_Task(priv->primary, virtualMachine->obj,
4226 4227 4228
                                  def->name, def->description,
                                  esxVI_Boolean_True,
                                  esxVI_Boolean_False, &task) < 0 ||
4229
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
4230
                                    esxVI_Occurrence_RequiredItem,
4231
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4232
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4233
        goto cleanup;
4234 4235 4236
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4237 4238
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not create snapshot: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
4239
        goto cleanup;
4240 4241 4242 4243 4244 4245 4246 4247 4248
    }

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

  cleanup:
    virDomainSnapshotDefFree(def);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4249
    VIR_FREE(taskInfoErrorMessage);
4250 4251 4252 4253 4254 4255 4256

    return snapshot;
}



static char *
4257 4258
esxDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                            unsigned int flags)
4259 4260 4261 4262 4263 4264 4265 4266 4267
{
    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;

4268 4269
    virCheckFlags(0, NULL);

M
Matthias Bolte 已提交
4270
    memset(&def, 0, sizeof (def));
4271

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

4276
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4277 4278 4279 4280
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4281
        goto cleanup;
4282 4283 4284 4285 4286 4287 4288 4289
    }

    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 已提交
4290
        goto cleanup;
4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308
    }

    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
4309
esxDomainSnapshotNum(virDomainPtr domain, unsigned int flags)
4310
{
M
Matthias Bolte 已提交
4311
    int count;
4312 4313 4314
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;

4315 4316
    virCheckFlags(0, -1);

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

4321
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4322
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4323
        return -1;
4324 4325
    }

M
Matthias Bolte 已提交
4326
    count = esxVI_GetNumberOfSnapshotTrees(rootSnapshotTreeList);
4327 4328 4329

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

M
Matthias Bolte 已提交
4330
    return count;
4331 4332 4333 4334 4335 4336
}



static int
esxDomainSnapshotListNames(virDomainPtr domain, char **names, int nameslen,
4337
                           unsigned int flags)
4338
{
M
Matthias Bolte 已提交
4339
    int result;
4340 4341 4342
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;

4343 4344
    virCheckFlags(0, -1);

4345 4346 4347 4348 4349 4350 4351 4352 4353
    if (names == NULL || nameslen < 0) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
    }

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

4354
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4355
        return -1;
4356 4357
    }

4358
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4359
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4360
        return -1;
4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373
    }

    result = esxVI_GetSnapshotTreeNames(rootSnapshotTreeList, names, nameslen);

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



static virDomainSnapshotPtr
esxDomainSnapshotLookupByName(virDomainPtr domain, const char *name,
4374
                              unsigned int flags)
4375 4376 4377 4378 4379 4380 4381
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    virDomainSnapshotPtr snapshot = NULL;

4382 4383
    virCheckFlags(0, NULL);

4384
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4385
        return NULL;
4386 4387
    }

4388
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411
                                         &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;

4412
    virCheckFlags(0, -1);
4413

4414
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4415
        return -1;
4416 4417
    }

4418
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4419 4420
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4421
        return -1;
4422 4423 4424
    }

    if (currentSnapshotTree != NULL) {
M
Matthias Bolte 已提交
4425 4426
        esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);
        return 1;
4427 4428
    }

M
Matthias Bolte 已提交
4429
    return 0;
4430 4431 4432 4433 4434 4435 4436 4437 4438
}



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

4441
    virCheckFlags(0, NULL);
4442

4443
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4444
        return NULL;
4445 4446
    }

4447
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4448 4449
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4450
        return NULL;
4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464
    }

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

    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return snapshot;
}



static int
esxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4465
    int result = -1;
4466 4467 4468 4469 4470 4471
    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;
4472
    char *taskInfoErrorMessage = NULL;
4473

4474
    virCheckFlags(0, -1);
4475

4476
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4477
        return -1;
4478 4479
    }

4480
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4481 4482 4483 4484
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4485
        goto cleanup;
4486 4487
    }

4488
    if (esxVI_RevertToSnapshot_Task(priv->primary, snapshotTree->snapshot, NULL,
4489
                                    &task) < 0 ||
4490
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4491
                                    esxVI_Occurrence_RequiredItem,
4492
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4493
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4494
        goto cleanup;
4495 4496 4497 4498
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
4499 4500
                  _("Could not revert to snapshot '%s': %s"), snapshot->name,
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
4501
        goto cleanup;
4502 4503
    }

M
Matthias Bolte 已提交
4504 4505
    result = 0;

4506 4507 4508
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4509
    VIR_FREE(taskInfoErrorMessage);
4510 4511 4512 4513 4514 4515 4516 4517 4518

    return result;
}



static int
esxDomainSnapshotDelete(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4519
    int result = -1;
4520 4521 4522 4523 4524 4525 4526
    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;
4527
    char *taskInfoErrorMessage = NULL;
4528

4529 4530
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN, -1);

4531
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4532
        return -1;
4533 4534 4535 4536 4537 4538
    }

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

4539
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4540 4541 4542 4543
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4544
        goto cleanup;
4545 4546
    }

4547
    if (esxVI_RemoveSnapshot_Task(priv->primary, snapshotTree->snapshot,
4548
                                  removeChildren, &task) < 0 ||
4549
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4550
                                    esxVI_Occurrence_RequiredItem,
4551
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4552
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4553
        goto cleanup;
4554 4555 4556 4557
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
4558 4559
                  _("Could not delete snapshot '%s': %s"), snapshot->name,
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
4560
        goto cleanup;
4561 4562
    }

M
Matthias Bolte 已提交
4563 4564
    result = 0;

4565 4566 4567
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4568
    VIR_FREE(taskInfoErrorMessage);
4569 4570 4571 4572 4573 4574

    return result;
}



4575
static int
4576
esxDomainSetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
4577 4578 4579 4580 4581 4582 4583 4584
                             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;
4585
    char *taskInfoErrorMessage = NULL;
4586 4587 4588 4589 4590 4591 4592 4593 4594 4595
    int i;

    virCheckFlags(0, -1);

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

    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4596
           priv->parsedUri->autoAnswer) < 0 ||
4597 4598 4599 4600 4601 4602 4603
        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) &&
4604
            params[i].type == VIR_TYPED_PARAM_ULLONG) {
4605 4606 4607 4608 4609
            if (esxVI_Long_Alloc(&spec->memoryAllocation->reservation) < 0) {
                goto cleanup;
            }

            spec->memoryAllocation->reservation->value =
4610
              VIR_DIV_UP(params[i].value.ul, 1024); /* Scale from kilobytes to megabytes */
4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621
        } 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,
4622
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4623
                                    &taskInfoErrorMessage) < 0) {
4624 4625 4626 4627
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4628 4629 4630
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not change memory parameters: %s"),
                  taskInfoErrorMessage);
4631 4632 4633 4634 4635 4636 4637 4638 4639
        goto cleanup;
    }

    result = 0;

  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
4640
    VIR_FREE(taskInfoErrorMessage);
4641 4642 4643 4644 4645 4646 4647

    return result;
}



static int
4648
esxDomainGetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
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
                             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;
    }

4692
    params[0].type = VIR_TYPED_PARAM_ULLONG;
4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707
    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;
}



4708
static virDriver esxDriver = {
4709 4710
    .no = VIR_DRV_ESX,
    .name = "ESX",
4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753
    .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 */
4754
    .domainGetSchedulerParametersFlags = esxDomainGetSchedulerParametersFlags, /* 0.9.2 */
4755
    .domainSetSchedulerParameters = esxDomainSetSchedulerParameters, /* 0.7.0 */
4756
    .domainSetSchedulerParametersFlags = esxDomainSetSchedulerParametersFlags, /* 0.9.2 */
4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774
    .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 */
4775 4776 4777 4778 4779 4780 4781
};



int
esxRegister(void)
{
4782 4783 4784 4785 4786
    if (virRegisterDriver(&esxDriver) < 0 ||
        esxInterfaceRegister() < 0 ||
        esxNetworkRegister() < 0 ||
        esxStorageRegister() < 0 ||
        esxDeviceRegister() < 0 ||
M
Matthias Bolte 已提交
4787 4788
        esxSecretRegister() < 0 ||
        esxNWFilterRegister() < 0) {
4789 4790
        return -1;
    }
4791 4792 4793

    return 0;
}