esx_driver.c 157.6 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
 *
 * 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
E
Eric Blake 已提交
279
 * and file name to an absolute path and return it. Detect the separator type
280 281
 * 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

    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")) {
415
        *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_BUSLOGIC;
416 417
    } else if (STRCASEEQ(vmDiskFileInfo->controllerType,
                         "VirtualLsiLogicController")) {
418
        *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC;
419 420
    } else if (STRCASEEQ(vmDiskFileInfo->controllerType,
                         "VirtualLsiLogicSASController")) {
421
        *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSISAS1068;
422 423
    } else if (STRCASEEQ(vmDiskFileInfo->controllerType,
                         "ParaVirtualSCSIController")) {
424
        *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VMPVSCSI;
425 426 427 428 429 430 431 432 433 434
    } 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
    char *plus;
942
    esxPrivate *priv = NULL;
943
    char *potentialVCenterIpAddress = NULL;
M
Matthias Bolte 已提交
944
    char vCenterIpAddress[NI_MAXHOST] = "";
945

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

948 949
    /* Decline if the URI is NULL or the scheme is NULL */
    if (conn->uri == NULL || conn->uri->scheme == NULL) {
950 951 952
        return VIR_DRV_OPEN_DECLINED;
    }

953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
    /* Decline if the scheme is not one of {vpx|esx|gsx} */
    plus = strchr(conn->uri->scheme, '+');

    if (plus == NULL) {
        if (STRCASENEQ(conn->uri->scheme, "vpx") &&
            STRCASENEQ(conn->uri->scheme, "esx") &&
            STRCASENEQ(conn->uri->scheme, "gsx")) {
            return VIR_DRV_OPEN_DECLINED;
        }
    } else {
        if (plus - conn->uri->scheme != 3 ||
            (STRCASENEQLEN(conn->uri->scheme, "vpx", 3) &&
             STRCASENEQLEN(conn->uri->scheme, "esx", 3) &&
             STRCASENEQLEN(conn->uri->scheme, "gsx", 3))) {
            return VIR_DRV_OPEN_DECLINED;
        }

        ESX_ERROR(VIR_ERR_INVALID_ARG,
                  _("Transport '%s' in URI scheme is not supported, try again "
                    "without the transport part"), plus + 1);
        return VIR_DRV_OPEN_ERROR;
    }

976 977 978 979 980 981 982 983 984 985 986 987
    /* 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;
988 989 990 991
    }

    /* Allocate per-connection private data */
    if (VIR_ALLOC(priv) < 0) {
992
        virReportOOMError();
M
Matthias Bolte 已提交
993
        goto cleanup;
994 995
    }

996
    if (esxUtil_ParseUri(&priv->parsedUri, conn->uri) < 0) {
997 998 999
        goto cleanup;
    }

M
Matthias Bolte 已提交
1000 1001
    priv->maxVcpus = -1;
    priv->supportsVMotion = esxVI_Boolean_Undefined;
1002
    priv->supportsLongMode = esxVI_Boolean_Undefined;
1003 1004
    priv->usedCpuTimeCounterId = -1;

M
Matthias Bolte 已提交
1005 1006 1007 1008 1009 1010 1011
    /*
     * 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) {
1012 1013
        if (STRCASEEQ(conn->uri->scheme, "vpx") ||
            STRCASEEQ(conn->uri->scheme, "esx")) {
1014
            if (STRCASEEQ(priv->parsedUri->transport, "https")) {
M
Matthias Bolte 已提交
1015 1016 1017 1018 1019
                conn->uri->port = 443;
            } else {
                conn->uri->port = 80;
            }
        } else { /* GSX */
1020
            if (STRCASEEQ(priv->parsedUri->transport, "https")) {
M
Matthias Bolte 已提交
1021 1022 1023 1024
                conn->uri->port = 8333;
            } else {
                conn->uri->port = 8222;
            }
1025
        }
M
Matthias Bolte 已提交
1026
    }
1027

1028 1029 1030 1031
    if (STRCASEEQ(conn->uri->scheme, "esx") ||
        STRCASEEQ(conn->uri->scheme, "gsx")) {
        /* Connect to host */
        if (esxConnectToHost(priv, auth, conn->uri->server, conn->uri->port,
1032
                             conn->uri->user,
1033 1034 1035 1036
                             STRCASEEQ(conn->uri->scheme, "esx")
                               ? esxVI_ProductVersion_ESX
                               : esxVI_ProductVersion_GSX,
                             &potentialVCenterIpAddress) < 0) {
M
Matthias Bolte 已提交
1037
            goto cleanup;
1038
        }
1039

1040
        /* Connect to vCenter */
1041 1042
        if (priv->parsedUri->vCenter != NULL) {
            if (STREQ(priv->parsedUri->vCenter, "*")) {
1043 1044 1045
                if (potentialVCenterIpAddress == NULL) {
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                              _("This host is not managed by a vCenter"));
M
Matthias Bolte 已提交
1046
                    goto cleanup;
1047 1048
                }

1049 1050 1051 1052 1053 1054 1055 1056
                if (virStrcpyStatic(vCenterIpAddress,
                                    potentialVCenterIpAddress) == NULL) {
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                              _("vCenter IP address %s too big for destination"),
                              potentialVCenterIpAddress);
                    goto cleanup;
                }
            } else {
1057
                if (esxUtil_ResolveHostname(priv->parsedUri->vCenter,
1058 1059 1060
                                            vCenterIpAddress, NI_MAXHOST) < 0) {
                    goto cleanup;
                }
1061

1062 1063
                if (potentialVCenterIpAddress != NULL &&
                    STRNEQ(vCenterIpAddress, potentialVCenterIpAddress)) {
1064
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1065 1066 1067
                              _("This host is managed by a vCenter with IP "
                                "address %s, but a mismachting vCenter '%s' "
                                "(%s) has been specified"),
1068
                              potentialVCenterIpAddress, priv->parsedUri->vCenter,
1069
                              vCenterIpAddress);
M
Matthias Bolte 已提交
1070
                    goto cleanup;
1071 1072
                }
            }
1073

1074
            if (esxConnectToVCenter(priv, auth, vCenterIpAddress,
1075
                                    conn->uri->port, NULL,
1076
                                    priv->host->ipAddress) < 0) {
1077 1078
                goto cleanup;
            }
1079 1080
        }

1081 1082 1083 1084
        priv->primary = priv->host;
    } else { /* VPX */
        /* Connect to vCenter */
        if (esxConnectToVCenter(priv, auth, conn->uri->server, conn->uri->port,
1085
                                conn->uri->user, NULL) < 0) {
M
Matthias Bolte 已提交
1086
            goto cleanup;
1087 1088
        }

1089
        priv->primary = priv->vCenter;
1090 1091
    }

M
Matthias Bolte 已提交
1092
    /* Setup capabilities */
1093
    priv->caps = esxCapsInit(priv);
1094

M
Matthias Bolte 已提交
1095
    if (priv->caps == NULL) {
M
Matthias Bolte 已提交
1096
        goto cleanup;
1097 1098
    }

1099 1100
    conn->privateData = priv;

M
Matthias Bolte 已提交
1101
    result = VIR_DRV_OPEN_SUCCESS;
1102

M
Matthias Bolte 已提交
1103
  cleanup:
1104 1105
    if (result == VIR_DRV_OPEN_ERROR) {
        esxFreePrivate(&priv);
1106 1107
    }

1108
    VIR_FREE(potentialVCenterIpAddress);
1109

M
Matthias Bolte 已提交
1110
    return result;
1111 1112 1113 1114 1115 1116 1117
}



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

1121 1122 1123 1124 1125 1126
    if (priv->host != NULL) {
        if (esxVI_EnsureSession(priv->host) < 0 ||
            esxVI_Logout(priv->host) < 0) {
            result = -1;
        }
    }
1127

M
Matthias Bolte 已提交
1128
    if (priv->vCenter != NULL) {
E
Eric Blake 已提交
1129 1130 1131 1132
        if (esxVI_EnsureSession(priv->vCenter) < 0 ||
            esxVI_Logout(priv->vCenter) < 0) {
            result = -1;
        }
1133 1134
    }

1135
    esxFreePrivate(&priv);
1136 1137 1138

    conn->privateData = NULL;

E
Eric Blake 已提交
1139
    return result;
1140 1141 1142 1143 1144
}



static esxVI_Boolean
1145
esxSupportsVMotion(esxPrivate *priv)
1146 1147 1148 1149
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;

M
Matthias Bolte 已提交
1150 1151
    if (priv->supportsVMotion != esxVI_Boolean_Undefined) {
        return priv->supportsVMotion;
1152 1153
    }

1154
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1155
        return esxVI_Boolean_Undefined;
1156 1157
    }

1158
    if (esxVI_String_AppendValueToList(&propertyNameList,
1159
                                       "capability.vmotionSupported") < 0 ||
1160 1161
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1162
        goto cleanup;
1163 1164 1165
    }

    if (hostSystem == NULL) {
1166 1167
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
1168
        goto cleanup;
1169 1170
    }

1171 1172 1173 1174
    if (esxVI_GetBoolean(hostSystem, "capability.vmotionSupported",
                         &priv->supportsVMotion,
                         esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
1175 1176 1177
    }

  cleanup:
M
Matthias Bolte 已提交
1178 1179 1180 1181
    /*
     * 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.
     */
1182 1183 1184
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
1185
    return priv->supportsVMotion;
1186 1187 1188 1189 1190 1191 1192
}



static int
esxSupportsFeature(virConnectPtr conn, int feature)
{
M
Matthias Bolte 已提交
1193
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1194
    esxVI_Boolean supportsVMotion = esxVI_Boolean_Undefined;
1195 1196 1197

    switch (feature) {
      case VIR_DRV_FEATURE_MIGRATION_V1:
1198
        supportsVMotion = esxSupportsVMotion(priv);
1199

M
Matthias Bolte 已提交
1200
        if (supportsVMotion == esxVI_Boolean_Undefined) {
1201 1202 1203
            return -1;
        }

M
Matthias Bolte 已提交
1204 1205 1206
        /* Migration is only possible via a vCenter and if VMotion is enabled */
        return priv->vCenter != NULL &&
               supportsVMotion == esxVI_Boolean_True ? 1 : 0;
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225

      default:
        return 0;
    }
}



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



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

1228
    if (virParseVersionString(priv->primary->service->about->version,
1229
                              version, false) < 0) {
1230
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1231
                  _("Could not parse version number from '%s'"),
1232
                  priv->primary->service->about->version);
1233

1234
        return -1;
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
    }

    return 0;
}



static char *
esxGetHostname(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1245
    esxPrivate *priv = conn->privateData;
1246 1247 1248 1249 1250 1251 1252
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    const char *hostName = NULL;
    const char *domainName = NULL;
    char *complete = NULL;

1253
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1254
        return NULL;
1255 1256 1257
    }

    if (esxVI_String_AppendValueListToList
1258
          (&propertyNameList,
1259 1260
           "config.network.dnsConfig.hostName\0"
           "config.network.dnsConfig.domainName\0") < 0 ||
1261 1262
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1263
        goto cleanup;
1264 1265 1266
    }

    if (hostSystem == NULL) {
1267 1268
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
1269
        goto cleanup;
1270 1271 1272 1273 1274 1275
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name,
                  "config.network.dnsConfig.hostName")) {
1276
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1277
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1278
                goto cleanup;
1279 1280 1281 1282 1283
            }

            hostName = dynamicProperty->val->string;
        } else if (STREQ(dynamicProperty->name,
                         "config.network.dnsConfig.domainName")) {
1284
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1285
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1286
                goto cleanup;
1287 1288 1289 1290 1291 1292 1293 1294
            }

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

M
Matthias Bolte 已提交
1295
    if (hostName == NULL || strlen(hostName) < 1) {
1296 1297
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Missing or empty 'hostName' property"));
M
Matthias Bolte 已提交
1298
        goto cleanup;
1299 1300
    }

M
Matthias Bolte 已提交
1301
    if (domainName == NULL || strlen(domainName) < 1) {
1302
        complete = strdup(hostName);
1303

1304
        if (complete == NULL) {
1305
            virReportOOMError();
M
Matthias Bolte 已提交
1306
            goto cleanup;
1307 1308 1309
        }
    } else {
        if (virAsprintf(&complete, "%s.%s", hostName, domainName) < 0) {
1310
            virReportOOMError();
M
Matthias Bolte 已提交
1311
            goto cleanup;
1312
        }
1313 1314 1315
    }

  cleanup:
M
Matthias Bolte 已提交
1316 1317 1318 1319 1320
    /*
     * 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
     */
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return complete;
}



static int
esxNodeGetInfo(virConnectPtr conn, virNodeInfoPtr nodeinfo)
{
M
Matthias Bolte 已提交
1332
    int result = -1;
M
Matthias Bolte 已提交
1333
    esxPrivate *priv = conn->privateData;
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
    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 已提交
1345
    memset(nodeinfo, 0, sizeof (*nodeinfo));
1346

1347
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1348
        return -1;
1349 1350
    }

1351
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1352 1353 1354 1355 1356 1357 1358
                                           "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 ||
1359 1360
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1361
        goto cleanup;
1362 1363 1364
    }

    if (hostSystem == NULL) {
1365 1366
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
1367
        goto cleanup;
1368 1369 1370 1371 1372
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuInfo.hz")) {
1373
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1374
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1375
                goto cleanup;
1376 1377 1378 1379 1380
            }

            cpuInfo_hz = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuCores")) {
1381
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1382
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1383
                goto cleanup;
1384 1385 1386 1387 1388
            }

            cpuInfo_numCpuCores = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuPackages")) {
1389
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1390
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1391
                goto cleanup;
1392 1393 1394 1395 1396
            }

            cpuInfo_numCpuPackages = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuThreads")) {
1397
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1398
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1399
                goto cleanup;
1400 1401 1402 1403
            }

            cpuInfo_numCpuThreads = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name, "hardware.memorySize")) {
1404
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1405
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1406
                goto cleanup;
1407 1408 1409 1410 1411
            }

            memorySize = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.numaInfo.numNodes")) {
1412
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1413
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1414
                goto cleanup;
1415 1416 1417 1418 1419
            }

            numaInfo_numNodes = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "summary.hardware.cpuModel")) {
1420
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1421
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1422
                goto cleanup;
1423 1424 1425 1426 1427 1428
            }

            ptr = dynamicProperty->val->string;

            /* Strip the string to fit more relevant information in 32 chars */
            while (*ptr != '\0') {
M
Matthias Bolte 已提交
1429 1430
                if (STRPREFIX(ptr, "  ")) {
                    memmove(ptr, ptr + 1, strlen(ptr + 1) + 1);
1431
                    continue;
1432
                } else if (STRPREFIX(ptr, "(R)") || STRPREFIX(ptr, "(C)")) {
M
Matthias Bolte 已提交
1433
                    memmove(ptr, ptr + 3, strlen(ptr + 3) + 1);
1434
                    continue;
1435 1436 1437
                } else if (STRPREFIX(ptr, "(TM)")) {
                    memmove(ptr, ptr + 4, strlen(ptr + 4) + 1);
                    continue;
1438 1439 1440 1441 1442
                }

                ++ptr;
            }

C
Chris Lalancette 已提交
1443 1444 1445
            if (virStrncpy(nodeinfo->model, dynamicProperty->val->string,
                           sizeof(nodeinfo->model) - 1,
                           sizeof(nodeinfo->model)) == NULL) {
1446
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1447
                          _("CPU Model %s too long for destination"),
C
Chris Lalancette 已提交
1448
                          dynamicProperty->val->string);
M
Matthias Bolte 已提交
1449
                goto cleanup;
C
Chris Lalancette 已提交
1450
            }
1451 1452 1453 1454 1455 1456 1457
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    nodeinfo->memory = memorySize / 1024; /* Scale from bytes to kilobytes */
    nodeinfo->cpus = cpuInfo_numCpuCores;
1458
    nodeinfo->mhz = cpuInfo_hz / (1000 * 1000); /* Scale from hz to mhz */
1459 1460 1461 1462 1463 1464 1465 1466 1467
    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 已提交
1468 1469
    result = 0;

1470 1471 1472 1473 1474 1475 1476 1477 1478
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



1479 1480 1481
static char *
esxGetCapabilities(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1482
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1483
    char *xml = virCapabilitiesFormatXML(priv->caps);
1484 1485

    if (xml == NULL) {
1486
        virReportOOMError();
1487 1488 1489 1490 1491 1492 1493 1494
        return NULL;
    }

    return xml;
}



1495 1496 1497
static int
esxListDomains(virConnectPtr conn, int *ids, int maxids)
{
M
Matthias Bolte 已提交
1498
    bool success = false;
M
Matthias Bolte 已提交
1499
    esxPrivate *priv = conn->privateData;
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;

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

1510
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1511
        return -1;
1512 1513
    }

1514
    if (esxVI_String_AppendValueToList(&propertyNameList,
1515
                                       "runtime.powerState") < 0 ||
1516 1517
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1518
        goto cleanup;
1519 1520 1521 1522
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
1523
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1524
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1525
            goto cleanup;
1526 1527 1528 1529 1530 1531 1532 1533 1534
        }

        if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

        if (esxUtil_ParseVirtualMachineIDString(virtualMachine->obj->value,
                                                &ids[count]) < 0 ||
            ids[count] <= 0) {
1535
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1536
                      _("Failed to parse positive integer from '%s'"),
1537
                      virtualMachine->obj->value);
M
Matthias Bolte 已提交
1538
            goto cleanup;
1539 1540 1541 1542 1543 1544 1545 1546 1547
        }

        count++;

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

M
Matthias Bolte 已提交
1548 1549
    success = true;

1550 1551 1552 1553
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
1554
    return success ? count : -1;
1555 1556 1557 1558 1559 1560 1561
}



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

1564
    if (esxVI_EnsureSession(priv->primary) < 0) {
1565 1566 1567
        return -1;
    }

1568
    return esxVI_LookupNumberOfDomainsByPowerState
1569
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, false);
1570 1571 1572 1573 1574 1575 1576
}



static virDomainPtr
esxDomainLookupByID(virConnectPtr conn, int id)
{
M
Matthias Bolte 已提交
1577
    esxPrivate *priv = conn->privateData;
1578 1579 1580 1581
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
M
Matthias Bolte 已提交
1582 1583 1584
    int id_candidate = -1;
    char *name_candidate = NULL;
    unsigned char uuid_candidate[VIR_UUID_BUFLEN];
1585 1586
    virDomainPtr domain = NULL;

1587
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1588
        return NULL;
1589 1590
    }

1591
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1592
                                           "configStatus\0"
1593 1594
                                           "name\0"
                                           "runtime.powerState\0"
1595
                                           "config.uuid\0") < 0 ||
1596 1597
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1598
        goto cleanup;
1599 1600 1601 1602
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
1603
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1604
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1605
            goto cleanup;
1606 1607 1608 1609 1610 1611 1612
        }

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

M
Matthias Bolte 已提交
1613
        VIR_FREE(name_candidate);
1614

1615
        if (esxVI_GetVirtualMachineIdentity(virtualMachine,
M
Matthias Bolte 已提交
1616 1617
                                            &id_candidate, &name_candidate,
                                            uuid_candidate) < 0) {
M
Matthias Bolte 已提交
1618
            goto cleanup;
1619 1620
        }

M
Matthias Bolte 已提交
1621
        if (id != id_candidate) {
1622 1623 1624
            continue;
        }

M
Matthias Bolte 已提交
1625
        domain = virGetDomain(conn, name_candidate, uuid_candidate);
1626 1627

        if (domain == NULL) {
M
Matthias Bolte 已提交
1628
            goto cleanup;
1629 1630 1631 1632 1633 1634 1635 1636
        }

        domain->id = id;

        break;
    }

    if (domain == NULL) {
1637
        ESX_ERROR(VIR_ERR_NO_DOMAIN, _("No domain with ID %d"), id);
1638 1639 1640 1641 1642
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
M
Matthias Bolte 已提交
1643
    VIR_FREE(name_candidate);
1644 1645 1646 1647 1648 1649 1650 1651 1652

    return domain;
}



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

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

1665
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1666
                                           "name\0"
1667
                                           "runtime.powerState\0") < 0 ||
1668
        esxVI_LookupVirtualMachineByUuid(priv->primary, uuid, propertyNameList,
1669
                                         &virtualMachine,
M
Matthias Bolte 已提交
1670
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1671 1672
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, &name, NULL) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1673
        goto cleanup;
1674 1675
    }

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

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

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

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

    return domain;
}



static virDomainPtr
esxDomainLookupByName(virConnectPtr conn, const char *name)
{
M
Matthias Bolte 已提交
1702
    esxPrivate *priv = conn->privateData;
1703 1704 1705
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1706 1707
    int id = -1;
    unsigned char uuid[VIR_UUID_BUFLEN];
1708 1709
    virDomainPtr domain = NULL;

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

1714
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1715
                                           "configStatus\0"
1716
                                           "runtime.powerState\0"
1717
                                           "config.uuid\0") < 0 ||
1718
        esxVI_LookupVirtualMachineByName(priv->primary, name, propertyNameList,
1719 1720
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
1721
        goto cleanup;
1722 1723
    }

1724
    if (virtualMachine == NULL) {
1725
        ESX_ERROR(VIR_ERR_NO_DOMAIN, _("No domain with name '%s'"), name);
M
Matthias Bolte 已提交
1726
        goto cleanup;
1727
    }
1728

M
Matthias Bolte 已提交
1729 1730 1731
    if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, uuid) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
1732
    }
1733

1734
    domain = virGetDomain(conn, name, uuid);
1735

1736
    if (domain == NULL) {
M
Matthias Bolte 已提交
1737
        goto cleanup;
1738 1739
    }

1740 1741 1742 1743 1744
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1745 1746 1747 1748
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1749
    esxVI_ObjectContent_Free(&virtualMachine);
1750 1751 1752 1753 1754 1755 1756 1757 1758

    return domain;
}



static int
esxDomainSuspend(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1759
    int result = -1;
M
Matthias Bolte 已提交
1760
    esxPrivate *priv = domain->conn->privateData;
1761 1762 1763 1764 1765
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1766
    char *taskInfoErrorMessage = NULL;
1767

1768
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1769
        return -1;
1770 1771
    }

1772
    if (esxVI_String_AppendValueToList(&propertyNameList,
1773
                                       "runtime.powerState") < 0 ||
1774
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1775
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1776
           priv->parsedUri->autoAnswer) < 0 ||
1777
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1778
        goto cleanup;
1779 1780 1781
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1782 1783
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1784
        goto cleanup;
1785 1786
    }

1787 1788
    if (esxVI_SuspendVM_Task(priv->primary, virtualMachine->obj, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1789
                                    esxVI_Occurrence_RequiredItem,
1790
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1791
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1792
        goto cleanup;
1793 1794 1795
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1796 1797
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not suspend domain: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
1798
        goto cleanup;
1799 1800
    }

M
Matthias Bolte 已提交
1801 1802
    result = 0;

1803 1804 1805 1806
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1807
    VIR_FREE(taskInfoErrorMessage);
1808 1809 1810 1811 1812 1813 1814 1815 1816

    return result;
}



static int
esxDomainResume(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1817
    int result = -1;
M
Matthias Bolte 已提交
1818
    esxPrivate *priv = domain->conn->privateData;
1819 1820 1821 1822 1823
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1824
    char *taskInfoErrorMessage = NULL;
1825

1826
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1827
        return -1;
1828 1829
    }

1830
    if (esxVI_String_AppendValueToList(&propertyNameList,
1831
                                       "runtime.powerState") < 0 ||
1832
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1833
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1834
           priv->parsedUri->autoAnswer) < 0 ||
1835
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1836
        goto cleanup;
1837 1838 1839
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended) {
1840
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not suspended"));
M
Matthias Bolte 已提交
1841
        goto cleanup;
1842 1843
    }

1844
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
1845
                             &task) < 0 ||
1846
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1847
                                    esxVI_Occurrence_RequiredItem,
1848
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1849
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1850
        goto cleanup;
1851 1852 1853
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1854 1855
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not resume domain: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
1856
        goto cleanup;
1857 1858
    }

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

1861 1862 1863 1864
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1865
    VIR_FREE(taskInfoErrorMessage);
1866 1867 1868 1869 1870 1871 1872 1873 1874

    return result;
}



static int
esxDomainShutdown(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1875
    int result = -1;
M
Matthias Bolte 已提交
1876
    esxPrivate *priv = domain->conn->privateData;
1877 1878 1879 1880
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1881
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1882
        return -1;
1883 1884
    }

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

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

1900
    if (esxVI_ShutdownGuest(priv->primary, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1901
        goto cleanup;
1902 1903
    }

M
Matthias Bolte 已提交
1904 1905
    result = 0;

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

    return result;
}



static int
E
Eric Blake 已提交
1916
esxDomainReboot(virDomainPtr domain, unsigned int flags)
1917
{
M
Matthias Bolte 已提交
1918
    int result = -1;
M
Matthias Bolte 已提交
1919
    esxPrivate *priv = domain->conn->privateData;
1920 1921 1922 1923
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

E
Eric Blake 已提交
1924 1925
    virCheckFlags(0, -1);

1926
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1927
        return -1;
1928 1929
    }

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

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

1945
    if (esxVI_RebootGuest(priv->primary, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1946
        goto cleanup;
1947 1948
    }

M
Matthias Bolte 已提交
1949 1950
    result = 0;

1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
1961 1962
esxDomainDestroyFlags(virDomainPtr domain,
                      unsigned int flags)
1963
{
M
Matthias Bolte 已提交
1964
    int result = -1;
M
Matthias Bolte 已提交
1965
    esxPrivate *priv = domain->conn->privateData;
1966
    esxVI_Context *ctx = NULL;
1967 1968 1969 1970 1971
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1972
    char *taskInfoErrorMessage = NULL;
1973

1974 1975
    virCheckFlags(0, -1);

1976 1977 1978 1979 1980 1981
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

1982
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
1983
        return -1;
1984 1985
    }

1986
    if (esxVI_String_AppendValueToList(&propertyNameList,
1987
                                       "runtime.powerState") < 0 ||
1988
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1989
          (ctx, domain->uuid, propertyNameList, &virtualMachine,
1990
           priv->parsedUri->autoAnswer) < 0 ||
1991
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1992
        goto cleanup;
1993 1994 1995
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1996 1997
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1998
        goto cleanup;
1999 2000
    }

2001
    if (esxVI_PowerOffVM_Task(ctx, virtualMachine->obj, &task) < 0 ||
2002 2003
        esxVI_WaitForTaskCompletion(ctx, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
2004
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2005
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2006
        goto cleanup;
2007 2008 2009
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2010 2011
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not destroy domain: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
2012
        goto cleanup;
2013 2014
    }

2015
    domain->id = -1;
M
Matthias Bolte 已提交
2016 2017
    result = 0;

2018 2019 2020 2021
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
2022
    VIR_FREE(taskInfoErrorMessage);
2023 2024 2025 2026 2027

    return result;
}


2028 2029 2030 2031 2032 2033
static int
esxDomainDestroy(virDomainPtr dom)
{
    return esxDomainDestroyFlags(dom, 0);
}

2034 2035

static char *
2036
esxDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED)
2037
{
2038 2039 2040
    char *osType = strdup("hvm");

    if (osType == NULL) {
2041
        virReportOOMError();
2042 2043 2044 2045
        return NULL;
    }

    return osType;
2046 2047 2048 2049 2050 2051 2052
}



static unsigned long
esxDomainGetMaxMemory(virDomainPtr domain)
{
M
Matthias Bolte 已提交
2053
    esxPrivate *priv = domain->conn->privateData;
2054 2055 2056 2057 2058
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    unsigned long memoryMB = 0;

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

2063
    if (esxVI_String_AppendValueToList(&propertyNameList,
2064
                                       "config.hardware.memoryMB") < 0 ||
2065
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2066
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2067
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2068
        goto cleanup;
2069 2070 2071 2072 2073
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2074
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2075
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2076
                goto cleanup;
2077 2078 2079
            }

            if (dynamicProperty->val->int32 < 0) {
2080 2081
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                          _("Got invalid memory size %d"),
2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104
                          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 已提交
2105
    int result = -1;
M
Matthias Bolte 已提交
2106
    esxPrivate *priv = domain->conn->privateData;
2107
    esxVI_String *propertyNameList = NULL;
2108
    esxVI_ObjectContent *virtualMachine = NULL;
2109
    esxVI_VirtualMachinePowerState powerState;
2110 2111 2112
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2113
    char *taskInfoErrorMessage = NULL;
2114

2115
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2116
        return -1;
2117 2118
    }

2119 2120 2121 2122
    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "runtime.powerState") < 0 ||
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
2123
           priv->parsedUri->autoAnswer) < 0 ||
2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
        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 ||
2135
        esxVI_Long_Alloc(&spec->memoryMB) < 0) {
M
Matthias Bolte 已提交
2136
        goto cleanup;
2137 2138
    }

2139
    /* max-memory must be a multiple of 4096 kilobyte */
2140
    spec->memoryMB->value =
2141
      VIR_DIV_UP(memory, 4096) * 4; /* Scale from kilobytes to megabytes */
2142

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

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

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

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

    return result;
}



static int
esxDomainSetMemory(virDomainPtr domain, unsigned long memory)
{
M
Matthias Bolte 已提交
2176
    int result = -1;
M
Matthias Bolte 已提交
2177
    esxPrivate *priv = domain->conn->privateData;
2178 2179 2180 2181
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2182
    char *taskInfoErrorMessage = NULL;
2183

2184
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2185
        return -1;
2186 2187
    }

2188
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2189
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2190
           priv->parsedUri->autoAnswer) < 0 ||
2191 2192 2193
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0 ||
        esxVI_Long_Alloc(&spec->memoryAllocation->limit) < 0) {
M
Matthias Bolte 已提交
2194
        goto cleanup;
2195 2196 2197
    }

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

2200
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2201
                              &task) < 0 ||
2202
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2203
                                    esxVI_Occurrence_RequiredItem,
2204
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2205
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2206
        goto cleanup;
2207 2208 2209
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2210
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2211 2212
                  _("Could not set memory to %lu kilobytes: %s"), memory,
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
2213
        goto cleanup;
2214 2215
    }

M
Matthias Bolte 已提交
2216 2217
    result = 0;

2218 2219 2220 2221
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2222
    VIR_FREE(taskInfoErrorMessage);
2223 2224 2225 2226 2227 2228

    return result;
}



2229 2230 2231 2232 2233 2234 2235 2236 2237
/*
 * 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

2238 2239 2240
static int
esxDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info)
{
M
Matthias Bolte 已提交
2241
    int result = -1;
M
Matthias Bolte 已提交
2242
    esxPrivate *priv = domain->conn->privateData;
2243 2244 2245 2246 2247
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int64_t memory_limit = -1;
2248
#if ESX_QUERY_FOR_USED_CPU_TIME
2249 2250 2251 2252 2253 2254 2255
    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;
2256 2257
    esxVI_PerfEntityMetricBase *perfEntityMetricBase = NULL;
    esxVI_PerfEntityMetricBase *perfEntityMetricBaseList = NULL;
2258 2259 2260
    esxVI_PerfEntityMetric *perfEntityMetric = NULL;
    esxVI_PerfMetricIntSeries *perfMetricIntSeries = NULL;
    esxVI_Long *value = NULL;
2261
#endif
2262

M
Matthias Bolte 已提交
2263 2264
    memset(info, 0, sizeof (*info));

2265
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2266
        return -1;
2267 2268
    }

2269
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2270 2271 2272 2273
                                           "runtime.powerState\0"
                                           "config.hardware.memoryMB\0"
                                           "config.hardware.numCPU\0"
                                           "config.memoryAllocation.limit\0") < 0 ||
2274
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2275
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2276
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2277
        goto cleanup;
2278 2279 2280 2281 2282 2283 2284 2285
    }

    info->state = VIR_DOMAIN_NOSTATE;

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

2290 2291
            info->state = esxVI_VirtualMachinePowerState_ConvertToLibvirt
                            (powerState);
2292
        } else if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2293
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2294
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2295
                goto cleanup;
2296 2297 2298 2299
            }

            info->maxMem = dynamicProperty->val->int32 * 1024; /* Scale from megabyte to kilobyte */
        } else if (STREQ(dynamicProperty->name, "config.hardware.numCPU")) {
2300
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2301
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2302
                goto cleanup;
2303 2304 2305 2306 2307
            }

            info->nrVirtCpu = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "config.memoryAllocation.limit")) {
2308
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2309
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
2310
                goto cleanup;
2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325
            }

            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;

2326
#if ESX_QUERY_FOR_USED_CPU_TIME
2327
    /* Verify the cached 'used CPU time' performance counter ID */
2328 2329 2330 2331 2332 2333
    /* 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;
            }
2334

2335
            counterId->value = priv->usedCpuTimeCounterId;
2336

2337 2338 2339
            if (esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                goto cleanup;
            }
2340

2341 2342 2343 2344
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfo) < 0) {
                goto cleanup;
            }
2345

2346 2347 2348 2349 2350
            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);
2351

2352 2353 2354 2355 2356
                priv->usedCpuTimeCounterId = -1;
            }

            esxVI_Int_Free(&counterIdList);
            esxVI_PerfCounterInfo_Free(&perfCounterInfo);
2357 2358
        }

2359 2360 2361 2362 2363 2364 2365 2366 2367 2368
        /*
         * 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;
            }
2369

2370 2371 2372 2373
            for (perfMetricId = perfMetricIdList; perfMetricId != NULL;
                 perfMetricId = perfMetricId->_next) {
                VIR_DEBUG("perfMetricId counterId %d, instance '%s'",
                          perfMetricId->counterId->value, perfMetricId->instance);
2374

2375
                counterId = NULL;
2376

2377 2378 2379 2380 2381
                if (esxVI_Int_DeepCopy(&counterId, perfMetricId->counterId) < 0 ||
                    esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                    goto cleanup;
                }
            }
2382

2383 2384
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfoList) < 0) {
M
Matthias Bolte 已提交
2385
                goto cleanup;
2386 2387
            }

2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404
            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;
                }
2405 2406
            }

2407
            if (priv->usedCpuTimeCounterId < 0) {
2408
                VIR_WARN("Could not find 'used CPU time' performance counter");
2409
            }
2410 2411
        }

2412 2413 2414 2415 2416 2417
        /*
         * 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);
2418

2419 2420 2421 2422 2423 2424
            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;
            }
2425

2426 2427 2428 2429 2430 2431 2432 2433 2434 2435
            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;
            }
2436

2437 2438 2439
            for (perfEntityMetricBase = perfEntityMetricBaseList;
                 perfEntityMetricBase != NULL;
                 perfEntityMetricBase = perfEntityMetricBase->_next) {
2440
                VIR_DEBUG("perfEntityMetric ...");
2441

2442 2443
                perfEntityMetric =
                  esxVI_PerfEntityMetric_DynamicCast(perfEntityMetricBase);
2444

2445
                if (perfEntityMetric == NULL) {
2446 2447
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                              _("QueryPerf returned object with unexpected type '%s'"),
2448
                              esxVI_Type_ToString(perfEntityMetricBase->_type));
2449
                    goto cleanup;
2450
                }
2451

2452 2453
                perfMetricIntSeries =
                  esxVI_PerfMetricIntSeries_DynamicCast(perfEntityMetric->value);
2454

2455
                if (perfMetricIntSeries == NULL) {
2456 2457
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                              _("QueryPerf returned object with unexpected type '%s'"),
2458
                              esxVI_Type_ToString(perfEntityMetric->value->_type));
2459
                    goto cleanup;
2460
                }
2461

2462 2463
                for (; perfMetricIntSeries != NULL;
                     perfMetricIntSeries = perfMetricIntSeries->_next) {
2464
                    VIR_DEBUG("perfMetricIntSeries ...");
2465

2466 2467 2468 2469 2470
                    for (value = perfMetricIntSeries->value;
                         value != NULL;
                         value = value->_next) {
                        VIR_DEBUG("value %lld", (long long int)value->value);
                    }
2471 2472 2473
                }
            }

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

2476
            /*
E
Eric Blake 已提交
2477
             * FIXME: Cannot map between relative used-cpu-time and absolute
2478 2479 2480
             *        info->cpuTime
             */
        }
2481
    }
2482
#endif
2483

M
Matthias Bolte 已提交
2484 2485
    result = 0;

2486
  cleanup:
2487
#if ESX_QUERY_FOR_USED_CPU_TIME
2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499
    /*
     * 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;
        }
    }
2500
#endif
2501

2502 2503
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2504
#if ESX_QUERY_FOR_USED_CPU_TIME
2505 2506 2507 2508
    esxVI_PerfMetricId_Free(&perfMetricIdList);
    esxVI_Int_Free(&counterIdList);
    esxVI_PerfCounterInfo_Free(&perfCounterInfoList);
    esxVI_PerfQuerySpec_Free(&querySpec);
2509
    esxVI_PerfEntityMetricBase_Free(&perfEntityMetricBaseList);
2510
#endif
2511 2512 2513 2514 2515 2516

    return result;
}



2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559
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;
}



2560
static int
2561 2562
esxDomainSetVcpusFlags(virDomainPtr domain, unsigned int nvcpus,
                       unsigned int flags)
2563
{
M
Matthias Bolte 已提交
2564
    int result = -1;
M
Matthias Bolte 已提交
2565
    esxPrivate *priv = domain->conn->privateData;
M
Matthias Bolte 已提交
2566
    int maxVcpus;
2567 2568 2569 2570
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2571
    char *taskInfoErrorMessage = NULL;
2572

2573
    if (flags != VIR_DOMAIN_AFFECT_LIVE) {
2574 2575 2576 2577
        ESX_ERROR(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
        return -1;
    }

2578
    if (nvcpus < 1) {
2579 2580
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Requested number of virtual CPUs must at least be 1"));
M
Matthias Bolte 已提交
2581
        return -1;
2582 2583
    }

2584
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2585
        return -1;
2586 2587
    }

M
Matthias Bolte 已提交
2588
    maxVcpus = esxDomainGetMaxVcpus(domain);
2589

M
Matthias Bolte 已提交
2590
    if (maxVcpus < 0) {
M
Matthias Bolte 已提交
2591
        return -1;
2592 2593
    }

M
Matthias Bolte 已提交
2594
    if (nvcpus > maxVcpus) {
2595
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2596 2597
                  _("Requested number of virtual CPUs is greater than max "
                    "allowable number of virtual CPUs for the domain: %d > %d"),
M
Matthias Bolte 已提交
2598
                  nvcpus, maxVcpus);
M
Matthias Bolte 已提交
2599
        return -1;
2600 2601
    }

2602
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2603
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2604
           priv->parsedUri->autoAnswer) < 0 ||
2605 2606
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Int_Alloc(&spec->numCPUs) < 0) {
M
Matthias Bolte 已提交
2607
        goto cleanup;
2608 2609 2610 2611
    }

    spec->numCPUs->value = nvcpus;

2612
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2613
                              &task) < 0 ||
2614
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2615
                                    esxVI_Occurrence_RequiredItem,
2616
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2617
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2618
        goto cleanup;
2619 2620 2621
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2622
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2623 2624
                  _("Could not set number of virtual CPUs to %d: %s"), nvcpus,
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
2625
        goto cleanup;
2626 2627
    }

M
Matthias Bolte 已提交
2628 2629
    result = 0;

2630 2631 2632 2633
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2634
    VIR_FREE(taskInfoErrorMessage);
2635 2636 2637 2638 2639

    return result;
}


M
Matthias Bolte 已提交
2640

2641 2642 2643
static int
esxDomainSetVcpus(virDomainPtr domain, unsigned int nvcpus)
{
2644
    return esxDomainSetVcpusFlags(domain, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
2645 2646
}

2647

M
Matthias Bolte 已提交
2648

2649
static int
2650
esxDomainGetVcpusFlags(virDomainPtr domain, unsigned int flags)
2651
{
M
Matthias Bolte 已提交
2652
    esxPrivate *priv = domain->conn->privateData;
2653 2654 2655 2656
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

2657
    if (flags != (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_VCPU_MAXIMUM)) {
2658 2659 2660 2661
        ESX_ERROR(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
        return -1;
    }

M
Matthias Bolte 已提交
2662 2663
    if (priv->maxVcpus > 0) {
        return priv->maxVcpus;
2664 2665
    }

M
Matthias Bolte 已提交
2666 2667
    priv->maxVcpus = -1;

2668
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2669
        return -1;
2670 2671
    }

2672
    if (esxVI_String_AppendValueToList(&propertyNameList,
2673
                                       "capability.maxSupportedVcpus") < 0 ||
2674 2675
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
2676
        goto cleanup;
2677 2678 2679
    }

    if (hostSystem == NULL) {
2680 2681
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
2682
        goto cleanup;
2683 2684 2685 2686 2687
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "capability.maxSupportedVcpus")) {
2688
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2689
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2690
                goto cleanup;
2691 2692
            }

M
Matthias Bolte 已提交
2693
            priv->maxVcpus = dynamicProperty->val->int32;
2694 2695 2696 2697 2698 2699 2700 2701 2702 2703
            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

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

M
Matthias Bolte 已提交
2704
    return priv->maxVcpus;
2705 2706
}

M
Matthias Bolte 已提交
2707 2708


2709 2710 2711
static int
esxDomainGetMaxVcpus(virDomainPtr domain)
{
2712
    return esxDomainGetVcpusFlags(domain, (VIR_DOMAIN_AFFECT_LIVE |
2713 2714
                                           VIR_DOMAIN_VCPU_MAXIMUM));
}
2715

M
Matthias Bolte 已提交
2716 2717


2718
static char *
2719
esxDomainGetXMLDesc(virDomainPtr domain, unsigned int flags)
2720
{
M
Matthias Bolte 已提交
2721
    esxPrivate *priv = domain->conn->privateData;
2722 2723
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
2724 2725
    esxVI_VirtualMachinePowerState powerState;
    int id;
2726
    char *vmPathName = NULL;
2727
    char *datastoreName = NULL;
M
Matthias Bolte 已提交
2728
    char *directoryName = NULL;
2729
    char *directoryAndFileName = NULL;
2730
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
2731 2732
    char *url = NULL;
    char *vmx = NULL;
2733
    virVMXContext ctx;
2734
    esxVMX_Data data;
2735 2736 2737
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2738 2739
    /* Flags checked by virDomainDefFormat */

2740 2741
    memset(&data, 0, sizeof (data));

2742
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2743
        return NULL;
2744 2745
    }

2746 2747 2748
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "config.files.vmPathName\0"
                                           "runtime.powerState\0") < 0 ||
2749
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2750
                                         propertyNameList, &virtualMachine,
2751
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2752 2753
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0 ||
2754 2755
        esxVI_GetStringValue(virtualMachine, "config.files.vmPathName",
                             &vmPathName, esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2756
        goto cleanup;
2757 2758
    }

2759
    if (esxUtil_ParseDatastorePath(vmPathName, &datastoreName, &directoryName,
2760
                                   &directoryAndFileName) < 0) {
M
Matthias Bolte 已提交
2761
        goto cleanup;
2762 2763
    }

2764
    virBufferAsprintf(&buffer, "%s://%s:%d/folder/", priv->parsedUri->transport,
2765
                      domain->conn->uri->server, domain->conn->uri->port);
2766
    virBufferURIEncodeString(&buffer, directoryAndFileName);
2767
    virBufferAddLit(&buffer, "?dcPath=");
2768
    virBufferURIEncodeString(&buffer, priv->primary->datacenter->name);
2769 2770 2771 2772
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
2773
        virReportOOMError();
M
Matthias Bolte 已提交
2774
        goto cleanup;
2775 2776
    }

2777 2778
    url = virBufferContentAndReset(&buffer);

2779
    if (esxVI_CURL_Download(priv->primary->curl, url, &vmx) < 0) {
M
Matthias Bolte 已提交
2780
        goto cleanup;
2781 2782
    }

2783
    data.ctx = priv->primary;
2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797

    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;
        }
    }
2798 2799 2800 2801 2802 2803

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

2804
    def = virVMXParseConfig(&ctx, priv->caps, vmx);
2805 2806

    if (def != NULL) {
2807 2808 2809 2810
        if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
            def->id = id;
        }

2811
        xml = virDomainDefFormat(def, flags);
2812 2813 2814
    }

  cleanup:
M
Matthias Bolte 已提交
2815 2816 2817 2818
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

2819 2820
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2821
    VIR_FREE(datastoreName);
M
Matthias Bolte 已提交
2822
    VIR_FREE(directoryName);
2823
    VIR_FREE(directoryAndFileName);
2824
    VIR_FREE(url);
2825
    VIR_FREE(data.datastorePathWithoutFileName);
2826
    VIR_FREE(vmx);
2827
    virDomainDefFree(def);
2828 2829 2830 2831 2832 2833 2834 2835 2836

    return xml;
}



static char *
esxDomainXMLFromNative(virConnectPtr conn, const char *nativeFormat,
                       const char *nativeConfig,
E
Eric Blake 已提交
2837
                       unsigned int flags)
2838
{
M
Matthias Bolte 已提交
2839
    esxPrivate *priv = conn->privateData;
2840
    virVMXContext ctx;
2841
    esxVMX_Data data;
2842 2843 2844
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2845 2846
    virCheckFlags(0, NULL);

2847 2848
    memset(&data, 0, sizeof (data));

2849
    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2850
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2851
                  _("Unsupported config format '%s'"), nativeFormat);
2852
        return NULL;
2853 2854
    }

2855
    data.ctx = priv->primary;
2856
    data.datastorePathWithoutFileName = (char *)"[?] ?";
2857 2858 2859 2860 2861 2862

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

2863
    def = virVMXParseConfig(&ctx, priv->caps, nativeConfig);
2864 2865

    if (def != NULL) {
2866
        xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
2867 2868 2869 2870 2871 2872 2873 2874 2875
    }

    virDomainDefFree(def);

    return xml;
}



M
Matthias Bolte 已提交
2876 2877 2878
static char *
esxDomainXMLToNative(virConnectPtr conn, const char *nativeFormat,
                     const char *domainXml,
E
Eric Blake 已提交
2879
                     unsigned int flags)
M
Matthias Bolte 已提交
2880
{
M
Matthias Bolte 已提交
2881
    esxPrivate *priv = conn->privateData;
2882 2883
    int virtualHW_version;
    virVMXContext ctx;
2884
    esxVMX_Data data;
M
Matthias Bolte 已提交
2885 2886 2887
    virDomainDefPtr def = NULL;
    char *vmx = NULL;

E
Eric Blake 已提交
2888 2889
    virCheckFlags(0, NULL);

2890 2891
    memset(&data, 0, sizeof (data));

M
Matthias Bolte 已提交
2892
    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2893
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2894
                  _("Unsupported config format '%s'"), nativeFormat);
M
Matthias Bolte 已提交
2895 2896 2897
        return NULL;
    }

2898 2899 2900 2901 2902 2903 2904
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        return NULL;
    }

M
Matthias Bolte 已提交
2905 2906
    def = virDomainDefParseString(priv->caps, domainXml,
                                  1 << VIR_DOMAIN_VIRT_VMWARE, 0);
M
Matthias Bolte 已提交
2907 2908 2909 2910 2911

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

2912
    data.ctx = priv->primary;
2913
    data.datastorePathWithoutFileName = NULL;
2914 2915 2916 2917 2918 2919

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

2920
    vmx = virVMXFormatConfig(&ctx, priv->caps, def, virtualHW_version);
M
Matthias Bolte 已提交
2921 2922 2923 2924 2925 2926 2927 2928

    virDomainDefFree(def);

    return vmx;
}



2929 2930 2931
static int
esxListDefinedDomains(virConnectPtr conn, char **const names, int maxnames)
{
M
Matthias Bolte 已提交
2932
    bool success = false;
M
Matthias Bolte 已提交
2933
    esxPrivate *priv = conn->privateData;
2934 2935 2936 2937 2938
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;
2939
    int i;
2940 2941 2942 2943 2944

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

2945
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2946
        return -1;
2947 2948
    }

2949
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2950 2951
                                           "name\0"
                                           "runtime.powerState\0") < 0 ||
2952 2953
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2954
        goto cleanup;
2955 2956 2957 2958
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
2959
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
2960
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
2961
            goto cleanup;
2962 2963 2964 2965 2966 2967
        }

        if (powerState == esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

2968
        names[count] = NULL;
2969

2970 2971 2972
        if (esxVI_GetVirtualMachineIdentity(virtualMachine, NULL, &names[count],
                                            NULL) < 0) {
            goto cleanup;
2973 2974
        }

2975 2976
        ++count;

2977 2978 2979 2980 2981
        if (count >= maxnames) {
            break;
        }
    }

M
Matthias Bolte 已提交
2982
    success = true;
2983

M
Matthias Bolte 已提交
2984 2985 2986 2987 2988
  cleanup:
    if (! success) {
        for (i = 0; i < count; ++i) {
            VIR_FREE(names[i]);
        }
2989

M
Matthias Bolte 已提交
2990
        count = -1;
2991 2992
    }

M
Matthias Bolte 已提交
2993 2994
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
2995

M
Matthias Bolte 已提交
2996
    return count;
2997 2998 2999 3000 3001 3002 3003
}



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

3006
    if (esxVI_EnsureSession(priv->primary) < 0) {
3007 3008 3009
        return -1;
    }

3010
    return esxVI_LookupNumberOfDomainsByPowerState
3011
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, true);
3012 3013 3014 3015 3016
}



static int
3017
esxDomainCreateWithFlags(virDomainPtr domain, unsigned int flags)
3018
{
M
Matthias Bolte 已提交
3019
    int result = -1;
M
Matthias Bolte 已提交
3020
    esxPrivate *priv = domain->conn->privateData;
3021 3022 3023
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
3024
    int id = -1;
3025 3026
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3027
    char *taskInfoErrorMessage = NULL;
3028

3029 3030
    virCheckFlags(0, -1);

3031
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3032
        return -1;
3033 3034
    }

3035
    if (esxVI_String_AppendValueToList(&propertyNameList,
3036
                                       "runtime.powerState") < 0 ||
3037
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3038
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
3039
           priv->parsedUri->autoAnswer) < 0 ||
3040 3041
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0) {
M
Matthias Bolte 已提交
3042
        goto cleanup;
3043 3044 3045
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
3046 3047
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered off"));
M
Matthias Bolte 已提交
3048
        goto cleanup;
3049 3050
    }

3051
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
3052
                             &task) < 0 ||
3053
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3054
                                    esxVI_Occurrence_RequiredItem,
3055
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3056
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3057
        goto cleanup;
3058 3059 3060
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3061 3062
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not start domain: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
3063
        goto cleanup;
3064 3065
    }

3066
    domain->id = id;
M
Matthias Bolte 已提交
3067 3068
    result = 0;

3069 3070 3071 3072
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
3073
    VIR_FREE(taskInfoErrorMessage);
3074 3075 3076 3077

    return result;
}

3078 3079


3080 3081 3082 3083 3084
static int
esxDomainCreate(virDomainPtr domain)
{
    return esxDomainCreateWithFlags(domain, 0);
}
3085

3086 3087


M
Matthias Bolte 已提交
3088
static virDomainPtr
3089
esxDomainDefineXML(virConnectPtr conn, const char *xml)
M
Matthias Bolte 已提交
3090
{
M
Matthias Bolte 已提交
3091
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
3092 3093
    virDomainDefPtr def = NULL;
    char *vmx = NULL;
3094 3095
    int i;
    virDomainDiskDefPtr disk = NULL;
M
Matthias Bolte 已提交
3096
    esxVI_ObjectContent *virtualMachine = NULL;
3097 3098
    int virtualHW_version;
    virVMXContext ctx;
3099
    esxVMX_Data data;
M
Matthias Bolte 已提交
3100 3101
    char *datastoreName = NULL;
    char *directoryName = NULL;
3102
    char *escapedName = NULL;
M
Matthias Bolte 已提交
3103 3104 3105 3106 3107 3108 3109 3110
    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;
3111
    char *taskInfoErrorMessage = NULL;
M
Matthias Bolte 已提交
3112 3113
    virDomainPtr domain = NULL;

3114 3115
    memset(&data, 0, sizeof (data));

3116
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3117
        return NULL;
M
Matthias Bolte 已提交
3118 3119 3120
    }

    /* Parse domain XML */
M
Matthias Bolte 已提交
3121
    def = virDomainDefParseString(priv->caps, xml, 1 << VIR_DOMAIN_VIRT_VMWARE,
M
Matthias Bolte 已提交
3122 3123 3124
                                  VIR_DOMAIN_XML_INACTIVE);

    if (def == NULL) {
M
Matthias Bolte 已提交
3125
        return NULL;
M
Matthias Bolte 已提交
3126 3127 3128
    }

    /* Check if an existing domain should be edited */
3129
    if (esxVI_LookupVirtualMachineByUuid(priv->primary, def->uuid, NULL,
M
Matthias Bolte 已提交
3130
                                         &virtualMachine,
M
Matthias Bolte 已提交
3131
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
3132
        goto cleanup;
M
Matthias Bolte 已提交
3133 3134
    }

3135 3136 3137 3138 3139 3140 3141
    if (virtualMachine == NULL &&
        esxVI_LookupVirtualMachineByName(priv->primary, def->name, NULL,
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
    }

M
Matthias Bolte 已提交
3142 3143
    if (virtualMachine != NULL) {
        /* FIXME */
3144 3145 3146
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Domain already exists, editing existing domains is not "
                    "supported yet"));
M
Matthias Bolte 已提交
3147
        goto cleanup;
M
Matthias Bolte 已提交
3148 3149 3150
    }

    /* Build VMX from domain XML */
3151 3152 3153 3154 3155 3156 3157
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        goto cleanup;
    }

3158
    data.ctx = priv->primary;
3159
    data.datastorePathWithoutFileName = NULL;
3160 3161 3162 3163 3164 3165

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

3166
    vmx = virVMXFormatConfig(&ctx, priv->caps, def, virtualHW_version);
M
Matthias Bolte 已提交
3167 3168

    if (vmx == NULL) {
M
Matthias Bolte 已提交
3169
        goto cleanup;
M
Matthias Bolte 已提交
3170 3171
    }

3172 3173 3174 3175 3176 3177 3178
    /*
     * 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 已提交
3179
    if (def->ndisks < 1) {
3180 3181 3182
        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 已提交
3183
        goto cleanup;
3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194
    }

    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) {
3195 3196 3197
        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 已提交
3198
        goto cleanup;
M
Matthias Bolte 已提交
3199 3200
    }

3201
    if (disk->src == NULL) {
3202 3203 3204
        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 已提交
3205
        goto cleanup;
M
Matthias Bolte 已提交
3206 3207
    }

3208
    if (esxUtil_ParseDatastorePath(disk->src, &datastoreName, &directoryName,
3209
                                   NULL) < 0) {
M
Matthias Bolte 已提交
3210
        goto cleanup;
M
Matthias Bolte 已提交
3211 3212
    }

3213
    if (! virFileHasSuffix(disk->src, ".vmdk")) {
3214
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3215 3216
                  _("Expecting source '%s' of first file-based harddisk to "
                    "be a VMDK image"), disk->src);
M
Matthias Bolte 已提交
3217
        goto cleanup;
M
Matthias Bolte 已提交
3218 3219
    }

3220
    virBufferAsprintf(&buffer, "%s://%s:%d/folder/", priv->parsedUri->transport,
M
Matthias Bolte 已提交
3221 3222 3223 3224 3225 3226 3227
                      conn->uri->server, conn->uri->port);

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

3228 3229 3230 3231 3232 3233 3234
    escapedName = esxUtil_EscapeDatastoreItem(def->name);

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

    virBufferURIEncodeString(&buffer, escapedName);
M
Matthias Bolte 已提交
3235
    virBufferAddLit(&buffer, ".vmx?dcPath=");
3236
    virBufferURIEncodeString(&buffer, priv->primary->datacenter->name);
M
Matthias Bolte 已提交
3237 3238 3239 3240
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
3241
        virReportOOMError();
M
Matthias Bolte 已提交
3242
        goto cleanup;
M
Matthias Bolte 已提交
3243 3244 3245 3246
    }

    url = virBufferContentAndReset(&buffer);

3247 3248 3249 3250 3251 3252
    /* Check, if VMX file already exists */
    /* FIXME */

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

3253
    if (esxVI_CURL_Upload(priv->primary->curl, url, vmx) < 0) {
3254 3255 3256 3257
        goto cleanup;
    }

    /* Register the domain */
M
Matthias Bolte 已提交
3258 3259
    if (directoryName != NULL) {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s/%s.vmx", datastoreName,
3260
                        directoryName, escapedName) < 0) {
3261
            virReportOOMError();
M
Matthias Bolte 已提交
3262
            goto cleanup;
M
Matthias Bolte 已提交
3263 3264 3265
        }
    } else {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s.vmx", datastoreName,
3266
                        escapedName) < 0) {
3267
            virReportOOMError();
M
Matthias Bolte 已提交
3268
            goto cleanup;
M
Matthias Bolte 已提交
3269 3270 3271
        }
    }

3272
    if (esxVI_RegisterVM_Task(priv->primary, priv->primary->datacenter->vmFolder,
M
Matthias Bolte 已提交
3273
                              datastoreRelatedPath, NULL, esxVI_Boolean_False,
3274 3275 3276 3277
                              priv->primary->computeResource->resourcePool,
                              priv->primary->hostSystem->_reference,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, def->uuid,
3278
                                    esxVI_Occurrence_OptionalItem,
3279
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3280
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3281
        goto cleanup;
M
Matthias Bolte 已提交
3282 3283 3284
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3285 3286
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not define domain: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
3287
        goto cleanup;
M
Matthias Bolte 已提交
3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298
    }

    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 已提交
3299 3300 3301 3302
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

M
Matthias Bolte 已提交
3303 3304 3305 3306
    virDomainDefFree(def);
    VIR_FREE(vmx);
    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
3307
    VIR_FREE(escapedName);
M
Matthias Bolte 已提交
3308 3309 3310 3311 3312 3313 3314
    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);
3315
    VIR_FREE(taskInfoErrorMessage);
M
Matthias Bolte 已提交
3316 3317 3318 3319 3320 3321

    return domain;
}



3322
static int
3323 3324
esxDomainUndefineFlags(virDomainPtr domain,
                       unsigned int flags)
3325
{
M
Matthias Bolte 已提交
3326
    int result = -1;
M
Matthias Bolte 已提交
3327
    esxPrivate *priv = domain->conn->privateData;
3328
    esxVI_Context *ctx = NULL;
3329 3330 3331 3332
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

3333 3334 3335 3336
    /* No managed save, so we explicitly reject
     * VIR_DOMAIN_UNDEFINE_MANAGED_SAVE.  No snapshot metadata for
     * ESX, so we can trivially ignore that flag.  */
    virCheckFlags(VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA, -1);
3337

3338 3339 3340 3341 3342 3343
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

3344
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
3345
        return -1;
3346 3347
    }

3348
    if (esxVI_String_AppendValueToList(&propertyNameList,
3349
                                       "runtime.powerState") < 0 ||
3350 3351
        esxVI_LookupVirtualMachineByUuid(ctx, domain->uuid, propertyNameList,
                                         &virtualMachine,
M
Matthias Bolte 已提交
3352
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3353
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
3354
        goto cleanup;
3355 3356 3357 3358
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended &&
        powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
3359 3360
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not suspended or powered off"));
M
Matthias Bolte 已提交
3361
        goto cleanup;
3362 3363
    }

3364
    if (esxVI_UnregisterVM(ctx, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
3365
        goto cleanup;
3366 3367
    }

M
Matthias Bolte 已提交
3368 3369
    result = 0;

3370 3371 3372 3373 3374 3375 3376 3377
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}


3378 3379 3380 3381 3382
static int
esxDomainUndefine(virDomainPtr domain)
{
    return esxDomainUndefineFlags(domain, 0);
}
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 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562
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;
}



3563 3564 3565 3566 3567 3568 3569 3570 3571 3572
/*
 * 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:
 *
3573
 * - reservation (VIR_TYPED_PARAM_LLONG >= 0, in megaherz)
3574
 *
3575
 *   The amount of CPU resource that is guaranteed to be available to the domain.
3576 3577
 *
 *
3578
 * - limit (VIR_TYPED_PARAM_LLONG >= 0, or -1, in megaherz)
3579
 *
3580 3581
 *   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
3582 3583 3584 3585
 *   utilization of the domain is unlimited. If the limit is not set to -1, it
 *   must be greater than or equal to the reservation.
 *
 *
3586
 * - shares (VIR_TYPED_PARAM_INT >= 0, or in {-1, -2, -3}, no unit)
3587 3588 3589 3590 3591 3592
 *
 *   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'.
 */
3593
static char *
3594
esxDomainGetSchedulerType(virDomainPtr domain ATTRIBUTE_UNUSED, int *nparams)
3595 3596 3597 3598
{
    char *type = strdup("allocation");

    if (type == NULL) {
3599
        virReportOOMError();
3600
        return NULL;
3601 3602
    }

3603 3604 3605
    if (nparams != NULL) {
        *nparams = 3; /* reservation, limit, shares */
    }
3606 3607 3608 3609 3610 3611 3612

    return type;
}



static int
3613 3614 3615
esxDomainGetSchedulerParametersFlags(virDomainPtr domain,
                                     virTypedParameterPtr params, int *nparams,
                                     unsigned int flags)
3616
{
M
Matthias Bolte 已提交
3617
    int result = -1;
M
Matthias Bolte 已提交
3618
    esxPrivate *priv = domain->conn->privateData;
3619 3620 3621 3622 3623 3624 3625
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    unsigned int mask = 0;
    int i = 0;

3626 3627
    virCheckFlags(0, -1);

3628
    if (*nparams < 3) {
3629 3630
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Parameter array must have space for 3 items"));
M
Matthias Bolte 已提交
3631
        return -1;
3632 3633
    }

3634
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3635
        return -1;
3636 3637
    }

3638
    if (esxVI_String_AppendValueListToList(&propertyNameList,
3639 3640 3641
                                           "config.cpuAllocation.reservation\0"
                                           "config.cpuAllocation.limit\0"
                                           "config.cpuAllocation.shares\0") < 0 ||
3642
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
3643
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3644
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3645
        goto cleanup;
3646 3647 3648 3649 3650 3651
    }

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

3656
            params[i].type = VIR_TYPED_PARAM_LLONG;
3657

3658
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3659
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3660
                goto cleanup;
3661 3662 3663 3664 3665 3666 3667
            }

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

3672
            params[i].type = VIR_TYPED_PARAM_LLONG;
3673

3674
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3675
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3676
                goto cleanup;
3677 3678 3679 3680 3681 3682 3683
            }

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

3688
            params[i].type = VIR_TYPED_PARAM_INT;
3689

3690
            if (esxVI_SharesInfo_CastFromAnyType(dynamicProperty->val,
3691
                                                 &sharesInfo) < 0) {
M
Matthias Bolte 已提交
3692
                goto cleanup;
3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712
            }

            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:
3713
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3714
                          _("Shares level has unknown value %d"),
3715
                          (int)sharesInfo->level);
M
Matthias Bolte 已提交
3716
                goto cleanup;
3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728
            }

            esxVI_SharesInfo_Free(&sharesInfo);

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

    *nparams = i;
M
Matthias Bolte 已提交
3729
    result = 0;
3730 3731 3732 3733 3734 3735 3736 3737

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

    return result;
}

3738 3739 3740 3741 3742 3743
static int
esxDomainGetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int *nparams)
{
    return esxDomainGetSchedulerParametersFlags(domain, params, nparams, 0);
}
3744 3745 3746


static int
3747 3748 3749
esxDomainSetSchedulerParametersFlags(virDomainPtr domain,
                                     virTypedParameterPtr params, int nparams,
                                     unsigned int flags)
3750
{
M
Matthias Bolte 已提交
3751
    int result = -1;
M
Matthias Bolte 已提交
3752
    esxPrivate *priv = domain->conn->privateData;
3753 3754 3755 3756 3757
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3758
    char *taskInfoErrorMessage = NULL;
3759 3760
    int i;

3761 3762
    virCheckFlags(0, -1);

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

3767
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3768
          (priv->primary, domain->uuid, NULL, &virtualMachine,
3769
           priv->parsedUri->autoAnswer) < 0 ||
3770 3771
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->cpuAllocation) < 0) {
M
Matthias Bolte 已提交
3772
        goto cleanup;
3773 3774 3775 3776
    }

    for (i = 0; i < nparams; ++i) {
        if (STREQ (params[i].field, "reservation") &&
3777
            params[i].type == VIR_TYPED_PARAM_LLONG) {
3778
            if (esxVI_Long_Alloc(&spec->cpuAllocation->reservation) < 0) {
M
Matthias Bolte 已提交
3779
                goto cleanup;
3780 3781 3782
            }

            if (params[i].value.l < 0) {
3783
                ESX_ERROR(VIR_ERR_INVALID_ARG,
3784 3785
                          _("Could not set reservation to %lld MHz, expecting "
                            "positive value"), params[i].value.l);
M
Matthias Bolte 已提交
3786
                goto cleanup;
3787 3788 3789 3790
            }

            spec->cpuAllocation->reservation->value = params[i].value.l;
        } else if (STREQ (params[i].field, "limit") &&
3791
                   params[i].type == VIR_TYPED_PARAM_LLONG) {
3792
            if (esxVI_Long_Alloc(&spec->cpuAllocation->limit) < 0) {
M
Matthias Bolte 已提交
3793
                goto cleanup;
3794 3795 3796
            }

            if (params[i].value.l < -1) {
3797
                ESX_ERROR(VIR_ERR_INVALID_ARG,
3798 3799
                          _("Could not set limit to %lld MHz, expecting "
                            "positive value or -1 (unlimited)"),
3800
                          params[i].value.l);
M
Matthias Bolte 已提交
3801
                goto cleanup;
3802 3803 3804 3805
            }

            spec->cpuAllocation->limit->value = params[i].value.l;
        } else if (STREQ (params[i].field, "shares") &&
3806
                   params[i].type == VIR_TYPED_PARAM_INT) {
3807 3808
            if (esxVI_SharesInfo_Alloc(&sharesInfo) < 0 ||
                esxVI_Int_Alloc(&sharesInfo->shares) < 0) {
M
Matthias Bolte 已提交
3809
                goto cleanup;
3810 3811 3812 3813
            }

            spec->cpuAllocation->shares = sharesInfo;

3814
            if (params[i].value.i >= 0) {
3815
                spec->cpuAllocation->shares->level = esxVI_SharesLevel_Custom;
3816
                spec->cpuAllocation->shares->shares->value = params[i].value.i;
3817
            } else {
3818
                switch (params[i].value.i) {
3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836
                  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:
3837
                    ESX_ERROR(VIR_ERR_INVALID_ARG,
3838 3839
                              _("Could not set shares to %d, expecting positive "
                                "value or -1 (low), -2 (normal) or -3 (high)"),
3840
                              params[i].value.i);
M
Matthias Bolte 已提交
3841
                    goto cleanup;
3842 3843 3844
                }
            }
        } else {
3845
            ESX_ERROR(VIR_ERR_INVALID_ARG, _("Unknown field '%s'"),
3846
                      params[i].field);
M
Matthias Bolte 已提交
3847
            goto cleanup;
3848 3849 3850
        }
    }

3851
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
3852
                              &task) < 0 ||
3853
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3854
                                    esxVI_Occurrence_RequiredItem,
3855
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3856
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3857
        goto cleanup;
3858 3859 3860
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3861 3862 3863
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not change scheduler parameters: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
3864
        goto cleanup;
3865 3866
    }

M
Matthias Bolte 已提交
3867 3868
    result = 0;

3869 3870 3871 3872
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
3873
    VIR_FREE(taskInfoErrorMessage);
3874 3875 3876 3877

    return result;
}

3878 3879 3880 3881 3882 3883
static int
esxDomainSetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int nparams)
{
    return esxDomainSetSchedulerParametersFlags(domain, params, nparams, 0);
}
3884

E
Eric Blake 已提交
3885 3886 3887 3888 3889 3890
/* 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)
3891 3892 3893 3894 3895

static int
esxDomainMigratePrepare(virConnectPtr dconn,
                        char **cookie ATTRIBUTE_UNUSED,
                        int *cookielen ATTRIBUTE_UNUSED,
3896 3897
                        const char *uri_in ATTRIBUTE_UNUSED,
                        char **uri_out,
E
Eric Blake 已提交
3898
                        unsigned long flags,
3899 3900 3901
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
3902
    esxPrivate *priv = dconn->privateData;
3903

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

3906
    if (uri_in == NULL) {
3907 3908 3909 3910
        if (virAsprintf(uri_out, "vpxmigr://%s/%s/%s",
                        priv->vCenter->ipAddress,
                        priv->vCenter->computeResource->resourcePool->value,
                        priv->vCenter->hostSystem->_reference->value) < 0) {
3911
            virReportOOMError();
3912
            return -1;
3913 3914 3915
        }
    }

3916
    return 0;
3917 3918 3919 3920 3921 3922 3923 3924 3925
}



static int
esxDomainMigratePerform(virDomainPtr domain,
                        const char *cookie ATTRIBUTE_UNUSED,
                        int cookielen ATTRIBUTE_UNUSED,
                        const char *uri,
E
Eric Blake 已提交
3926
                        unsigned long flags,
3927 3928 3929
                        const char *dname,
                        unsigned long bandwidth ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
3930
    int result = -1;
M
Matthias Bolte 已提交
3931
    esxPrivate *priv = domain->conn->privateData;
3932 3933 3934 3935
    xmlURIPtr parsedUri = NULL;
    char *saveptr;
    char *path_resourcePool;
    char *path_hostSystem;
3936
    esxVI_ObjectContent *virtualMachine = NULL;
3937 3938
    esxVI_ManagedObjectReference resourcePool;
    esxVI_ManagedObjectReference hostSystem;
3939 3940 3941
    esxVI_Event *eventList = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3942
    char *taskInfoErrorMessage = NULL;
3943

E
Eric Blake 已提交
3944 3945
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

M
Matthias Bolte 已提交
3946
    if (priv->vCenter == NULL) {
3947 3948
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Migration not possible without a vCenter"));
M
Matthias Bolte 已提交
3949
        return -1;
3950 3951 3952
    }

    if (dname != NULL) {
3953 3954
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Renaming domains on migration not supported"));
M
Matthias Bolte 已提交
3955
        return -1;
3956 3957
    }

3958
    if (esxVI_EnsureSession(priv->vCenter) < 0) {
M
Matthias Bolte 已提交
3959
        return -1;
3960 3961
    }

3962 3963
    /* Parse migration URI */
    parsedUri = xmlParseURI(uri);
3964

3965
    if (parsedUri == NULL) {
3966
        virReportOOMError();
M
Matthias Bolte 已提交
3967
        return -1;
3968 3969
    }

3970 3971 3972
    if (parsedUri->scheme == NULL || STRCASENEQ(parsedUri->scheme, "vpxmigr")) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Only vpxmigr:// migration URIs are supported"));
M
Matthias Bolte 已提交
3973
        goto cleanup;
3974 3975
    }

3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988
    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 已提交
3989
        goto cleanup;
3990 3991
    }

3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004
    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,
4005
           priv->parsedUri->autoAnswer) < 0) {
M
Matthias Bolte 已提交
4006
        goto cleanup;
4007 4008 4009
    }

    /* Validate the purposed migration */
4010
    if (esxVI_ValidateMigration(priv->vCenter, virtualMachine->obj,
4011 4012
                                esxVI_VirtualMachinePowerState_Undefined, NULL,
                                &resourcePool, &hostSystem, &eventList) < 0) {
M
Matthias Bolte 已提交
4013
        goto cleanup;
4014 4015 4016 4017 4018 4019 4020 4021
    }

    if (eventList != NULL) {
        /*
         * FIXME: Need to report the complete list of events. Limit reporting
         *        to the first event for now.
         */
        if (eventList->fullFormattedMessage != NULL) {
4022
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
4023 4024
                      _("Could not migrate domain, validation reported a "
                        "problem: %s"), eventList->fullFormattedMessage);
4025
        } else {
4026 4027 4028
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                      _("Could not migrate domain, validation reported a "
                        "problem"));
4029 4030
        }

M
Matthias Bolte 已提交
4031
        goto cleanup;
4032 4033 4034
    }

    /* Perform the purposed migration */
4035 4036
    if (esxVI_MigrateVM_Task(priv->vCenter, virtualMachine->obj,
                             &resourcePool, &hostSystem,
4037 4038 4039
                             esxVI_VirtualMachineMovePriority_DefaultPriority,
                             esxVI_VirtualMachinePowerState_Undefined,
                             &task) < 0 ||
4040
        esxVI_WaitForTaskCompletion(priv->vCenter, task, domain->uuid,
4041
                                    esxVI_Occurrence_RequiredItem,
4042
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4043
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4044
        goto cleanup;
4045 4046 4047
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4048
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
4049
                  _("Could not migrate domain, migration task finished with "
4050 4051
                    "an error: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
4052
        goto cleanup;
4053 4054
    }

M
Matthias Bolte 已提交
4055 4056
    result = 0;

4057
  cleanup:
4058
    xmlFreeURI(parsedUri);
4059 4060 4061
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Event_Free(&eventList);
    esxVI_ManagedObjectReference_Free(&task);
4062
    VIR_FREE(taskInfoErrorMessage);
4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073

    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 已提交
4074
                       unsigned long flags)
4075
{
E
Eric Blake 已提交
4076 4077
    virCheckFlags(ESX_MIGRATION_FLAGS, NULL);

4078 4079 4080 4081 4082
    return esxDomainLookupByName(dconn, dname);
}



M
Matthias Bolte 已提交
4083 4084 4085 4086
static unsigned long long
esxNodeGetFreeMemory(virConnectPtr conn)
{
    unsigned long long result = 0;
M
Matthias Bolte 已提交
4087
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
4088 4089 4090 4091 4092
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *resourcePool = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ResourcePoolResourceUsage *resourcePoolResourceUsage = NULL;

4093
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4094
        return 0;
M
Matthias Bolte 已提交
4095 4096 4097
    }

    /* Get memory usage of resource pool */
4098
    if (esxVI_String_AppendValueToList(&propertyNameList,
M
Matthias Bolte 已提交
4099
                                       "runtime.memory") < 0 ||
4100 4101
        esxVI_LookupObjectContentByType(priv->primary,
                                        priv->primary->computeResource->resourcePool,
4102
                                        "ResourcePool", propertyNameList,
4103 4104
                                        &resourcePool,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4105
        goto cleanup;
M
Matthias Bolte 已提交
4106 4107 4108 4109 4110 4111
    }

    for (dynamicProperty = resourcePool->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.memory")) {
            if (esxVI_ResourcePoolResourceUsage_CastFromAnyType
4112
                  (dynamicProperty->val, &resourcePoolResourceUsage) < 0) {
M
Matthias Bolte 已提交
4113
                goto cleanup;
M
Matthias Bolte 已提交
4114 4115 4116 4117 4118 4119 4120 4121 4122
            }

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

    if (resourcePoolResourceUsage == NULL) {
4123 4124
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve memory usage of resource pool"));
M
Matthias Bolte 已提交
4125
        goto cleanup;
M
Matthias Bolte 已提交
4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139
    }

    result = resourcePoolResourceUsage->unreservedForVm->value;

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

    return result;
}



4140 4141 4142
static int
esxIsEncrypted(virConnectPtr conn)
{
M
Matthias Bolte 已提交
4143
    esxPrivate *priv = conn->privateData;
4144

4145
    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156
        return 1;
    } else {
        return 0;
    }
}



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

4159
    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170
        return 1;
    } else {
        return 0;
    }
}



static int
esxDomainIsActive(virDomainPtr domain)
{
M
Matthias Bolte 已提交
4171
    int result = -1;
M
Matthias Bolte 已提交
4172
    esxPrivate *priv = domain->conn->privateData;
4173 4174 4175 4176
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

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

4181
    if (esxVI_String_AppendValueToList(&propertyNameList,
4182
                                       "runtime.powerState") < 0 ||
4183
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
4184
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
4185
                                         esxVI_Occurrence_RequiredItem) < 0 ||
4186
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
4187
        goto cleanup;
4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211
    }

    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 已提交
4212 4213


4214 4215 4216 4217 4218
static int
esxDomainIsUpdated(virDomainPtr domain ATTRIBUTE_UNUSED)
{
    return 0;
}
4219

M
Matthias Bolte 已提交
4220 4221


4222 4223
static virDomainSnapshotPtr
esxDomainSnapshotCreateXML(virDomainPtr domain, const char *xmlDesc,
4224
                           unsigned int flags)
4225 4226 4227 4228 4229 4230 4231 4232
{
    esxPrivate *priv = domain->conn->privateData;
    virDomainSnapshotDefPtr def = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
4233
    char *taskInfoErrorMessage = NULL;
4234 4235
    virDomainSnapshotPtr snapshot = NULL;

4236 4237
    /* ESX has no snapshot metadata, so this flag is trivial.  */
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA, NULL);
4238

4239
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4240
        return NULL;
4241 4242
    }

4243
    def = virDomainSnapshotDefParseString(xmlDesc, NULL, 0, 0);
4244 4245

    if (def == NULL) {
M
Matthias Bolte 已提交
4246
        return NULL;
4247 4248
    }

4249 4250 4251 4252 4253 4254
    if (def->ndisks) {
        ESX_ERROR(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                  _("disk snapshots not supported yet"));
        return NULL;
    }

4255
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
4256
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4257
           priv->parsedUri->autoAnswer) < 0 ||
4258
        esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4259 4260
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, def->name,
4261
                                    &snapshotTree, NULL,
4262
                                    esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4263
        goto cleanup;
4264 4265 4266 4267 4268
    }

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

4272
    if (esxVI_CreateSnapshot_Task(priv->primary, virtualMachine->obj,
4273 4274 4275
                                  def->name, def->description,
                                  esxVI_Boolean_True,
                                  esxVI_Boolean_False, &task) < 0 ||
4276
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
4277
                                    esxVI_Occurrence_RequiredItem,
4278
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4279
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4280
        goto cleanup;
4281 4282 4283
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4284 4285
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not create snapshot: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
4286
        goto cleanup;
4287 4288 4289 4290 4291 4292 4293 4294 4295
    }

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

  cleanup:
    virDomainSnapshotDefFree(def);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4296
    VIR_FREE(taskInfoErrorMessage);
4297 4298 4299 4300 4301 4302 4303

    return snapshot;
}



static char *
4304 4305
esxDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                            unsigned int flags)
4306 4307 4308 4309 4310 4311 4312 4313 4314
{
    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;

4315 4316
    virCheckFlags(0, NULL);

M
Matthias Bolte 已提交
4317
    memset(&def, 0, sizeof (def));
4318

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

4323
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4324 4325 4326 4327
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4328
        goto cleanup;
4329 4330 4331 4332 4333 4334 4335 4336
    }

    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 已提交
4337
        goto cleanup;
4338 4339 4340 4341 4342 4343 4344
    }

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

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

4345
    xml = virDomainSnapshotDefFormat(uuid_string, &def, flags, 0);
4346 4347 4348 4349 4350 4351 4352 4353 4354 4355

  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return xml;
}



static int
4356
esxDomainSnapshotNum(virDomainPtr domain, unsigned int flags)
4357
{
M
Matthias Bolte 已提交
4358
    int count;
4359 4360
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
4361
    bool recurse;
4362
    bool leaves;
4363

4364
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
4365 4366
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4367 4368

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) == 0;
4369
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4370

4371
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4372
        return -1;
4373 4374
    }

4375 4376 4377 4378
    /* ESX snapshots do not require libvirt to maintain any metadata.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA)
        return 0;

4379
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4380
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4381
        return -1;
4382 4383
    }

4384 4385
    count = esxVI_GetNumberOfSnapshotTrees(rootSnapshotTreeList, recurse,
                                           leaves);
4386 4387 4388

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

M
Matthias Bolte 已提交
4389
    return count;
4390 4391 4392 4393 4394 4395
}



static int
esxDomainSnapshotListNames(virDomainPtr domain, char **names, int nameslen,
4396
                           unsigned int flags)
4397
{
M
Matthias Bolte 已提交
4398
    int result;
4399 4400
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
4401
    bool recurse;
4402
    bool leaves;
4403 4404

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
4405 4406
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4407

4408
    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) == 0;
4409
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4410

4411 4412 4413 4414 4415
    if (names == NULL || nameslen < 0) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
    }

4416
    if (nameslen == 0 || (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA)) {
4417 4418 4419
        return 0;
    }

4420
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4421
        return -1;
4422 4423
    }

4424
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4425
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4426
        return -1;
4427 4428
    }

4429
    result = esxVI_GetSnapshotTreeNames(rootSnapshotTreeList, names, nameslen,
4430
                                        recurse, leaves);
4431 4432 4433 4434 4435 4436 4437 4438

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



4439 4440 4441 4442 4443 4444 4445 4446
static int
esxDomainSnapshotNumChildren(virDomainSnapshotPtr snapshot, unsigned int flags)
{
    int count = -1;
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    bool recurse;
4447
    bool leaves;
4448 4449

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
4450 4451
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4452 4453

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) != 0;
4454
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474

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

    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
                                         &rootSnapshotTreeList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotTreeList, snapshot->name,
                                    &snapshotTree, NULL,
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    /* ESX snapshots do not require libvirt to maintain any metadata.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA) {
        count = 0;
        goto cleanup;
    }

    count = esxVI_GetNumberOfSnapshotTrees(snapshotTree->childSnapshotList,
4475
                                           recurse, leaves);
4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494

cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return count;
}



static int
esxDomainSnapshotListChildrenNames(virDomainSnapshotPtr snapshot,
                                   char **names, int nameslen,
                                   unsigned int flags)
{
    int result = -1;
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    bool recurse;
4495
    bool leaves;
4496 4497

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
4498 4499
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4500 4501

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) != 0;
4502
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531

    if (names == NULL || nameslen < 0) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
    }

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

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

    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
                                         &rootSnapshotTreeList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotTreeList, snapshot->name,
                                    &snapshotTree, NULL,
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    /* ESX snapshots do not require libvirt to maintain any metadata.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA) {
        result = 0;
        goto cleanup;
    }

    result = esxVI_GetSnapshotTreeNames(snapshotTree->childSnapshotList,
4532
                                        names, nameslen, recurse, leaves);
4533 4534 4535 4536 4537 4538 4539 4540 4541

cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



4542 4543
static virDomainSnapshotPtr
esxDomainSnapshotLookupByName(virDomainPtr domain, const char *name,
4544
                              unsigned int flags)
4545 4546 4547 4548 4549 4550
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    virDomainSnapshotPtr snapshot = NULL;

4551 4552
    virCheckFlags(0, NULL);

4553
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4554
        return NULL;
4555 4556
    }

4557
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4558 4559
                                         &rootSnapshotTreeList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotTreeList, name, &snapshotTree,
4560
                                    NULL,
4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580
                                    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;

4581
    virCheckFlags(0, -1);
4582

4583
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4584
        return -1;
4585 4586
    }

4587
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4588 4589
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4590
        return -1;
4591 4592 4593
    }

    if (currentSnapshotTree != NULL) {
M
Matthias Bolte 已提交
4594 4595
        esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);
        return 1;
4596 4597
    }

M
Matthias Bolte 已提交
4598
    return 0;
4599 4600 4601 4602
}



E
Eric Blake 已提交
4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642
static virDomainSnapshotPtr
esxDomainSnapshotGetParent(virDomainSnapshotPtr snapshot, unsigned int flags)
{
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    virDomainSnapshotPtr parent = NULL;

    virCheckFlags(0, NULL);

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

    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    if (!snapshotTreeParent) {
        ESX_ERROR(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                  _("snapshot '%s' does not have a parent"),
                  snapshotTree->name);
        goto cleanup;
    }

    parent = virGetDomainSnapshot(snapshot->domain, snapshotTreeParent->name);

cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return parent;
}



4643 4644 4645 4646 4647
static virDomainSnapshotPtr
esxDomainSnapshotCurrent(virDomainPtr domain, unsigned int flags)
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *currentSnapshotTree = NULL;
M
Matthias Bolte 已提交
4648
    virDomainSnapshotPtr snapshot = NULL;
4649

4650
    virCheckFlags(0, NULL);
4651

4652
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4653
        return NULL;
4654 4655
    }

4656
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4657 4658
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4659
        return NULL;
4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673
    }

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

    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return snapshot;
}



static int
esxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4674
    int result = -1;
4675 4676 4677 4678 4679
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
4680
    char *taskInfoErrorMessage = NULL;
4681

4682
    virCheckFlags(0, -1);
4683

4684
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4685
        return -1;
4686 4687
    }

4688
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4689 4690
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
4691
                                    &snapshotTree, NULL,
4692
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4693
        goto cleanup;
4694 4695
    }

4696
    if (esxVI_RevertToSnapshot_Task(priv->primary, snapshotTree->snapshot, NULL,
4697
                                    &task) < 0 ||
4698
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4699
                                    esxVI_Occurrence_RequiredItem,
4700
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4701
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4702
        goto cleanup;
4703 4704 4705 4706
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
4707 4708
                  _("Could not revert to snapshot '%s': %s"), snapshot->name,
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
4709
        goto cleanup;
4710 4711
    }

M
Matthias Bolte 已提交
4712 4713
    result = 0;

4714 4715 4716
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4717
    VIR_FREE(taskInfoErrorMessage);
4718 4719 4720 4721 4722 4723 4724 4725 4726

    return result;
}



static int
esxDomainSnapshotDelete(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4727
    int result = -1;
4728 4729 4730 4731 4732 4733
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_Boolean removeChildren = esxVI_Boolean_False;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
4734
    char *taskInfoErrorMessage = NULL;
4735

4736 4737
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
                  VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY, -1);
4738

4739
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4740
        return -1;
4741 4742 4743 4744 4745 4746
    }

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

4747
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4748 4749
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
4750
                                    &snapshotTree, NULL,
4751
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4752
        goto cleanup;
4753 4754
    }

4755 4756 4757 4758 4759 4760 4761
    /* ESX snapshots do not require any libvirt metadata, making this
     * flag trivial once we know we have a valid snapshot.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY) {
        result = 0;
        goto cleanup;
    }

4762
    if (esxVI_RemoveSnapshot_Task(priv->primary, snapshotTree->snapshot,
4763
                                  removeChildren, &task) < 0 ||
4764
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4765
                                    esxVI_Occurrence_RequiredItem,
4766
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4767
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4768
        goto cleanup;
4769 4770 4771 4772
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
4773 4774
                  _("Could not delete snapshot '%s': %s"), snapshot->name,
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
4775
        goto cleanup;
4776 4777
    }

M
Matthias Bolte 已提交
4778 4779
    result = 0;

4780 4781 4782
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4783
    VIR_FREE(taskInfoErrorMessage);
4784 4785 4786 4787 4788 4789

    return result;
}



4790
static int
4791
esxDomainSetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
4792 4793 4794 4795 4796 4797 4798 4799
                             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;
4800
    char *taskInfoErrorMessage = NULL;
4801 4802 4803 4804 4805 4806 4807 4808 4809 4810
    int i;

    virCheckFlags(0, -1);

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

    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4811
           priv->parsedUri->autoAnswer) < 0 ||
4812 4813 4814 4815 4816 4817 4818
        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) &&
4819
            params[i].type == VIR_TYPED_PARAM_ULLONG) {
4820 4821 4822 4823 4824
            if (esxVI_Long_Alloc(&spec->memoryAllocation->reservation) < 0) {
                goto cleanup;
            }

            spec->memoryAllocation->reservation->value =
4825
              VIR_DIV_UP(params[i].value.ul, 1024); /* Scale from kilobytes to megabytes */
4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836
        } 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,
4837
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4838
                                    &taskInfoErrorMessage) < 0) {
4839 4840 4841 4842
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4843 4844 4845
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not change memory parameters: %s"),
                  taskInfoErrorMessage);
4846 4847 4848 4849 4850 4851 4852 4853 4854
        goto cleanup;
    }

    result = 0;

  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
4855
    VIR_FREE(taskInfoErrorMessage);
4856 4857 4858 4859 4860 4861 4862

    return result;
}



static int
4863
esxDomainGetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906
                             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;
    }

4907
    params[0].type = VIR_TYPED_PARAM_ULLONG;
4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922
    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;
}



4923
static virDriver esxDriver = {
4924 4925
    .no = VIR_DRV_ESX,
    .name = "ESX",
4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943
    .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 */
4944
    .domainDestroyFlags = esxDomainDestroyFlags, /* 0.9.4 */
4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965
    .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 */
4966
    .domainUndefineFlags = esxDomainUndefineFlags, /* 0.9.4 */
4967 4968 4969 4970
    .domainGetAutostart = esxDomainGetAutostart, /* 0.9.0 */
    .domainSetAutostart = esxDomainSetAutostart, /* 0.9.0 */
    .domainGetSchedulerType = esxDomainGetSchedulerType, /* 0.7.0 */
    .domainGetSchedulerParameters = esxDomainGetSchedulerParameters, /* 0.7.0 */
4971
    .domainGetSchedulerParametersFlags = esxDomainGetSchedulerParametersFlags, /* 0.9.2 */
4972
    .domainSetSchedulerParameters = esxDomainSetSchedulerParameters, /* 0.7.0 */
4973
    .domainSetSchedulerParametersFlags = esxDomainSetSchedulerParametersFlags, /* 0.9.2 */
4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986
    .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 */
4987 4988
    .domainSnapshotNumChildren = esxDomainSnapshotNumChildren, /* 0.9.7 */
    .domainSnapshotListChildrenNames = esxDomainSnapshotListChildrenNames, /* 0.9.7 */
4989 4990
    .domainSnapshotLookupByName = esxDomainSnapshotLookupByName, /* 0.8.0 */
    .domainHasCurrentSnapshot = esxDomainHasCurrentSnapshot, /* 0.8.0 */
E
Eric Blake 已提交
4991
    .domainSnapshotGetParent = esxDomainSnapshotGetParent, /* 0.9.7 */
4992 4993 4994
    .domainSnapshotCurrent = esxDomainSnapshotCurrent, /* 0.8.0 */
    .domainRevertToSnapshot = esxDomainRevertToSnapshot, /* 0.8.0 */
    .domainSnapshotDelete = esxDomainSnapshotDelete, /* 0.8.0 */
4995 4996 4997 4998 4999 5000 5001
};



int
esxRegister(void)
{
5002 5003 5004 5005 5006
    if (virRegisterDriver(&esxDriver) < 0 ||
        esxInterfaceRegister() < 0 ||
        esxNetworkRegister() < 0 ||
        esxStorageRegister() < 0 ||
        esxDeviceRegister() < 0 ||
M
Matthias Bolte 已提交
5007 5008
        esxSecretRegister() < 0 ||
        esxNWFilterRegister() < 0) {
5009 5010
        return -1;
    }
5011 5012 5013

    return 0;
}