esx_driver.c 159.0 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 "virtypedparam.h"
36
#include "esx_driver.h"
37 38 39 40 41
#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 已提交
42
#include "esx_nwfilter_driver.h"
43
#include "esx_private.h"
44 45 46
#include "esx_vi.h"
#include "esx_vi_methods.h"
#include "esx_util.h"
M
Martin Kletzander 已提交
47
#include "viruri.h"
48 49 50 51 52

#define VIR_FROM_THIS VIR_FROM_ESX

static int esxDomainGetMaxVcpus(virDomainPtr domain);

53 54 55 56
typedef struct _esxVMX_Data esxVMX_Data;

struct _esxVMX_Data {
    esxVI_Context *ctx;
57
    char *datastorePathWithoutFileName;
58 59 60 61
};



62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
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);
}



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

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

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

171
            tmp = (char *)STRSKIP(fileName, hostMount->mountInfo->path);
172

173 174 175
            if (tmp == NULL) {
                continue;
            }
176

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

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

186
            tmp = strippedFileName;
187

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

194 195
                ++tmp;
            }
196

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

203 204
            break;
        }
205

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

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

222
            esxVI_ObjectContent_Free(&datastoreList);
223

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

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

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

244 245 246 247 248 249 250 251 252
        /* 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) {
253
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
254
                      _("Could not handle file name '%s'"), fileName);
255
            goto cleanup;
256
        }
257
    }
258

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

266
    return result;
267 268 269 270
}



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

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

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

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

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

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

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

328 329
        if (separator != '/') {
            tmp = directoryAndFileName;
330

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

336 337
                ++tmp;
            }
338
        }
339

340 341
        virBufferAddChar(&buffer, separator);
        virBufferAdd(&buffer, directoryAndFileName, -1);
342

343 344 345 346 347 348 349 350 351 352 353 354 355 356
        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);
357 358 359 360 361 362 363 364 365
        goto cleanup;
    }

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

    success = true;

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

    VIR_FREE(datastoreName);
371
    VIR_FREE(directoryAndFileName);
372 373
    esxVI_ObjectContent_Free(&datastore);
    esxVI_DatastoreHostMount_Free(&hostMount);
374

375
    return result;
376 377 378 379 380 381 382 383 384 385
}



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

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

407
    vmDiskFileInfo = esxVI_VmDiskFileInfo_DynamicCast(fileInfo);
408 409 410 411 412 413 414 415 416

    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")) {
417
        *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_BUSLOGIC;
418 419
    } else if (STRCASEEQ(vmDiskFileInfo->controllerType,
                         "VirtualLsiLogicController")) {
420
        *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC;
421 422
    } else if (STRCASEEQ(vmDiskFileInfo->controllerType,
                         "VirtualLsiLogicSASController")) {
423
        *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSISAS1068;
424 425
    } else if (STRCASEEQ(vmDiskFileInfo->controllerType,
                         "ParaVirtualSCSIController")) {
426
        *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VMPVSCSI;
427 428 429 430 431 432 433 434 435 436
    } else {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Found unexpected controller model '%s' for disk '%s'"),
                  vmDiskFileInfo->controllerType, def->src);
        goto cleanup;
    }

    result = 0;

  cleanup:
437
    esxVI_FileInfo_Free(&fileInfo);
438 439 440 441

    return result;
}

442 443


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

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

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

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

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

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

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

492
                    edxLongModeBit = parsedHostCpuIdInfo.edx[29];
493 494 495 496 497 498

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

                    break;
                }
            }

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

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

    return priv->supportsLongMode;
}



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

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

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


593 594 595 596 597
static int esxDefaultConsoleType(const char *ostype ATTRIBUTE_UNUSED)
{
    return VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL;
}

598

599
static virCapsPtr
600
esxCapsInit(esxPrivate *priv)
601
{
602
    esxVI_Boolean supportsLongMode = esxSupportsLongMode(priv);
603 604 605
    virCapsPtr caps = NULL;
    virCapsGuestPtr guest = NULL;

606 607 608 609 610 611 612 613 614
    if (supportsLongMode == esxVI_Boolean_Undefined) {
        return NULL;
    }

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

    if (caps == NULL) {
617
        virReportOOMError();
618 619 620
        return NULL;
    }

621
    virCapabilitiesSetMacPrefix(caps, (unsigned char[]){ 0x00, 0x0c, 0x29 });
622
    virCapabilitiesAddHostMigrateTransport(caps, "vpxmigr");
623

624
    caps->hasWideScsiBus = true;
625
    caps->defaultConsoleTargetType = esxDefaultConsoleType;
626

627 628 629 630
    if (esxLookupHostSystemBiosUuid(priv, caps->host.host_uuid) < 0) {
        goto failure;
    }

631 632 633
    /* i686 */
    guest = virCapabilitiesAddGuest(caps, "hvm", "i686", 32, NULL, NULL, 0,
                                    NULL);
634 635 636 637 638 639 640 641 642 643

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

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

644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
    /* 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;
        }
    }

659 660 661 662 663 664 665 666 667 668
    return caps;

  failure:
    virCapabilitiesFree(caps);

    return NULL;
}



669 670 671 672 673 674 675 676 677 678
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 已提交
679
    char *unescapedPassword = NULL;
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
    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 已提交
711
    unescapedPassword = virRequestPassword(auth, username, hostname);
712

M
Matthias Bolte 已提交
713
    if (unescapedPassword == NULL) {
714 715 716 717
        ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
        goto cleanup;
    }

M
Matthias Bolte 已提交
718 719 720 721 722 723
    password = esxUtil_EscapeForXml(unescapedPassword);

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

724 725
    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->parsedUri->transport,
                    hostname, port) < 0) {
726 727 728 729 730 731
        virReportOOMError();
        goto cleanup;
    }

    if (esxVI_Context_Alloc(&priv->host) < 0 ||
        esxVI_Context_Connect(priv->host, url, ipAddress, username, password,
732
                              priv->parsedUri) < 0 ||
733
        esxVI_Context_LookupManagedObjects(priv->host) < 0) {
734 735 736 737 738
        goto cleanup;
    }

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

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

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

    result = 0;

  cleanup:
    VIR_FREE(username);
M
Matthias Bolte 已提交
790 791
    VIR_FREE(unescapedPassword);
    VIR_FREE(password);
792 793 794 795 796 797 798 799 800 801 802 803 804
    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,
805
                    const char *hostSystemIpAddress)
806 807 808 809
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
M
Matthias Bolte 已提交
810
    char *unescapedPassword = NULL;
811 812 813
    char *password = NULL;
    char *url = NULL;

814
    if (hostSystemIpAddress == NULL &&
815
        (priv->parsedUri->path == NULL || STREQ(priv->parsedUri->path, "/"))) {
816 817 818 819 820
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Path has to specify the datacenter and compute resource"));
        return -1;
    }

821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
    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 已提交
841
    unescapedPassword = virRequestPassword(auth, username, hostname);
842

M
Matthias Bolte 已提交
843
    if (unescapedPassword == NULL) {
844 845 846 847
        ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
        goto cleanup;
    }

M
Matthias Bolte 已提交
848 849 850 851 852 853
    password = esxUtil_EscapeForXml(unescapedPassword);

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

854 855
    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->parsedUri->transport,
                    hostname, port) < 0) {
856 857 858 859 860 861
        virReportOOMError();
        goto cleanup;
    }

    if (esxVI_Context_Alloc(&priv->vCenter) < 0 ||
        esxVI_Context_Connect(priv->vCenter, url, ipAddress, username,
862
                              password, priv->parsedUri) < 0) {
863 864 865 866
        goto cleanup;
    }

    if (priv->vCenter->productVersion != esxVI_ProductVersion_VPX25 &&
M
Matthias Bolte 已提交
867 868
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX40 &&
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX41 &&
P
Patrice LACHANCE 已提交
869 870 871
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX4x &&
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX50 &&
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX5x) {
872
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
P
Patrice LACHANCE 已提交
873 874
                  _("%s is neither a vCenter 2.5, 4.x nor 5.x server"),
                  hostname);
875 876 877
        goto cleanup;
    }

878
    if (hostSystemIpAddress != NULL) {
879 880
        if (esxVI_Context_LookupManagedObjectsByHostSystemIp
              (priv->vCenter, hostSystemIpAddress) < 0) {
881 882 883
            goto cleanup;
        }
    } else {
884 885
        if (esxVI_Context_LookupManagedObjectsByPath(priv->vCenter,
                                                     priv->parsedUri->path) < 0) {
886 887 888 889
            goto cleanup;
        }
    }

890 891 892 893
    result = 0;

  cleanup:
    VIR_FREE(username);
M
Matthias Bolte 已提交
894 895
    VIR_FREE(unescapedPassword);
    VIR_FREE(password);
896 897 898 899 900 901 902
    VIR_FREE(url);

    return result;
}



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

E
Eric Blake 已提交
958 959
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

960 961
    /* Decline if the URI is NULL or the scheme is NULL */
    if (conn->uri == NULL || conn->uri->scheme == NULL) {
962 963 964
        return VIR_DRV_OPEN_DECLINED;
    }

965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
    /* 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;
    }

988 989 990 991 992 993
    if (STRCASENEQ(conn->uri->scheme, "vpx") &&
        conn->uri->path != NULL && STRNEQ(conn->uri->path, "/")) {
        VIR_WARN("Ignoring unexpected path '%s' for non-vpx scheme '%s'",
                 conn->uri->path, conn->uri->scheme);
    }

994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
    /* 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;
1006 1007 1008 1009
    }

    /* Allocate per-connection private data */
    if (VIR_ALLOC(priv) < 0) {
1010
        virReportOOMError();
M
Matthias Bolte 已提交
1011
        goto cleanup;
1012 1013
    }

1014
    if (esxUtil_ParseUri(&priv->parsedUri, conn->uri) < 0) {
1015 1016 1017
        goto cleanup;
    }

M
Matthias Bolte 已提交
1018 1019
    priv->maxVcpus = -1;
    priv->supportsVMotion = esxVI_Boolean_Undefined;
1020
    priv->supportsLongMode = esxVI_Boolean_Undefined;
1021 1022
    priv->usedCpuTimeCounterId = -1;

M
Matthias Bolte 已提交
1023 1024 1025 1026 1027 1028 1029
    /*
     * 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) {
1030 1031
        if (STRCASEEQ(conn->uri->scheme, "vpx") ||
            STRCASEEQ(conn->uri->scheme, "esx")) {
1032
            if (STRCASEEQ(priv->parsedUri->transport, "https")) {
M
Matthias Bolte 已提交
1033 1034 1035 1036 1037
                conn->uri->port = 443;
            } else {
                conn->uri->port = 80;
            }
        } else { /* GSX */
1038
            if (STRCASEEQ(priv->parsedUri->transport, "https")) {
M
Matthias Bolte 已提交
1039 1040 1041 1042
                conn->uri->port = 8333;
            } else {
                conn->uri->port = 8222;
            }
1043
        }
M
Matthias Bolte 已提交
1044
    }
1045

1046 1047 1048 1049
    if (STRCASEEQ(conn->uri->scheme, "esx") ||
        STRCASEEQ(conn->uri->scheme, "gsx")) {
        /* Connect to host */
        if (esxConnectToHost(priv, auth, conn->uri->server, conn->uri->port,
1050
                             conn->uri->user,
1051 1052 1053 1054
                             STRCASEEQ(conn->uri->scheme, "esx")
                               ? esxVI_ProductVersion_ESX
                               : esxVI_ProductVersion_GSX,
                             &potentialVCenterIpAddress) < 0) {
M
Matthias Bolte 已提交
1055
            goto cleanup;
1056
        }
1057

1058
        /* Connect to vCenter */
1059 1060
        if (priv->parsedUri->vCenter != NULL) {
            if (STREQ(priv->parsedUri->vCenter, "*")) {
1061 1062 1063
                if (potentialVCenterIpAddress == NULL) {
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                              _("This host is not managed by a vCenter"));
M
Matthias Bolte 已提交
1064
                    goto cleanup;
1065 1066
                }

1067 1068 1069 1070 1071 1072 1073 1074
                if (virStrcpyStatic(vCenterIpAddress,
                                    potentialVCenterIpAddress) == NULL) {
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                              _("vCenter IP address %s too big for destination"),
                              potentialVCenterIpAddress);
                    goto cleanup;
                }
            } else {
1075
                if (esxUtil_ResolveHostname(priv->parsedUri->vCenter,
1076 1077 1078
                                            vCenterIpAddress, NI_MAXHOST) < 0) {
                    goto cleanup;
                }
1079

1080 1081
                if (potentialVCenterIpAddress != NULL &&
                    STRNEQ(vCenterIpAddress, potentialVCenterIpAddress)) {
1082
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1083 1084 1085
                              _("This host is managed by a vCenter with IP "
                                "address %s, but a mismachting vCenter '%s' "
                                "(%s) has been specified"),
1086
                              potentialVCenterIpAddress, priv->parsedUri->vCenter,
1087
                              vCenterIpAddress);
M
Matthias Bolte 已提交
1088
                    goto cleanup;
1089 1090
                }
            }
1091

1092
            if (esxConnectToVCenter(priv, auth, vCenterIpAddress,
1093
                                    conn->uri->port, NULL,
1094
                                    priv->host->ipAddress) < 0) {
1095 1096
                goto cleanup;
            }
1097 1098
        }

1099 1100 1101 1102
        priv->primary = priv->host;
    } else { /* VPX */
        /* Connect to vCenter */
        if (esxConnectToVCenter(priv, auth, conn->uri->server, conn->uri->port,
1103
                                conn->uri->user, NULL) < 0) {
M
Matthias Bolte 已提交
1104
            goto cleanup;
1105 1106
        }

1107
        priv->primary = priv->vCenter;
1108 1109
    }

M
Matthias Bolte 已提交
1110
    /* Setup capabilities */
1111
    priv->caps = esxCapsInit(priv);
1112

M
Matthias Bolte 已提交
1113
    if (priv->caps == NULL) {
M
Matthias Bolte 已提交
1114
        goto cleanup;
1115 1116
    }

1117 1118
    conn->privateData = priv;

M
Matthias Bolte 已提交
1119
    result = VIR_DRV_OPEN_SUCCESS;
1120

M
Matthias Bolte 已提交
1121
  cleanup:
1122 1123
    if (result == VIR_DRV_OPEN_ERROR) {
        esxFreePrivate(&priv);
1124 1125
    }

1126
    VIR_FREE(potentialVCenterIpAddress);
1127

M
Matthias Bolte 已提交
1128
    return result;
1129 1130 1131 1132 1133 1134 1135
}



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

1139 1140 1141 1142 1143 1144
    if (priv->host != NULL) {
        if (esxVI_EnsureSession(priv->host) < 0 ||
            esxVI_Logout(priv->host) < 0) {
            result = -1;
        }
    }
1145

M
Matthias Bolte 已提交
1146
    if (priv->vCenter != NULL) {
E
Eric Blake 已提交
1147 1148 1149 1150
        if (esxVI_EnsureSession(priv->vCenter) < 0 ||
            esxVI_Logout(priv->vCenter) < 0) {
            result = -1;
        }
1151 1152
    }

1153
    esxFreePrivate(&priv);
1154 1155 1156

    conn->privateData = NULL;

E
Eric Blake 已提交
1157
    return result;
1158 1159 1160 1161 1162
}



static esxVI_Boolean
1163
esxSupportsVMotion(esxPrivate *priv)
1164 1165 1166 1167
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;

M
Matthias Bolte 已提交
1168 1169
    if (priv->supportsVMotion != esxVI_Boolean_Undefined) {
        return priv->supportsVMotion;
1170 1171
    }

1172
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1173
        return esxVI_Boolean_Undefined;
1174 1175
    }

1176
    if (esxVI_String_AppendValueToList(&propertyNameList,
1177
                                       "capability.vmotionSupported") < 0 ||
1178 1179
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1180
        goto cleanup;
1181 1182 1183
    }

    if (hostSystem == NULL) {
1184 1185
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
1186
        goto cleanup;
1187 1188
    }

1189 1190 1191 1192
    if (esxVI_GetBoolean(hostSystem, "capability.vmotionSupported",
                         &priv->supportsVMotion,
                         esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
1193 1194 1195
    }

  cleanup:
M
Matthias Bolte 已提交
1196 1197 1198 1199
    /*
     * 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.
     */
1200 1201 1202
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
1203
    return priv->supportsVMotion;
1204 1205 1206 1207 1208 1209 1210
}



static int
esxSupportsFeature(virConnectPtr conn, int feature)
{
M
Matthias Bolte 已提交
1211
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1212
    esxVI_Boolean supportsVMotion = esxVI_Boolean_Undefined;
1213 1214 1215

    switch (feature) {
      case VIR_DRV_FEATURE_MIGRATION_V1:
1216
        supportsVMotion = esxSupportsVMotion(priv);
1217

M
Matthias Bolte 已提交
1218
        if (supportsVMotion == esxVI_Boolean_Undefined) {
1219 1220 1221
            return -1;
        }

M
Matthias Bolte 已提交
1222 1223 1224
        /* Migration is only possible via a vCenter and if VMotion is enabled */
        return priv->vCenter != NULL &&
               supportsVMotion == esxVI_Boolean_True ? 1 : 0;
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243

      default:
        return 0;
    }
}



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



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

1246
    if (virParseVersionString(priv->primary->service->about->version,
1247
                              version, false) < 0) {
1248
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1249
                  _("Could not parse version number from '%s'"),
1250
                  priv->primary->service->about->version);
1251

1252
        return -1;
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
    }

    return 0;
}



static char *
esxGetHostname(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1263
    esxPrivate *priv = conn->privateData;
1264 1265 1266 1267 1268 1269 1270
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    const char *hostName = NULL;
    const char *domainName = NULL;
    char *complete = NULL;

1271
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1272
        return NULL;
1273 1274 1275
    }

    if (esxVI_String_AppendValueListToList
1276
          (&propertyNameList,
1277 1278
           "config.network.dnsConfig.hostName\0"
           "config.network.dnsConfig.domainName\0") < 0 ||
1279 1280
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1281
        goto cleanup;
1282 1283 1284
    }

    if (hostSystem == NULL) {
1285 1286
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
1287
        goto cleanup;
1288 1289 1290 1291 1292 1293
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name,
                  "config.network.dnsConfig.hostName")) {
1294
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1295
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1296
                goto cleanup;
1297 1298 1299 1300 1301
            }

            hostName = dynamicProperty->val->string;
        } else if (STREQ(dynamicProperty->name,
                         "config.network.dnsConfig.domainName")) {
1302
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1303
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1304
                goto cleanup;
1305 1306 1307 1308 1309 1310 1311 1312
            }

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

M
Matthias Bolte 已提交
1313
    if (hostName == NULL || strlen(hostName) < 1) {
1314 1315
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Missing or empty 'hostName' property"));
M
Matthias Bolte 已提交
1316
        goto cleanup;
1317 1318
    }

M
Matthias Bolte 已提交
1319
    if (domainName == NULL || strlen(domainName) < 1) {
1320
        complete = strdup(hostName);
1321

1322
        if (complete == NULL) {
1323
            virReportOOMError();
M
Matthias Bolte 已提交
1324
            goto cleanup;
1325 1326 1327
        }
    } else {
        if (virAsprintf(&complete, "%s.%s", hostName, domainName) < 0) {
1328
            virReportOOMError();
M
Matthias Bolte 已提交
1329
            goto cleanup;
1330
        }
1331 1332 1333
    }

  cleanup:
M
Matthias Bolte 已提交
1334 1335 1336 1337 1338
    /*
     * 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
     */
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return complete;
}



static int
esxNodeGetInfo(virConnectPtr conn, virNodeInfoPtr nodeinfo)
{
M
Matthias Bolte 已提交
1350
    int result = -1;
M
Matthias Bolte 已提交
1351
    esxPrivate *priv = conn->privateData;
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
    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 已提交
1363
    memset(nodeinfo, 0, sizeof (*nodeinfo));
1364

1365
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1366
        return -1;
1367 1368
    }

1369
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1370 1371 1372 1373 1374 1375 1376
                                           "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 ||
1377 1378
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1379
        goto cleanup;
1380 1381 1382
    }

    if (hostSystem == NULL) {
1383 1384
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
1385
        goto cleanup;
1386 1387 1388 1389 1390
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuInfo.hz")) {
1391
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1392
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1393
                goto cleanup;
1394 1395 1396 1397 1398
            }

            cpuInfo_hz = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuCores")) {
1399
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1400
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1401
                goto cleanup;
1402 1403 1404 1405 1406
            }

            cpuInfo_numCpuCores = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuPackages")) {
1407
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1408
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1409
                goto cleanup;
1410 1411 1412 1413 1414
            }

            cpuInfo_numCpuPackages = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuThreads")) {
1415
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1416
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1417
                goto cleanup;
1418 1419 1420 1421
            }

            cpuInfo_numCpuThreads = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name, "hardware.memorySize")) {
1422
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1423
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1424
                goto cleanup;
1425 1426 1427 1428 1429
            }

            memorySize = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.numaInfo.numNodes")) {
1430
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1431
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1432
                goto cleanup;
1433 1434 1435 1436 1437
            }

            numaInfo_numNodes = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "summary.hardware.cpuModel")) {
1438
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1439
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1440
                goto cleanup;
1441 1442 1443 1444 1445 1446
            }

            ptr = dynamicProperty->val->string;

            /* Strip the string to fit more relevant information in 32 chars */
            while (*ptr != '\0') {
M
Matthias Bolte 已提交
1447 1448
                if (STRPREFIX(ptr, "  ")) {
                    memmove(ptr, ptr + 1, strlen(ptr + 1) + 1);
1449
                    continue;
1450
                } else if (STRPREFIX(ptr, "(R)") || STRPREFIX(ptr, "(C)")) {
M
Matthias Bolte 已提交
1451
                    memmove(ptr, ptr + 3, strlen(ptr + 3) + 1);
1452
                    continue;
1453 1454 1455
                } else if (STRPREFIX(ptr, "(TM)")) {
                    memmove(ptr, ptr + 4, strlen(ptr + 4) + 1);
                    continue;
1456 1457 1458 1459 1460
                }

                ++ptr;
            }

C
Chris Lalancette 已提交
1461 1462 1463
            if (virStrncpy(nodeinfo->model, dynamicProperty->val->string,
                           sizeof(nodeinfo->model) - 1,
                           sizeof(nodeinfo->model)) == NULL) {
1464
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1465
                          _("CPU Model %s too long for destination"),
C
Chris Lalancette 已提交
1466
                          dynamicProperty->val->string);
M
Matthias Bolte 已提交
1467
                goto cleanup;
C
Chris Lalancette 已提交
1468
            }
1469 1470 1471 1472 1473 1474 1475
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    nodeinfo->memory = memorySize / 1024; /* Scale from bytes to kilobytes */
    nodeinfo->cpus = cpuInfo_numCpuCores;
1476
    nodeinfo->mhz = cpuInfo_hz / (1000 * 1000); /* Scale from hz to mhz */
1477 1478 1479 1480 1481 1482 1483 1484 1485
    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 已提交
1486 1487
    result = 0;

1488 1489 1490 1491 1492 1493 1494 1495 1496
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



1497 1498 1499
static char *
esxGetCapabilities(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1500
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1501
    char *xml = virCapabilitiesFormatXML(priv->caps);
1502 1503

    if (xml == NULL) {
1504
        virReportOOMError();
1505 1506 1507 1508 1509 1510 1511 1512
        return NULL;
    }

    return xml;
}



1513 1514 1515
static int
esxListDomains(virConnectPtr conn, int *ids, int maxids)
{
M
Matthias Bolte 已提交
1516
    bool success = false;
M
Matthias Bolte 已提交
1517
    esxPrivate *priv = conn->privateData;
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;

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

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

1532
    if (esxVI_String_AppendValueToList(&propertyNameList,
1533
                                       "runtime.powerState") < 0 ||
1534 1535
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1536
        goto cleanup;
1537 1538 1539 1540
    }

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

        if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

        if (esxUtil_ParseVirtualMachineIDString(virtualMachine->obj->value,
                                                &ids[count]) < 0 ||
            ids[count] <= 0) {
1553
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1554
                      _("Failed to parse positive integer from '%s'"),
1555
                      virtualMachine->obj->value);
M
Matthias Bolte 已提交
1556
            goto cleanup;
1557 1558 1559 1560 1561 1562 1563 1564 1565
        }

        count++;

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

M
Matthias Bolte 已提交
1566 1567
    success = true;

1568 1569 1570 1571
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
1572
    return success ? count : -1;
1573 1574 1575 1576 1577 1578 1579
}



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

1582
    if (esxVI_EnsureSession(priv->primary) < 0) {
1583 1584 1585
        return -1;
    }

1586
    return esxVI_LookupNumberOfDomainsByPowerState
1587
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, false);
1588 1589 1590 1591 1592 1593 1594
}



static virDomainPtr
esxDomainLookupByID(virConnectPtr conn, int id)
{
M
Matthias Bolte 已提交
1595
    esxPrivate *priv = conn->privateData;
1596 1597 1598 1599
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
M
Matthias Bolte 已提交
1600 1601 1602
    int id_candidate = -1;
    char *name_candidate = NULL;
    unsigned char uuid_candidate[VIR_UUID_BUFLEN];
1603 1604
    virDomainPtr domain = NULL;

1605
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1606
        return NULL;
1607 1608
    }

1609
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1610
                                           "configStatus\0"
1611 1612
                                           "name\0"
                                           "runtime.powerState\0"
1613
                                           "config.uuid\0") < 0 ||
1614 1615
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1616
        goto cleanup;
1617 1618 1619 1620
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
1621
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1622
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1623
            goto cleanup;
1624 1625 1626 1627 1628 1629 1630
        }

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

M
Matthias Bolte 已提交
1631
        VIR_FREE(name_candidate);
1632

1633
        if (esxVI_GetVirtualMachineIdentity(virtualMachine,
M
Matthias Bolte 已提交
1634 1635
                                            &id_candidate, &name_candidate,
                                            uuid_candidate) < 0) {
M
Matthias Bolte 已提交
1636
            goto cleanup;
1637 1638
        }

M
Matthias Bolte 已提交
1639
        if (id != id_candidate) {
1640 1641 1642
            continue;
        }

M
Matthias Bolte 已提交
1643
        domain = virGetDomain(conn, name_candidate, uuid_candidate);
1644 1645

        if (domain == NULL) {
M
Matthias Bolte 已提交
1646
            goto cleanup;
1647 1648 1649 1650 1651 1652 1653 1654
        }

        domain->id = id;

        break;
    }

    if (domain == NULL) {
1655
        ESX_ERROR(VIR_ERR_NO_DOMAIN, _("No domain with ID %d"), id);
1656 1657 1658 1659 1660
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
M
Matthias Bolte 已提交
1661
    VIR_FREE(name_candidate);
1662 1663 1664 1665 1666 1667 1668 1669 1670

    return domain;
}



static virDomainPtr
esxDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
M
Matthias Bolte 已提交
1671
    esxPrivate *priv = conn->privateData;
1672 1673 1674
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1675 1676
    int id = -1;
    char *name = NULL;
1677 1678
    virDomainPtr domain = NULL;

1679
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1680
        return NULL;
1681 1682
    }

1683
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1684
                                           "name\0"
1685
                                           "runtime.powerState\0") < 0 ||
1686
        esxVI_LookupVirtualMachineByUuid(priv->primary, uuid, propertyNameList,
1687
                                         &virtualMachine,
M
Matthias Bolte 已提交
1688
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1689 1690
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, &name, NULL) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1691
        goto cleanup;
1692 1693
    }

1694
    domain = virGetDomain(conn, name, uuid);
1695 1696

    if (domain == NULL) {
M
Matthias Bolte 已提交
1697
        goto cleanup;
1698
    }
1699

1700 1701 1702 1703 1704
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1705 1706 1707 1708
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1709 1710
    esxVI_ObjectContent_Free(&virtualMachine);
    VIR_FREE(name);
1711 1712 1713 1714 1715 1716 1717 1718 1719

    return domain;
}



static virDomainPtr
esxDomainLookupByName(virConnectPtr conn, const char *name)
{
M
Matthias Bolte 已提交
1720
    esxPrivate *priv = conn->privateData;
1721 1722 1723
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1724 1725
    int id = -1;
    unsigned char uuid[VIR_UUID_BUFLEN];
1726 1727
    virDomainPtr domain = NULL;

1728
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1729
        return NULL;
1730 1731
    }

1732
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1733
                                           "configStatus\0"
1734
                                           "runtime.powerState\0"
1735
                                           "config.uuid\0") < 0 ||
1736
        esxVI_LookupVirtualMachineByName(priv->primary, name, propertyNameList,
1737 1738
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
1739
        goto cleanup;
1740 1741
    }

1742
    if (virtualMachine == NULL) {
1743
        ESX_ERROR(VIR_ERR_NO_DOMAIN, _("No domain with name '%s'"), name);
M
Matthias Bolte 已提交
1744
        goto cleanup;
1745
    }
1746

M
Matthias Bolte 已提交
1747 1748 1749
    if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, uuid) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
1750
    }
1751

1752
    domain = virGetDomain(conn, name, uuid);
1753

1754
    if (domain == NULL) {
M
Matthias Bolte 已提交
1755
        goto cleanup;
1756 1757
    }

1758 1759 1760 1761 1762
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1763 1764 1765 1766
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1767
    esxVI_ObjectContent_Free(&virtualMachine);
1768 1769 1770 1771 1772 1773 1774 1775 1776

    return domain;
}



static int
esxDomainSuspend(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1777
    int result = -1;
M
Matthias Bolte 已提交
1778
    esxPrivate *priv = domain->conn->privateData;
1779 1780 1781 1782 1783
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1784
    char *taskInfoErrorMessage = NULL;
1785

1786
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1787
        return -1;
1788 1789
    }

1790
    if (esxVI_String_AppendValueToList(&propertyNameList,
1791
                                       "runtime.powerState") < 0 ||
1792
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1793
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1794
           priv->parsedUri->autoAnswer) < 0 ||
1795
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1796
        goto cleanup;
1797 1798 1799
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1800 1801
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1802
        goto cleanup;
1803 1804
    }

1805 1806
    if (esxVI_SuspendVM_Task(priv->primary, virtualMachine->obj, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1807
                                    esxVI_Occurrence_RequiredItem,
1808
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1809
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1810
        goto cleanup;
1811 1812 1813
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1814 1815
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not suspend domain: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
1816
        goto cleanup;
1817 1818
    }

M
Matthias Bolte 已提交
1819 1820
    result = 0;

1821 1822 1823 1824
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1825
    VIR_FREE(taskInfoErrorMessage);
1826 1827 1828 1829 1830 1831 1832 1833 1834

    return result;
}



static int
esxDomainResume(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1835
    int result = -1;
M
Matthias Bolte 已提交
1836
    esxPrivate *priv = domain->conn->privateData;
1837 1838 1839 1840 1841
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1842
    char *taskInfoErrorMessage = NULL;
1843

1844
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1845
        return -1;
1846 1847
    }

1848
    if (esxVI_String_AppendValueToList(&propertyNameList,
1849
                                       "runtime.powerState") < 0 ||
1850
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1851
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1852
           priv->parsedUri->autoAnswer) < 0 ||
1853
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1854
        goto cleanup;
1855 1856 1857
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended) {
1858
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not suspended"));
M
Matthias Bolte 已提交
1859
        goto cleanup;
1860 1861
    }

1862
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
1863
                             &task) < 0 ||
1864
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1865
                                    esxVI_Occurrence_RequiredItem,
1866
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1867
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1868
        goto cleanup;
1869 1870 1871
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1872 1873
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not resume domain: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
1874
        goto cleanup;
1875 1876
    }

M
Matthias Bolte 已提交
1877 1878
    result = 0;

1879 1880 1881 1882
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1883
    VIR_FREE(taskInfoErrorMessage);
1884 1885 1886 1887 1888 1889 1890

    return result;
}



static int
1891
esxDomainShutdownFlags(virDomainPtr domain, unsigned int flags)
1892
{
M
Matthias Bolte 已提交
1893
    int result = -1;
M
Matthias Bolte 已提交
1894
    esxPrivate *priv = domain->conn->privateData;
1895 1896 1897 1898
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1899 1900
    virCheckFlags(0, -1);

1901
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1902
        return -1;
1903 1904
    }

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

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1915 1916
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1917
        goto cleanup;
1918 1919
    }

1920
    if (esxVI_ShutdownGuest(priv->primary, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1921
        goto cleanup;
1922 1923
    }

M
Matthias Bolte 已提交
1924 1925
    result = 0;

1926 1927 1928 1929 1930 1931 1932 1933
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}


1934 1935 1936 1937 1938 1939
static int
esxDomainShutdown(virDomainPtr domain)
{
    return esxDomainShutdownFlags(domain, 0);
}

1940 1941

static int
E
Eric Blake 已提交
1942
esxDomainReboot(virDomainPtr domain, unsigned int flags)
1943
{
M
Matthias Bolte 已提交
1944
    int result = -1;
M
Matthias Bolte 已提交
1945
    esxPrivate *priv = domain->conn->privateData;
1946 1947 1948 1949
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

E
Eric Blake 已提交
1950 1951
    virCheckFlags(0, -1);

1952
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1953
        return -1;
1954 1955
    }

1956
    if (esxVI_String_AppendValueToList(&propertyNameList,
1957
                                       "runtime.powerState") < 0 ||
1958
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1959
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1960
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1961
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1962
        goto cleanup;
1963 1964 1965
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1966 1967
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1968
        goto cleanup;
1969 1970
    }

1971
    if (esxVI_RebootGuest(priv->primary, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1972
        goto cleanup;
1973 1974
    }

M
Matthias Bolte 已提交
1975 1976
    result = 0;

1977 1978 1979 1980 1981 1982 1983 1984 1985 1986
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
1987 1988
esxDomainDestroyFlags(virDomainPtr domain,
                      unsigned int flags)
1989
{
M
Matthias Bolte 已提交
1990
    int result = -1;
M
Matthias Bolte 已提交
1991
    esxPrivate *priv = domain->conn->privateData;
1992
    esxVI_Context *ctx = NULL;
1993 1994 1995 1996 1997
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1998
    char *taskInfoErrorMessage = NULL;
1999

2000 2001
    virCheckFlags(0, -1);

2002 2003 2004 2005 2006 2007
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

2008
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
2009
        return -1;
2010 2011
    }

2012
    if (esxVI_String_AppendValueToList(&propertyNameList,
2013
                                       "runtime.powerState") < 0 ||
2014
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2015
          (ctx, domain->uuid, propertyNameList, &virtualMachine,
2016
           priv->parsedUri->autoAnswer) < 0 ||
2017
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
2018
        goto cleanup;
2019 2020 2021
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
2022 2023
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
2024
        goto cleanup;
2025 2026
    }

2027
    if (esxVI_PowerOffVM_Task(ctx, virtualMachine->obj, &task) < 0 ||
2028 2029
        esxVI_WaitForTaskCompletion(ctx, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
2030
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2031
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2032
        goto cleanup;
2033 2034 2035
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2036 2037
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not destroy domain: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
2038
        goto cleanup;
2039 2040
    }

2041
    domain->id = -1;
M
Matthias Bolte 已提交
2042 2043
    result = 0;

2044 2045 2046 2047
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
2048
    VIR_FREE(taskInfoErrorMessage);
2049 2050 2051 2052 2053

    return result;
}


2054 2055 2056 2057 2058 2059
static int
esxDomainDestroy(virDomainPtr dom)
{
    return esxDomainDestroyFlags(dom, 0);
}

2060 2061

static char *
2062
esxDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED)
2063
{
2064 2065 2066
    char *osType = strdup("hvm");

    if (osType == NULL) {
2067
        virReportOOMError();
2068 2069 2070 2071
        return NULL;
    }

    return osType;
2072 2073 2074 2075 2076 2077 2078
}



static unsigned long
esxDomainGetMaxMemory(virDomainPtr domain)
{
M
Matthias Bolte 已提交
2079
    esxPrivate *priv = domain->conn->privateData;
2080 2081 2082 2083 2084
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    unsigned long memoryMB = 0;

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

2089
    if (esxVI_String_AppendValueToList(&propertyNameList,
2090
                                       "config.hardware.memoryMB") < 0 ||
2091
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2092
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2093
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2094
        goto cleanup;
2095 2096 2097 2098 2099
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2100
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2101
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2102
                goto cleanup;
2103 2104 2105
            }

            if (dynamicProperty->val->int32 < 0) {
2106 2107
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                          _("Got invalid memory size %d"),
2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130
                          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 已提交
2131
    int result = -1;
M
Matthias Bolte 已提交
2132
    esxPrivate *priv = domain->conn->privateData;
2133
    esxVI_String *propertyNameList = NULL;
2134
    esxVI_ObjectContent *virtualMachine = NULL;
2135
    esxVI_VirtualMachinePowerState powerState;
2136 2137 2138
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2139
    char *taskInfoErrorMessage = NULL;
2140

2141
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2142
        return -1;
2143 2144
    }

2145 2146 2147 2148
    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "runtime.powerState") < 0 ||
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
2149
           priv->parsedUri->autoAnswer) < 0 ||
2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160
        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 ||
2161
        esxVI_Long_Alloc(&spec->memoryMB) < 0) {
M
Matthias Bolte 已提交
2162
        goto cleanup;
2163 2164
    }

2165
    /* max-memory must be a multiple of 4096 kilobyte */
2166
    spec->memoryMB->value =
2167
      VIR_DIV_UP(memory, 4096) * 4; /* Scale from kilobytes to megabytes */
2168

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

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

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

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

    return result;
}



static int
esxDomainSetMemory(virDomainPtr domain, unsigned long memory)
{
M
Matthias Bolte 已提交
2202
    int result = -1;
M
Matthias Bolte 已提交
2203
    esxPrivate *priv = domain->conn->privateData;
2204 2205 2206 2207
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2208
    char *taskInfoErrorMessage = NULL;
2209

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

2214
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2215
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2216
           priv->parsedUri->autoAnswer) < 0 ||
2217 2218 2219
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0 ||
        esxVI_Long_Alloc(&spec->memoryAllocation->limit) < 0) {
M
Matthias Bolte 已提交
2220
        goto cleanup;
2221 2222 2223
    }

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

2226
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2227
                              &task) < 0 ||
2228
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2229
                                    esxVI_Occurrence_RequiredItem,
2230
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2231
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2232
        goto cleanup;
2233 2234 2235
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2236
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2237 2238
                  _("Could not set memory to %lu kilobytes: %s"), memory,
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
2239
        goto cleanup;
2240 2241
    }

M
Matthias Bolte 已提交
2242 2243
    result = 0;

2244 2245 2246 2247
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2248
    VIR_FREE(taskInfoErrorMessage);
2249 2250 2251 2252 2253 2254

    return result;
}



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

2264 2265 2266
static int
esxDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info)
{
M
Matthias Bolte 已提交
2267
    int result = -1;
M
Matthias Bolte 已提交
2268
    esxPrivate *priv = domain->conn->privateData;
2269 2270 2271 2272 2273
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int64_t memory_limit = -1;
2274
#if ESX_QUERY_FOR_USED_CPU_TIME
2275 2276 2277 2278 2279 2280 2281
    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;
2282 2283
    esxVI_PerfEntityMetricBase *perfEntityMetricBase = NULL;
    esxVI_PerfEntityMetricBase *perfEntityMetricBaseList = NULL;
2284 2285 2286
    esxVI_PerfEntityMetric *perfEntityMetric = NULL;
    esxVI_PerfMetricIntSeries *perfMetricIntSeries = NULL;
    esxVI_Long *value = NULL;
2287
#endif
2288

M
Matthias Bolte 已提交
2289 2290
    memset(info, 0, sizeof (*info));

2291
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2292
        return -1;
2293 2294
    }

2295
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2296 2297 2298 2299
                                           "runtime.powerState\0"
                                           "config.hardware.memoryMB\0"
                                           "config.hardware.numCPU\0"
                                           "config.memoryAllocation.limit\0") < 0 ||
2300
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2301
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2302
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2303
        goto cleanup;
2304 2305 2306 2307 2308 2309 2310 2311
    }

    info->state = VIR_DOMAIN_NOSTATE;

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

2316 2317
            info->state = esxVI_VirtualMachinePowerState_ConvertToLibvirt
                            (powerState);
2318
        } else if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2319
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2320
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2321
                goto cleanup;
2322 2323 2324 2325
            }

            info->maxMem = dynamicProperty->val->int32 * 1024; /* Scale from megabyte to kilobyte */
        } else if (STREQ(dynamicProperty->name, "config.hardware.numCPU")) {
2326
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2327
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2328
                goto cleanup;
2329 2330 2331 2332 2333
            }

            info->nrVirtCpu = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "config.memoryAllocation.limit")) {
2334
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2335
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
2336
                goto cleanup;
2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351
            }

            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;

2352
#if ESX_QUERY_FOR_USED_CPU_TIME
2353
    /* Verify the cached 'used CPU time' performance counter ID */
2354 2355 2356 2357 2358 2359
    /* 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;
            }
2360

2361
            counterId->value = priv->usedCpuTimeCounterId;
2362

2363 2364 2365
            if (esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                goto cleanup;
            }
2366

2367 2368 2369 2370
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfo) < 0) {
                goto cleanup;
            }
2371

2372 2373 2374 2375 2376
            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);
2377

2378 2379 2380 2381 2382
                priv->usedCpuTimeCounterId = -1;
            }

            esxVI_Int_Free(&counterIdList);
            esxVI_PerfCounterInfo_Free(&perfCounterInfo);
2383 2384
        }

2385 2386 2387 2388 2389 2390 2391 2392 2393 2394
        /*
         * 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;
            }
2395

2396 2397 2398 2399
            for (perfMetricId = perfMetricIdList; perfMetricId != NULL;
                 perfMetricId = perfMetricId->_next) {
                VIR_DEBUG("perfMetricId counterId %d, instance '%s'",
                          perfMetricId->counterId->value, perfMetricId->instance);
2400

2401
                counterId = NULL;
2402

2403 2404 2405 2406 2407
                if (esxVI_Int_DeepCopy(&counterId, perfMetricId->counterId) < 0 ||
                    esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                    goto cleanup;
                }
            }
2408

2409 2410
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfoList) < 0) {
M
Matthias Bolte 已提交
2411
                goto cleanup;
2412 2413
            }

2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430
            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;
                }
2431 2432
            }

2433
            if (priv->usedCpuTimeCounterId < 0) {
2434
                VIR_WARN("Could not find 'used CPU time' performance counter");
2435
            }
2436 2437
        }

2438 2439 2440 2441 2442 2443
        /*
         * 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);
2444

2445 2446 2447 2448 2449 2450
            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;
            }
2451

2452 2453 2454 2455 2456 2457 2458 2459 2460 2461
            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;
            }
2462

2463 2464 2465
            for (perfEntityMetricBase = perfEntityMetricBaseList;
                 perfEntityMetricBase != NULL;
                 perfEntityMetricBase = perfEntityMetricBase->_next) {
2466
                VIR_DEBUG("perfEntityMetric ...");
2467

2468 2469
                perfEntityMetric =
                  esxVI_PerfEntityMetric_DynamicCast(perfEntityMetricBase);
2470

2471
                if (perfEntityMetric == NULL) {
2472 2473
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                              _("QueryPerf returned object with unexpected type '%s'"),
2474
                              esxVI_Type_ToString(perfEntityMetricBase->_type));
2475
                    goto cleanup;
2476
                }
2477

2478 2479
                perfMetricIntSeries =
                  esxVI_PerfMetricIntSeries_DynamicCast(perfEntityMetric->value);
2480

2481
                if (perfMetricIntSeries == NULL) {
2482 2483
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                              _("QueryPerf returned object with unexpected type '%s'"),
2484
                              esxVI_Type_ToString(perfEntityMetric->value->_type));
2485
                    goto cleanup;
2486
                }
2487

2488 2489
                for (; perfMetricIntSeries != NULL;
                     perfMetricIntSeries = perfMetricIntSeries->_next) {
2490
                    VIR_DEBUG("perfMetricIntSeries ...");
2491

2492 2493 2494 2495 2496
                    for (value = perfMetricIntSeries->value;
                         value != NULL;
                         value = value->_next) {
                        VIR_DEBUG("value %lld", (long long int)value->value);
                    }
2497 2498 2499
                }
            }

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

2502
            /*
E
Eric Blake 已提交
2503
             * FIXME: Cannot map between relative used-cpu-time and absolute
2504 2505 2506
             *        info->cpuTime
             */
        }
2507
    }
2508
#endif
2509

M
Matthias Bolte 已提交
2510 2511
    result = 0;

2512
  cleanup:
2513
#if ESX_QUERY_FOR_USED_CPU_TIME
2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525
    /*
     * 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;
        }
    }
2526
#endif
2527

2528 2529
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2530
#if ESX_QUERY_FOR_USED_CPU_TIME
2531 2532 2533 2534
    esxVI_PerfMetricId_Free(&perfMetricIdList);
    esxVI_Int_Free(&counterIdList);
    esxVI_PerfCounterInfo_Free(&perfCounterInfoList);
    esxVI_PerfQuerySpec_Free(&querySpec);
2535
    esxVI_PerfEntityMetricBase_Free(&perfEntityMetricBaseList);
2536
#endif
2537 2538 2539 2540 2541 2542

    return result;
}



2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585
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;
}



2586
static int
2587 2588
esxDomainSetVcpusFlags(virDomainPtr domain, unsigned int nvcpus,
                       unsigned int flags)
2589
{
M
Matthias Bolte 已提交
2590
    int result = -1;
M
Matthias Bolte 已提交
2591
    esxPrivate *priv = domain->conn->privateData;
M
Matthias Bolte 已提交
2592
    int maxVcpus;
2593 2594 2595 2596
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2597
    char *taskInfoErrorMessage = NULL;
2598

2599
    if (flags != VIR_DOMAIN_AFFECT_LIVE) {
2600 2601 2602 2603
        ESX_ERROR(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
        return -1;
    }

2604
    if (nvcpus < 1) {
2605 2606
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Requested number of virtual CPUs must at least be 1"));
M
Matthias Bolte 已提交
2607
        return -1;
2608 2609
    }

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

M
Matthias Bolte 已提交
2614
    maxVcpus = esxDomainGetMaxVcpus(domain);
2615

M
Matthias Bolte 已提交
2616
    if (maxVcpus < 0) {
M
Matthias Bolte 已提交
2617
        return -1;
2618 2619
    }

M
Matthias Bolte 已提交
2620
    if (nvcpus > maxVcpus) {
2621
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2622 2623
                  _("Requested number of virtual CPUs is greater than max "
                    "allowable number of virtual CPUs for the domain: %d > %d"),
M
Matthias Bolte 已提交
2624
                  nvcpus, maxVcpus);
M
Matthias Bolte 已提交
2625
        return -1;
2626 2627
    }

2628
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2629
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2630
           priv->parsedUri->autoAnswer) < 0 ||
2631 2632
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Int_Alloc(&spec->numCPUs) < 0) {
M
Matthias Bolte 已提交
2633
        goto cleanup;
2634 2635 2636 2637
    }

    spec->numCPUs->value = nvcpus;

2638
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2639
                              &task) < 0 ||
2640
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2641
                                    esxVI_Occurrence_RequiredItem,
2642
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2643
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2644
        goto cleanup;
2645 2646 2647
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2648
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2649 2650
                  _("Could not set number of virtual CPUs to %d: %s"), nvcpus,
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
2651
        goto cleanup;
2652 2653
    }

M
Matthias Bolte 已提交
2654 2655
    result = 0;

2656 2657 2658 2659
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2660
    VIR_FREE(taskInfoErrorMessage);
2661 2662 2663 2664 2665

    return result;
}


M
Matthias Bolte 已提交
2666

2667 2668 2669
static int
esxDomainSetVcpus(virDomainPtr domain, unsigned int nvcpus)
{
2670
    return esxDomainSetVcpusFlags(domain, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
2671 2672
}

2673

M
Matthias Bolte 已提交
2674

2675
static int
2676
esxDomainGetVcpusFlags(virDomainPtr domain, unsigned int flags)
2677
{
M
Matthias Bolte 已提交
2678
    esxPrivate *priv = domain->conn->privateData;
2679 2680 2681 2682
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

2683
    if (flags != (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_VCPU_MAXIMUM)) {
2684 2685 2686 2687
        ESX_ERROR(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
        return -1;
    }

M
Matthias Bolte 已提交
2688 2689
    if (priv->maxVcpus > 0) {
        return priv->maxVcpus;
2690 2691
    }

M
Matthias Bolte 已提交
2692 2693
    priv->maxVcpus = -1;

2694
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2695
        return -1;
2696 2697
    }

2698
    if (esxVI_String_AppendValueToList(&propertyNameList,
2699
                                       "capability.maxSupportedVcpus") < 0 ||
2700 2701
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
2702
        goto cleanup;
2703 2704 2705
    }

    if (hostSystem == NULL) {
2706 2707
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
2708
        goto cleanup;
2709 2710 2711 2712 2713
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "capability.maxSupportedVcpus")) {
2714
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2715
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2716
                goto cleanup;
2717 2718
            }

M
Matthias Bolte 已提交
2719
            priv->maxVcpus = dynamicProperty->val->int32;
2720 2721 2722 2723 2724 2725 2726 2727 2728 2729
            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

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

M
Matthias Bolte 已提交
2730
    return priv->maxVcpus;
2731 2732
}

M
Matthias Bolte 已提交
2733 2734


2735 2736 2737
static int
esxDomainGetMaxVcpus(virDomainPtr domain)
{
2738
    return esxDomainGetVcpusFlags(domain, (VIR_DOMAIN_AFFECT_LIVE |
2739 2740
                                           VIR_DOMAIN_VCPU_MAXIMUM));
}
2741

M
Matthias Bolte 已提交
2742 2743


2744
static char *
2745
esxDomainGetXMLDesc(virDomainPtr domain, unsigned int flags)
2746
{
M
Matthias Bolte 已提交
2747
    esxPrivate *priv = domain->conn->privateData;
2748 2749
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
2750 2751
    esxVI_VirtualMachinePowerState powerState;
    int id;
2752
    char *vmPathName = NULL;
2753
    char *datastoreName = NULL;
M
Matthias Bolte 已提交
2754
    char *directoryName = NULL;
2755
    char *directoryAndFileName = NULL;
2756
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
2757 2758
    char *url = NULL;
    char *vmx = NULL;
2759
    virVMXContext ctx;
2760
    esxVMX_Data data;
2761 2762 2763
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2764 2765
    /* Flags checked by virDomainDefFormat */

2766 2767
    memset(&data, 0, sizeof (data));

2768
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2769
        return NULL;
2770 2771
    }

2772 2773 2774
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "config.files.vmPathName\0"
                                           "runtime.powerState\0") < 0 ||
2775
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2776
                                         propertyNameList, &virtualMachine,
2777
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2778 2779
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0 ||
2780 2781
        esxVI_GetStringValue(virtualMachine, "config.files.vmPathName",
                             &vmPathName, esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2782
        goto cleanup;
2783 2784
    }

2785
    if (esxUtil_ParseDatastorePath(vmPathName, &datastoreName, &directoryName,
2786
                                   &directoryAndFileName) < 0) {
M
Matthias Bolte 已提交
2787
        goto cleanup;
2788 2789
    }

2790
    virBufferAsprintf(&buffer, "%s://%s:%d/folder/", priv->parsedUri->transport,
2791
                      domain->conn->uri->server, domain->conn->uri->port);
2792
    virBufferURIEncodeString(&buffer, directoryAndFileName);
2793
    virBufferAddLit(&buffer, "?dcPath=");
2794
    virBufferURIEncodeString(&buffer, priv->primary->datacenterPath);
2795 2796 2797 2798
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
2799
        virReportOOMError();
M
Matthias Bolte 已提交
2800
        goto cleanup;
2801 2802
    }

2803 2804
    url = virBufferContentAndReset(&buffer);

2805
    if (esxVI_CURL_Download(priv->primary->curl, url, &vmx) < 0) {
M
Matthias Bolte 已提交
2806
        goto cleanup;
2807 2808
    }

2809
    data.ctx = priv->primary;
2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823

    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;
        }
    }
2824 2825 2826 2827 2828 2829

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

2830
    def = virVMXParseConfig(&ctx, priv->caps, vmx);
2831 2832

    if (def != NULL) {
2833 2834 2835 2836
        if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
            def->id = id;
        }

2837
        xml = virDomainDefFormat(def, flags);
2838 2839 2840
    }

  cleanup:
M
Matthias Bolte 已提交
2841 2842 2843 2844
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

2845 2846
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2847
    VIR_FREE(datastoreName);
M
Matthias Bolte 已提交
2848
    VIR_FREE(directoryName);
2849
    VIR_FREE(directoryAndFileName);
2850
    VIR_FREE(url);
2851
    VIR_FREE(data.datastorePathWithoutFileName);
2852
    VIR_FREE(vmx);
2853
    virDomainDefFree(def);
2854 2855 2856 2857 2858 2859 2860 2861 2862

    return xml;
}



static char *
esxDomainXMLFromNative(virConnectPtr conn, const char *nativeFormat,
                       const char *nativeConfig,
E
Eric Blake 已提交
2863
                       unsigned int flags)
2864
{
M
Matthias Bolte 已提交
2865
    esxPrivate *priv = conn->privateData;
2866
    virVMXContext ctx;
2867
    esxVMX_Data data;
2868 2869 2870
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2871 2872
    virCheckFlags(0, NULL);

2873 2874
    memset(&data, 0, sizeof (data));

2875
    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2876
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2877
                  _("Unsupported config format '%s'"), nativeFormat);
2878
        return NULL;
2879 2880
    }

2881
    data.ctx = priv->primary;
2882
    data.datastorePathWithoutFileName = (char *)"[?] ?";
2883 2884 2885 2886 2887 2888

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

2889
    def = virVMXParseConfig(&ctx, priv->caps, nativeConfig);
2890 2891

    if (def != NULL) {
2892
        xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
2893 2894 2895 2896 2897 2898 2899 2900 2901
    }

    virDomainDefFree(def);

    return xml;
}



M
Matthias Bolte 已提交
2902 2903 2904
static char *
esxDomainXMLToNative(virConnectPtr conn, const char *nativeFormat,
                     const char *domainXml,
E
Eric Blake 已提交
2905
                     unsigned int flags)
M
Matthias Bolte 已提交
2906
{
M
Matthias Bolte 已提交
2907
    esxPrivate *priv = conn->privateData;
2908 2909
    int virtualHW_version;
    virVMXContext ctx;
2910
    esxVMX_Data data;
M
Matthias Bolte 已提交
2911 2912 2913
    virDomainDefPtr def = NULL;
    char *vmx = NULL;

E
Eric Blake 已提交
2914 2915
    virCheckFlags(0, NULL);

2916 2917
    memset(&data, 0, sizeof (data));

M
Matthias Bolte 已提交
2918
    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2919
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2920
                  _("Unsupported config format '%s'"), nativeFormat);
M
Matthias Bolte 已提交
2921 2922 2923
        return NULL;
    }

2924 2925 2926 2927 2928 2929 2930
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        return NULL;
    }

M
Matthias Bolte 已提交
2931 2932
    def = virDomainDefParseString(priv->caps, domainXml,
                                  1 << VIR_DOMAIN_VIRT_VMWARE, 0);
M
Matthias Bolte 已提交
2933 2934 2935 2936 2937

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

2938
    data.ctx = priv->primary;
2939
    data.datastorePathWithoutFileName = NULL;
2940 2941 2942 2943 2944 2945

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

2946
    vmx = virVMXFormatConfig(&ctx, priv->caps, def, virtualHW_version);
M
Matthias Bolte 已提交
2947 2948 2949 2950 2951 2952 2953 2954

    virDomainDefFree(def);

    return vmx;
}



2955 2956 2957
static int
esxListDefinedDomains(virConnectPtr conn, char **const names, int maxnames)
{
M
Matthias Bolte 已提交
2958
    bool success = false;
M
Matthias Bolte 已提交
2959
    esxPrivate *priv = conn->privateData;
2960 2961 2962 2963 2964
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;
2965
    int i;
2966 2967 2968 2969 2970

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

2971
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2972
        return -1;
2973 2974
    }

2975
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2976 2977
                                           "name\0"
                                           "runtime.powerState\0") < 0 ||
2978 2979
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2980
        goto cleanup;
2981 2982 2983 2984
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
2985
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
2986
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
2987
            goto cleanup;
2988 2989 2990 2991 2992 2993
        }

        if (powerState == esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

2994
        names[count] = NULL;
2995

2996 2997 2998
        if (esxVI_GetVirtualMachineIdentity(virtualMachine, NULL, &names[count],
                                            NULL) < 0) {
            goto cleanup;
2999 3000
        }

3001 3002
        ++count;

3003 3004 3005 3006 3007
        if (count >= maxnames) {
            break;
        }
    }

M
Matthias Bolte 已提交
3008
    success = true;
3009

M
Matthias Bolte 已提交
3010 3011 3012 3013 3014
  cleanup:
    if (! success) {
        for (i = 0; i < count; ++i) {
            VIR_FREE(names[i]);
        }
3015

M
Matthias Bolte 已提交
3016
        count = -1;
3017 3018
    }

M
Matthias Bolte 已提交
3019 3020
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
3021

M
Matthias Bolte 已提交
3022
    return count;
3023 3024 3025 3026 3027 3028 3029
}



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

3032
    if (esxVI_EnsureSession(priv->primary) < 0) {
3033 3034 3035
        return -1;
    }

3036
    return esxVI_LookupNumberOfDomainsByPowerState
3037
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, true);
3038 3039 3040 3041 3042
}



static int
3043
esxDomainCreateWithFlags(virDomainPtr domain, unsigned int flags)
3044
{
M
Matthias Bolte 已提交
3045
    int result = -1;
M
Matthias Bolte 已提交
3046
    esxPrivate *priv = domain->conn->privateData;
3047 3048 3049
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
3050
    int id = -1;
3051 3052
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3053
    char *taskInfoErrorMessage = NULL;
3054

3055 3056
    virCheckFlags(0, -1);

3057
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3058
        return -1;
3059 3060
    }

3061
    if (esxVI_String_AppendValueToList(&propertyNameList,
3062
                                       "runtime.powerState") < 0 ||
3063
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3064
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
3065
           priv->parsedUri->autoAnswer) < 0 ||
3066 3067
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0) {
M
Matthias Bolte 已提交
3068
        goto cleanup;
3069 3070 3071
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
3072 3073
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered off"));
M
Matthias Bolte 已提交
3074
        goto cleanup;
3075 3076
    }

3077
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
3078
                             &task) < 0 ||
3079
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3080
                                    esxVI_Occurrence_RequiredItem,
3081
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3082
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3083
        goto cleanup;
3084 3085 3086
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3087 3088
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not start domain: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
3089
        goto cleanup;
3090 3091
    }

3092
    domain->id = id;
M
Matthias Bolte 已提交
3093 3094
    result = 0;

3095 3096 3097 3098
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
3099
    VIR_FREE(taskInfoErrorMessage);
3100 3101 3102 3103

    return result;
}

3104 3105


3106 3107 3108 3109 3110
static int
esxDomainCreate(virDomainPtr domain)
{
    return esxDomainCreateWithFlags(domain, 0);
}
3111

3112 3113


M
Matthias Bolte 已提交
3114
static virDomainPtr
3115
esxDomainDefineXML(virConnectPtr conn, const char *xml)
M
Matthias Bolte 已提交
3116
{
M
Matthias Bolte 已提交
3117
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
3118 3119
    virDomainDefPtr def = NULL;
    char *vmx = NULL;
3120 3121
    int i;
    virDomainDiskDefPtr disk = NULL;
M
Matthias Bolte 已提交
3122
    esxVI_ObjectContent *virtualMachine = NULL;
3123 3124
    int virtualHW_version;
    virVMXContext ctx;
3125
    esxVMX_Data data;
M
Matthias Bolte 已提交
3126 3127
    char *datastoreName = NULL;
    char *directoryName = NULL;
3128
    char *escapedName = NULL;
M
Matthias Bolte 已提交
3129 3130 3131 3132 3133 3134 3135 3136
    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;
3137
    char *taskInfoErrorMessage = NULL;
M
Matthias Bolte 已提交
3138 3139
    virDomainPtr domain = NULL;

3140 3141
    memset(&data, 0, sizeof (data));

3142
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3143
        return NULL;
M
Matthias Bolte 已提交
3144 3145 3146
    }

    /* Parse domain XML */
M
Matthias Bolte 已提交
3147
    def = virDomainDefParseString(priv->caps, xml, 1 << VIR_DOMAIN_VIRT_VMWARE,
M
Matthias Bolte 已提交
3148 3149 3150
                                  VIR_DOMAIN_XML_INACTIVE);

    if (def == NULL) {
M
Matthias Bolte 已提交
3151
        return NULL;
M
Matthias Bolte 已提交
3152 3153 3154
    }

    /* Check if an existing domain should be edited */
3155
    if (esxVI_LookupVirtualMachineByUuid(priv->primary, def->uuid, NULL,
M
Matthias Bolte 已提交
3156
                                         &virtualMachine,
M
Matthias Bolte 已提交
3157
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
3158
        goto cleanup;
M
Matthias Bolte 已提交
3159 3160
    }

3161 3162 3163 3164 3165 3166 3167
    if (virtualMachine == NULL &&
        esxVI_LookupVirtualMachineByName(priv->primary, def->name, NULL,
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
    }

M
Matthias Bolte 已提交
3168 3169
    if (virtualMachine != NULL) {
        /* FIXME */
3170 3171 3172
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Domain already exists, editing existing domains is not "
                    "supported yet"));
M
Matthias Bolte 已提交
3173
        goto cleanup;
M
Matthias Bolte 已提交
3174 3175 3176
    }

    /* Build VMX from domain XML */
3177 3178 3179 3180 3181 3182 3183
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        goto cleanup;
    }

3184
    data.ctx = priv->primary;
3185
    data.datastorePathWithoutFileName = NULL;
3186 3187 3188 3189 3190 3191

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

3192
    vmx = virVMXFormatConfig(&ctx, priv->caps, def, virtualHW_version);
M
Matthias Bolte 已提交
3193 3194

    if (vmx == NULL) {
M
Matthias Bolte 已提交
3195
        goto cleanup;
M
Matthias Bolte 已提交
3196 3197
    }

3198 3199 3200 3201 3202 3203 3204
    /*
     * 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 已提交
3205
    if (def->ndisks < 1) {
3206 3207 3208
        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 已提交
3209
        goto cleanup;
3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220
    }

    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) {
3221 3222 3223
        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 已提交
3224
        goto cleanup;
M
Matthias Bolte 已提交
3225 3226
    }

3227
    if (disk->src == NULL) {
3228 3229 3230
        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 已提交
3231
        goto cleanup;
M
Matthias Bolte 已提交
3232 3233
    }

3234
    if (esxUtil_ParseDatastorePath(disk->src, &datastoreName, &directoryName,
3235
                                   NULL) < 0) {
M
Matthias Bolte 已提交
3236
        goto cleanup;
M
Matthias Bolte 已提交
3237 3238
    }

3239
    if (! virFileHasSuffix(disk->src, ".vmdk")) {
3240
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3241 3242
                  _("Expecting source '%s' of first file-based harddisk to "
                    "be a VMDK image"), disk->src);
M
Matthias Bolte 已提交
3243
        goto cleanup;
M
Matthias Bolte 已提交
3244 3245
    }

3246
    virBufferAsprintf(&buffer, "%s://%s:%d/folder/", priv->parsedUri->transport,
M
Matthias Bolte 已提交
3247 3248 3249 3250 3251 3252 3253
                      conn->uri->server, conn->uri->port);

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

3254 3255 3256 3257 3258 3259 3260
    escapedName = esxUtil_EscapeDatastoreItem(def->name);

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

    virBufferURIEncodeString(&buffer, escapedName);
M
Matthias Bolte 已提交
3261
    virBufferAddLit(&buffer, ".vmx?dcPath=");
3262
    virBufferURIEncodeString(&buffer, priv->primary->datacenterPath);
M
Matthias Bolte 已提交
3263 3264 3265 3266
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
3267
        virReportOOMError();
M
Matthias Bolte 已提交
3268
        goto cleanup;
M
Matthias Bolte 已提交
3269 3270 3271 3272
    }

    url = virBufferContentAndReset(&buffer);

3273 3274 3275 3276 3277 3278
    /* Check, if VMX file already exists */
    /* FIXME */

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

3279
    if (esxVI_CURL_Upload(priv->primary->curl, url, vmx) < 0) {
3280 3281 3282 3283
        goto cleanup;
    }

    /* Register the domain */
M
Matthias Bolte 已提交
3284 3285
    if (directoryName != NULL) {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s/%s.vmx", datastoreName,
3286
                        directoryName, escapedName) < 0) {
3287
            virReportOOMError();
M
Matthias Bolte 已提交
3288
            goto cleanup;
M
Matthias Bolte 已提交
3289 3290 3291
        }
    } else {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s.vmx", datastoreName,
3292
                        escapedName) < 0) {
3293
            virReportOOMError();
M
Matthias Bolte 已提交
3294
            goto cleanup;
M
Matthias Bolte 已提交
3295 3296 3297
        }
    }

3298
    if (esxVI_RegisterVM_Task(priv->primary, priv->primary->datacenter->vmFolder,
M
Matthias Bolte 已提交
3299
                              datastoreRelatedPath, NULL, esxVI_Boolean_False,
3300 3301 3302 3303
                              priv->primary->computeResource->resourcePool,
                              priv->primary->hostSystem->_reference,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, def->uuid,
3304
                                    esxVI_Occurrence_OptionalItem,
3305
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3306
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3307
        goto cleanup;
M
Matthias Bolte 已提交
3308 3309 3310
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3311 3312
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not define domain: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
3313
        goto cleanup;
M
Matthias Bolte 已提交
3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324
    }

    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 已提交
3325 3326 3327 3328
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

M
Matthias Bolte 已提交
3329 3330 3331 3332
    virDomainDefFree(def);
    VIR_FREE(vmx);
    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
3333
    VIR_FREE(escapedName);
M
Matthias Bolte 已提交
3334 3335 3336 3337 3338 3339 3340
    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);
3341
    VIR_FREE(taskInfoErrorMessage);
M
Matthias Bolte 已提交
3342 3343 3344 3345 3346 3347

    return domain;
}



3348
static int
3349 3350
esxDomainUndefineFlags(virDomainPtr domain,
                       unsigned int flags)
3351
{
M
Matthias Bolte 已提交
3352
    int result = -1;
M
Matthias Bolte 已提交
3353
    esxPrivate *priv = domain->conn->privateData;
3354
    esxVI_Context *ctx = NULL;
3355 3356 3357 3358
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

3359 3360 3361 3362
    /* 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);
3363

3364 3365 3366 3367 3368 3369
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

3370
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
3371
        return -1;
3372 3373
    }

3374
    if (esxVI_String_AppendValueToList(&propertyNameList,
3375
                                       "runtime.powerState") < 0 ||
3376 3377
        esxVI_LookupVirtualMachineByUuid(ctx, domain->uuid, propertyNameList,
                                         &virtualMachine,
M
Matthias Bolte 已提交
3378
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3379
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
3380
        goto cleanup;
3381 3382 3383 3384
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended &&
        powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
3385 3386
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not suspended or powered off"));
M
Matthias Bolte 已提交
3387
        goto cleanup;
3388 3389
    }

3390
    if (esxVI_UnregisterVM(ctx, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
3391
        goto cleanup;
3392 3393
    }

M
Matthias Bolte 已提交
3394 3395
    result = 0;

3396 3397 3398 3399 3400 3401 3402 3403
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}


3404 3405 3406 3407 3408
static int
esxDomainUndefine(virDomainPtr domain)
{
    return esxDomainUndefineFlags(domain, 0);
}
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 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588
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;
}



3589 3590 3591 3592 3593 3594 3595 3596 3597 3598
/*
 * 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:
 *
3599
 * - reservation (VIR_TYPED_PARAM_LLONG >= 0, in megaherz)
3600
 *
3601
 *   The amount of CPU resource that is guaranteed to be available to the domain.
3602 3603
 *
 *
3604
 * - limit (VIR_TYPED_PARAM_LLONG >= 0, or -1, in megaherz)
3605
 *
3606 3607
 *   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
3608 3609 3610 3611
 *   utilization of the domain is unlimited. If the limit is not set to -1, it
 *   must be greater than or equal to the reservation.
 *
 *
3612
 * - shares (VIR_TYPED_PARAM_INT >= 0, or in {-1, -2, -3}, no unit)
3613 3614 3615 3616 3617 3618
 *
 *   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'.
 */
3619
static char *
3620
esxDomainGetSchedulerType(virDomainPtr domain ATTRIBUTE_UNUSED, int *nparams)
3621 3622 3623 3624
{
    char *type = strdup("allocation");

    if (type == NULL) {
3625
        virReportOOMError();
3626
        return NULL;
3627 3628
    }

3629 3630 3631
    if (nparams != NULL) {
        *nparams = 3; /* reservation, limit, shares */
    }
3632 3633 3634 3635 3636 3637 3638

    return type;
}



static int
3639 3640 3641
esxDomainGetSchedulerParametersFlags(virDomainPtr domain,
                                     virTypedParameterPtr params, int *nparams,
                                     unsigned int flags)
3642
{
M
Matthias Bolte 已提交
3643
    int result = -1;
M
Matthias Bolte 已提交
3644
    esxPrivate *priv = domain->conn->privateData;
3645 3646 3647 3648 3649 3650 3651
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    unsigned int mask = 0;
    int i = 0;

3652 3653
    virCheckFlags(0, -1);

3654
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3655
        return -1;
3656 3657
    }

3658
    if (esxVI_String_AppendValueListToList(&propertyNameList,
3659 3660 3661
                                           "config.cpuAllocation.reservation\0"
                                           "config.cpuAllocation.limit\0"
                                           "config.cpuAllocation.shares\0") < 0 ||
3662
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
3663
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3664
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3665
        goto cleanup;
3666 3667 3668
    }

    for (dynamicProperty = virtualMachine->propSet;
3669
         dynamicProperty != NULL && mask != 7 && i < 3 && i < *nparams;
3670 3671
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.cpuAllocation.reservation") &&
M
Matthias Bolte 已提交
3672
            ! (mask & (1 << 0))) {
3673
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3674
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3675
                goto cleanup;
3676
            }
3677 3678 3679 3680 3681
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_SCHEDULER_RESERVATION,
                                        VIR_TYPED_PARAM_LLONG,
                                        dynamicProperty->val->int64) < 0)
                goto cleanup;
3682 3683 3684 3685
            mask |= 1 << 0;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.limit") &&
M
Matthias Bolte 已提交
3686
                   ! (mask & (1 << 1))) {
3687
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3688
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3689
                goto cleanup;
3690
            }
3691 3692 3693 3694 3695
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_SCHEDULER_LIMIT,
                                        VIR_TYPED_PARAM_LLONG,
                                        dynamicProperty->val->int64) < 0)
                goto cleanup;
3696 3697 3698 3699
            mask |= 1 << 1;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.shares") &&
M
Matthias Bolte 已提交
3700
                   ! (mask & (1 << 2))) {
3701 3702 3703 3704
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_SCHEDULER_SHARES,
                                        VIR_TYPED_PARAM_INT, 0) < 0)
                goto cleanup;
3705
            if (esxVI_SharesInfo_CastFromAnyType(dynamicProperty->val,
3706
                                                 &sharesInfo) < 0) {
M
Matthias Bolte 已提交
3707
                goto cleanup;
3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727
            }

            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:
3728
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3729
                          _("Shares level has unknown value %d"),
3730
                          (int)sharesInfo->level);
M
Matthias Bolte 已提交
3731
                goto cleanup;
3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743
            }

            esxVI_SharesInfo_Free(&sharesInfo);

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

    *nparams = i;
M
Matthias Bolte 已提交
3744
    result = 0;
3745 3746 3747 3748 3749 3750 3751 3752

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

    return result;
}

3753 3754 3755 3756 3757 3758
static int
esxDomainGetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int *nparams)
{
    return esxDomainGetSchedulerParametersFlags(domain, params, nparams, 0);
}
3759 3760 3761


static int
3762 3763 3764
esxDomainSetSchedulerParametersFlags(virDomainPtr domain,
                                     virTypedParameterPtr params, int nparams,
                                     unsigned int flags)
3765
{
M
Matthias Bolte 已提交
3766
    int result = -1;
M
Matthias Bolte 已提交
3767
    esxPrivate *priv = domain->conn->privateData;
3768 3769 3770 3771 3772
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3773
    char *taskInfoErrorMessage = NULL;
3774 3775
    int i;

3776
    virCheckFlags(0, -1);
3777 3778 3779 3780 3781 3782 3783 3784 3785
    if (virTypedParameterArrayValidate(params, nparams,
                                       VIR_DOMAIN_SCHEDULER_RESERVATION,
                                       VIR_TYPED_PARAM_LLONG,
                                       VIR_DOMAIN_SCHEDULER_LIMIT,
                                       VIR_TYPED_PARAM_LLONG,
                                       VIR_DOMAIN_SCHEDULER_SHARES,
                                       VIR_TYPED_PARAM_INT,
                                       NULL) < 0)
        return -1;
3786

3787
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3788
        return -1;
3789 3790
    }

3791
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3792
          (priv->primary, domain->uuid, NULL, &virtualMachine,
3793
           priv->parsedUri->autoAnswer) < 0 ||
3794 3795
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->cpuAllocation) < 0) {
M
Matthias Bolte 已提交
3796
        goto cleanup;
3797 3798 3799
    }

    for (i = 0; i < nparams; ++i) {
3800
        if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_RESERVATION)) {
3801
            if (esxVI_Long_Alloc(&spec->cpuAllocation->reservation) < 0) {
M
Matthias Bolte 已提交
3802
                goto cleanup;
3803 3804 3805
            }

            if (params[i].value.l < 0) {
3806
                ESX_ERROR(VIR_ERR_INVALID_ARG,
3807 3808
                          _("Could not set reservation to %lld MHz, expecting "
                            "positive value"), params[i].value.l);
M
Matthias Bolte 已提交
3809
                goto cleanup;
3810 3811 3812
            }

            spec->cpuAllocation->reservation->value = params[i].value.l;
3813
        } else if(STREQ (params[i].field, VIR_DOMAIN_SCHEDULER_LIMIT)) {
3814
            if (esxVI_Long_Alloc(&spec->cpuAllocation->limit) < 0) {
M
Matthias Bolte 已提交
3815
                goto cleanup;
3816 3817 3818
            }

            if (params[i].value.l < -1) {
3819
                ESX_ERROR(VIR_ERR_INVALID_ARG,
3820 3821
                          _("Could not set limit to %lld MHz, expecting "
                            "positive value or -1 (unlimited)"),
3822
                          params[i].value.l);
M
Matthias Bolte 已提交
3823
                goto cleanup;
3824 3825 3826
            }

            spec->cpuAllocation->limit->value = params[i].value.l;
3827
        } else if(STREQ (params[i].field, VIR_DOMAIN_SCHEDULER_SHARES)) {
3828 3829
            if (esxVI_SharesInfo_Alloc(&sharesInfo) < 0 ||
                esxVI_Int_Alloc(&sharesInfo->shares) < 0) {
M
Matthias Bolte 已提交
3830
                goto cleanup;
3831 3832 3833 3834
            }

            spec->cpuAllocation->shares = sharesInfo;

3835
            if (params[i].value.i >= 0) {
3836
                spec->cpuAllocation->shares->level = esxVI_SharesLevel_Custom;
3837
                spec->cpuAllocation->shares->shares->value = params[i].value.i;
3838
            } else {
3839
                switch (params[i].value.i) {
3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857
                  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:
3858
                    ESX_ERROR(VIR_ERR_INVALID_ARG,
3859 3860
                              _("Could not set shares to %d, expecting positive "
                                "value or -1 (low), -2 (normal) or -3 (high)"),
3861
                              params[i].value.i);
M
Matthias Bolte 已提交
3862
                    goto cleanup;
3863 3864 3865 3866 3867
                }
            }
        }
    }

3868
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
3869
                              &task) < 0 ||
3870
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3871
                                    esxVI_Occurrence_RequiredItem,
3872
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3873
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3874
        goto cleanup;
3875 3876 3877
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3878 3879 3880
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not change scheduler parameters: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
3881
        goto cleanup;
3882 3883
    }

M
Matthias Bolte 已提交
3884 3885
    result = 0;

3886 3887 3888 3889
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
3890
    VIR_FREE(taskInfoErrorMessage);
3891 3892 3893 3894

    return result;
}

3895 3896 3897 3898 3899 3900
static int
esxDomainSetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int nparams)
{
    return esxDomainSetSchedulerParametersFlags(domain, params, nparams, 0);
}
3901

E
Eric Blake 已提交
3902 3903 3904 3905 3906 3907
/* 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)
3908 3909 3910 3911 3912

static int
esxDomainMigratePrepare(virConnectPtr dconn,
                        char **cookie ATTRIBUTE_UNUSED,
                        int *cookielen ATTRIBUTE_UNUSED,
3913 3914
                        const char *uri_in ATTRIBUTE_UNUSED,
                        char **uri_out,
E
Eric Blake 已提交
3915
                        unsigned long flags,
3916 3917 3918
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
3919
    esxPrivate *priv = dconn->privateData;
3920

E
Eric Blake 已提交
3921 3922
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

3923
    if (uri_in == NULL) {
3924 3925 3926 3927
        if (virAsprintf(uri_out, "vpxmigr://%s/%s/%s",
                        priv->vCenter->ipAddress,
                        priv->vCenter->computeResource->resourcePool->value,
                        priv->vCenter->hostSystem->_reference->value) < 0) {
3928
            virReportOOMError();
3929
            return -1;
3930 3931 3932
        }
    }

3933
    return 0;
3934 3935 3936 3937 3938 3939 3940 3941 3942
}



static int
esxDomainMigratePerform(virDomainPtr domain,
                        const char *cookie ATTRIBUTE_UNUSED,
                        int cookielen ATTRIBUTE_UNUSED,
                        const char *uri,
E
Eric Blake 已提交
3943
                        unsigned long flags,
3944 3945 3946
                        const char *dname,
                        unsigned long bandwidth ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
3947
    int result = -1;
M
Matthias Bolte 已提交
3948
    esxPrivate *priv = domain->conn->privateData;
M
Martin Kletzander 已提交
3949
    virURIPtr parsedUri = NULL;
3950 3951 3952
    char *saveptr;
    char *path_resourcePool;
    char *path_hostSystem;
3953
    esxVI_ObjectContent *virtualMachine = NULL;
3954 3955
    esxVI_ManagedObjectReference resourcePool;
    esxVI_ManagedObjectReference hostSystem;
3956 3957 3958
    esxVI_Event *eventList = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3959
    char *taskInfoErrorMessage = NULL;
3960

E
Eric Blake 已提交
3961 3962
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

M
Matthias Bolte 已提交
3963
    if (priv->vCenter == NULL) {
3964 3965
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Migration not possible without a vCenter"));
M
Matthias Bolte 已提交
3966
        return -1;
3967 3968 3969
    }

    if (dname != NULL) {
3970 3971
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Renaming domains on migration not supported"));
M
Matthias Bolte 已提交
3972
        return -1;
3973 3974
    }

3975
    if (esxVI_EnsureSession(priv->vCenter) < 0) {
M
Matthias Bolte 已提交
3976
        return -1;
3977 3978
    }

3979
    /* Parse migration URI */
M
Martin Kletzander 已提交
3980
    parsedUri = virURIParse(uri);
3981

3982
    if (parsedUri == NULL) {
3983
        virReportOOMError();
M
Matthias Bolte 已提交
3984
        return -1;
3985 3986
    }

3987 3988 3989
    if (parsedUri->scheme == NULL || STRCASENEQ(parsedUri->scheme, "vpxmigr")) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Only vpxmigr:// migration URIs are supported"));
M
Matthias Bolte 已提交
3990
        goto cleanup;
3991 3992
    }

3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005
    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 已提交
4006
        goto cleanup;
4007 4008
    }

4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021
    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,
4022
           priv->parsedUri->autoAnswer) < 0) {
M
Matthias Bolte 已提交
4023
        goto cleanup;
4024 4025 4026
    }

    /* Validate the purposed migration */
4027
    if (esxVI_ValidateMigration(priv->vCenter, virtualMachine->obj,
4028 4029
                                esxVI_VirtualMachinePowerState_Undefined, NULL,
                                &resourcePool, &hostSystem, &eventList) < 0) {
M
Matthias Bolte 已提交
4030
        goto cleanup;
4031 4032 4033 4034 4035 4036 4037 4038
    }

    if (eventList != NULL) {
        /*
         * FIXME: Need to report the complete list of events. Limit reporting
         *        to the first event for now.
         */
        if (eventList->fullFormattedMessage != NULL) {
4039
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
4040 4041
                      _("Could not migrate domain, validation reported a "
                        "problem: %s"), eventList->fullFormattedMessage);
4042
        } else {
4043 4044 4045
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                      _("Could not migrate domain, validation reported a "
                        "problem"));
4046 4047
        }

M
Matthias Bolte 已提交
4048
        goto cleanup;
4049 4050 4051
    }

    /* Perform the purposed migration */
4052 4053
    if (esxVI_MigrateVM_Task(priv->vCenter, virtualMachine->obj,
                             &resourcePool, &hostSystem,
4054 4055 4056
                             esxVI_VirtualMachineMovePriority_DefaultPriority,
                             esxVI_VirtualMachinePowerState_Undefined,
                             &task) < 0 ||
4057
        esxVI_WaitForTaskCompletion(priv->vCenter, task, domain->uuid,
4058
                                    esxVI_Occurrence_RequiredItem,
4059
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4060
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4061
        goto cleanup;
4062 4063 4064
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4065
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
4066
                  _("Could not migrate domain, migration task finished with "
4067 4068
                    "an error: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
4069
        goto cleanup;
4070 4071
    }

M
Matthias Bolte 已提交
4072 4073
    result = 0;

4074
  cleanup:
4075
    xmlFreeURI(parsedUri);
4076 4077 4078
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Event_Free(&eventList);
    esxVI_ManagedObjectReference_Free(&task);
4079
    VIR_FREE(taskInfoErrorMessage);
4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090

    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 已提交
4091
                       unsigned long flags)
4092
{
E
Eric Blake 已提交
4093 4094
    virCheckFlags(ESX_MIGRATION_FLAGS, NULL);

4095 4096 4097 4098 4099
    return esxDomainLookupByName(dconn, dname);
}



M
Matthias Bolte 已提交
4100 4101 4102 4103
static unsigned long long
esxNodeGetFreeMemory(virConnectPtr conn)
{
    unsigned long long result = 0;
M
Matthias Bolte 已提交
4104
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
4105 4106 4107 4108 4109
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *resourcePool = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ResourcePoolResourceUsage *resourcePoolResourceUsage = NULL;

4110
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4111
        return 0;
M
Matthias Bolte 已提交
4112 4113 4114
    }

    /* Get memory usage of resource pool */
4115
    if (esxVI_String_AppendValueToList(&propertyNameList,
M
Matthias Bolte 已提交
4116
                                       "runtime.memory") < 0 ||
4117 4118
        esxVI_LookupObjectContentByType(priv->primary,
                                        priv->primary->computeResource->resourcePool,
4119
                                        "ResourcePool", propertyNameList,
4120 4121
                                        &resourcePool,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4122
        goto cleanup;
M
Matthias Bolte 已提交
4123 4124 4125 4126 4127 4128
    }

    for (dynamicProperty = resourcePool->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.memory")) {
            if (esxVI_ResourcePoolResourceUsage_CastFromAnyType
4129
                  (dynamicProperty->val, &resourcePoolResourceUsage) < 0) {
M
Matthias Bolte 已提交
4130
                goto cleanup;
M
Matthias Bolte 已提交
4131 4132 4133 4134 4135 4136 4137 4138 4139
            }

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

    if (resourcePoolResourceUsage == NULL) {
4140 4141
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve memory usage of resource pool"));
M
Matthias Bolte 已提交
4142
        goto cleanup;
M
Matthias Bolte 已提交
4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156
    }

    result = resourcePoolResourceUsage->unreservedForVm->value;

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

    return result;
}



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

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



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

4176
    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
4177 4178 4179 4180 4181 4182 4183 4184
        return 1;
    } else {
        return 0;
    }
}



4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201
static int
esxIsAlive(virConnectPtr conn)
{
    esxPrivate *priv = conn->privateData;

    /* XXX we should be able to do something better than this but this is
     * simple, safe, and good enough for now. In worst case, the function will
     * return true even though the connection is not alive.
     */
    if (priv->primary)
        return 1;
    else
        return 0;
}



4202 4203 4204
static int
esxDomainIsActive(virDomainPtr domain)
{
M
Matthias Bolte 已提交
4205
    int result = -1;
M
Matthias Bolte 已提交
4206
    esxPrivate *priv = domain->conn->privateData;
4207 4208 4209 4210
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

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

4215
    if (esxVI_String_AppendValueToList(&propertyNameList,
4216
                                       "runtime.powerState") < 0 ||
4217
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
4218
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
4219
                                         esxVI_Occurrence_RequiredItem) < 0 ||
4220
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
4221
        goto cleanup;
4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245
    }

    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 已提交
4246 4247


4248 4249 4250 4251 4252
static int
esxDomainIsUpdated(virDomainPtr domain ATTRIBUTE_UNUSED)
{
    return 0;
}
4253

M
Matthias Bolte 已提交
4254 4255


4256 4257
static virDomainSnapshotPtr
esxDomainSnapshotCreateXML(virDomainPtr domain, const char *xmlDesc,
4258
                           unsigned int flags)
4259 4260 4261 4262 4263 4264 4265 4266
{
    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;
4267
    char *taskInfoErrorMessage = NULL;
4268 4269
    virDomainSnapshotPtr snapshot = NULL;

4270 4271
    /* ESX has no snapshot metadata, so this flag is trivial.  */
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA, NULL);
4272

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

4277
    def = virDomainSnapshotDefParseString(xmlDesc, NULL, 0, 0);
4278 4279

    if (def == NULL) {
M
Matthias Bolte 已提交
4280
        return NULL;
4281 4282
    }

4283 4284 4285 4286 4287 4288
    if (def->ndisks) {
        ESX_ERROR(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                  _("disk snapshots not supported yet"));
        return NULL;
    }

4289
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
4290
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4291
           priv->parsedUri->autoAnswer) < 0 ||
4292
        esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4293 4294
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, def->name,
4295
                                    &snapshotTree, NULL,
4296
                                    esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4297
        goto cleanup;
4298 4299 4300 4301 4302
    }

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

4306
    if (esxVI_CreateSnapshot_Task(priv->primary, virtualMachine->obj,
4307 4308 4309
                                  def->name, def->description,
                                  esxVI_Boolean_True,
                                  esxVI_Boolean_False, &task) < 0 ||
4310
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
4311
                                    esxVI_Occurrence_RequiredItem,
4312
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4313
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4314
        goto cleanup;
4315 4316 4317
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4318 4319
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, _("Could not create snapshot: %s"),
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
4320
        goto cleanup;
4321 4322 4323 4324 4325 4326 4327 4328 4329
    }

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

  cleanup:
    virDomainSnapshotDefFree(def);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4330
    VIR_FREE(taskInfoErrorMessage);
4331 4332 4333 4334 4335 4336 4337

    return snapshot;
}



static char *
4338 4339
esxDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                            unsigned int flags)
4340 4341 4342 4343 4344 4345 4346 4347 4348
{
    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;

4349 4350
    virCheckFlags(0, NULL);

M
Matthias Bolte 已提交
4351
    memset(&def, 0, sizeof (def));
4352

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

4357
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4358 4359 4360 4361
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4362
        goto cleanup;
4363 4364 4365 4366 4367 4368 4369 4370
    }

    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 已提交
4371
        goto cleanup;
4372 4373 4374 4375 4376 4377 4378
    }

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

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

4379
    xml = virDomainSnapshotDefFormat(uuid_string, &def, flags, 0);
4380 4381 4382 4383 4384 4385 4386 4387 4388 4389

  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return xml;
}



static int
4390
esxDomainSnapshotNum(virDomainPtr domain, unsigned int flags)
4391
{
M
Matthias Bolte 已提交
4392
    int count;
4393 4394
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
4395
    bool recurse;
4396
    bool leaves;
4397

4398
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
4399 4400
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4401 4402

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) == 0;
4403
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4404

4405
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4406
        return -1;
4407 4408
    }

4409 4410 4411 4412
    /* ESX snapshots do not require libvirt to maintain any metadata.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA)
        return 0;

4413
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4414
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4415
        return -1;
4416 4417
    }

4418 4419
    count = esxVI_GetNumberOfSnapshotTrees(rootSnapshotTreeList, recurse,
                                           leaves);
4420 4421 4422

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

M
Matthias Bolte 已提交
4423
    return count;
4424 4425 4426 4427 4428 4429
}



static int
esxDomainSnapshotListNames(virDomainPtr domain, char **names, int nameslen,
4430
                           unsigned int flags)
4431
{
M
Matthias Bolte 已提交
4432
    int result;
4433 4434
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
4435
    bool recurse;
4436
    bool leaves;
4437 4438

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
4439 4440
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4441

4442
    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) == 0;
4443
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4444

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

4450
    if (nameslen == 0 || (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA)) {
4451 4452 4453
        return 0;
    }

4454
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4455
        return -1;
4456 4457
    }

4458
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4459
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4460
        return -1;
4461 4462
    }

4463
    result = esxVI_GetSnapshotTreeNames(rootSnapshotTreeList, names, nameslen,
4464
                                        recurse, leaves);
4465 4466 4467 4468 4469 4470 4471 4472

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



4473 4474 4475 4476 4477 4478 4479 4480
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;
4481
    bool leaves;
4482 4483

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
4484 4485
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4486 4487

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) != 0;
4488
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508

    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,
4509
                                           recurse, leaves);
4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528

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;
4529
    bool leaves;
4530 4531

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
4532 4533
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4534 4535

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) != 0;
4536
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565

    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,
4566
                                        names, nameslen, recurse, leaves);
4567 4568 4569 4570 4571 4572 4573 4574 4575

cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



4576 4577
static virDomainSnapshotPtr
esxDomainSnapshotLookupByName(virDomainPtr domain, const char *name,
4578
                              unsigned int flags)
4579 4580 4581 4582 4583 4584
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    virDomainSnapshotPtr snapshot = NULL;

4585 4586
    virCheckFlags(0, NULL);

4587
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4588
        return NULL;
4589 4590
    }

4591
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4592 4593
                                         &rootSnapshotTreeList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotTreeList, name, &snapshotTree,
4594
                                    NULL,
4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614
                                    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;

4615
    virCheckFlags(0, -1);
4616

4617
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4618
        return -1;
4619 4620
    }

4621
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4622 4623
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4624
        return -1;
4625 4626 4627
    }

    if (currentSnapshotTree != NULL) {
M
Matthias Bolte 已提交
4628 4629
        esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);
        return 1;
4630 4631
    }

M
Matthias Bolte 已提交
4632
    return 0;
4633 4634 4635 4636
}



E
Eric Blake 已提交
4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676
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;
}



4677 4678 4679 4680 4681
static virDomainSnapshotPtr
esxDomainSnapshotCurrent(virDomainPtr domain, unsigned int flags)
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *currentSnapshotTree = NULL;
M
Matthias Bolte 已提交
4682
    virDomainSnapshotPtr snapshot = NULL;
4683

4684
    virCheckFlags(0, NULL);
4685

4686
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4687
        return NULL;
4688 4689
    }

4690
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4691 4692
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4693
        return NULL;
4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707
    }

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

    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return snapshot;
}



static int
esxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4708
    int result = -1;
4709 4710 4711 4712 4713
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
4714
    char *taskInfoErrorMessage = NULL;
4715

4716
    virCheckFlags(0, -1);
4717

4718
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4719
        return -1;
4720 4721
    }

4722
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4723 4724
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
4725
                                    &snapshotTree, NULL,
4726
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4727
        goto cleanup;
4728 4729
    }

4730
    if (esxVI_RevertToSnapshot_Task(priv->primary, snapshotTree->snapshot, NULL,
4731
                                    &task) < 0 ||
4732
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4733
                                    esxVI_Occurrence_RequiredItem,
4734
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4735
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4736
        goto cleanup;
4737 4738 4739 4740
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
4741 4742
                  _("Could not revert to snapshot '%s': %s"), snapshot->name,
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
4743
        goto cleanup;
4744 4745
    }

M
Matthias Bolte 已提交
4746 4747
    result = 0;

4748 4749 4750
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4751
    VIR_FREE(taskInfoErrorMessage);
4752 4753 4754 4755 4756 4757 4758 4759 4760

    return result;
}



static int
esxDomainSnapshotDelete(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4761
    int result = -1;
4762 4763 4764 4765 4766 4767
    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;
4768
    char *taskInfoErrorMessage = NULL;
4769

4770 4771
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
                  VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY, -1);
4772

4773
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4774
        return -1;
4775 4776 4777 4778 4779 4780
    }

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

4781
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4782 4783
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
4784
                                    &snapshotTree, NULL,
4785
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4786
        goto cleanup;
4787 4788
    }

4789 4790 4791 4792 4793 4794 4795
    /* 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;
    }

4796
    if (esxVI_RemoveSnapshot_Task(priv->primary, snapshotTree->snapshot,
4797
                                  removeChildren, &task) < 0 ||
4798
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4799
                                    esxVI_Occurrence_RequiredItem,
4800
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4801
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4802
        goto cleanup;
4803 4804 4805 4806
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
4807 4808
                  _("Could not delete snapshot '%s': %s"), snapshot->name,
                  taskInfoErrorMessage);
M
Matthias Bolte 已提交
4809
        goto cleanup;
4810 4811
    }

M
Matthias Bolte 已提交
4812 4813
    result = 0;

4814 4815 4816
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4817
    VIR_FREE(taskInfoErrorMessage);
4818 4819 4820 4821 4822 4823

    return result;
}



4824
static int
4825
esxDomainSetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
4826 4827 4828 4829 4830 4831 4832 4833
                             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;
4834
    char *taskInfoErrorMessage = NULL;
4835 4836 4837
    int i;

    virCheckFlags(0, -1);
4838 4839 4840 4841 4842
    if (virTypedParameterArrayValidate(params, nparams,
                                       VIR_DOMAIN_MEMORY_MIN_GUARANTEE,
                                       VIR_TYPED_PARAM_ULLONG,
                                       NULL) < 0)
        return -1;
4843 4844 4845 4846 4847 4848 4849

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

    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4850
           priv->parsedUri->autoAnswer) < 0 ||
4851 4852 4853 4854 4855 4856
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0) {
        goto cleanup;
    }

    for (i = 0; i < nparams; ++i) {
4857
        if (STREQ(params[i].field, VIR_DOMAIN_MEMORY_MIN_GUARANTEE)) {
4858 4859 4860 4861 4862
            if (esxVI_Long_Alloc(&spec->memoryAllocation->reservation) < 0) {
                goto cleanup;
            }

            spec->memoryAllocation->reservation->value =
4863
              VIR_DIV_UP(params[i].value.ul, 1024); /* Scale from kilobytes to megabytes */
4864 4865 4866 4867 4868 4869 4870
        }
    }

    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
4871
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4872
                                    &taskInfoErrorMessage) < 0) {
4873 4874 4875 4876
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4877 4878 4879
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not change memory parameters: %s"),
                  taskInfoErrorMessage);
4880 4881 4882 4883 4884 4885 4886 4887 4888
        goto cleanup;
    }

    result = 0;

  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
4889
    VIR_FREE(taskInfoErrorMessage);
4890 4891 4892 4893 4894 4895 4896

    return result;
}



static int
4897
esxDomainGetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926
                             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 (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;
    }

4927 4928 4929 4930
    /* Scale from megabytes to kilobytes */
    if (virTypedParameterAssign(params, VIR_DOMAIN_MEMORY_MIN_GUARANTEE,
                                VIR_TYPED_PARAM_ULLONG,
                                reservation->value * 1024) < 0)
4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945
        goto cleanup;

    *nparams = 1;
    result = 0;

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

    return result;
}



4946
static virDriver esxDriver = {
4947 4948
    .no = VIR_DRV_ESX,
    .name = "ESX",
4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964
    .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 */
4965
    .domainShutdownFlags = esxDomainShutdownFlags, /* 0.9.10 */
4966 4967
    .domainReboot = esxDomainReboot, /* 0.7.0 */
    .domainDestroy = esxDomainDestroy, /* 0.7.0 */
4968
    .domainDestroyFlags = esxDomainDestroyFlags, /* 0.9.4 */
4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989
    .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 */
4990
    .domainUndefineFlags = esxDomainUndefineFlags, /* 0.9.4 */
4991 4992 4993 4994
    .domainGetAutostart = esxDomainGetAutostart, /* 0.9.0 */
    .domainSetAutostart = esxDomainSetAutostart, /* 0.9.0 */
    .domainGetSchedulerType = esxDomainGetSchedulerType, /* 0.7.0 */
    .domainGetSchedulerParameters = esxDomainGetSchedulerParameters, /* 0.7.0 */
4995
    .domainGetSchedulerParametersFlags = esxDomainGetSchedulerParametersFlags, /* 0.9.2 */
4996
    .domainSetSchedulerParameters = esxDomainSetSchedulerParameters, /* 0.7.0 */
4997
    .domainSetSchedulerParametersFlags = esxDomainSetSchedulerParametersFlags, /* 0.9.2 */
4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010
    .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 */
5011 5012
    .domainSnapshotNumChildren = esxDomainSnapshotNumChildren, /* 0.9.7 */
    .domainSnapshotListChildrenNames = esxDomainSnapshotListChildrenNames, /* 0.9.7 */
5013 5014
    .domainSnapshotLookupByName = esxDomainSnapshotLookupByName, /* 0.8.0 */
    .domainHasCurrentSnapshot = esxDomainHasCurrentSnapshot, /* 0.8.0 */
E
Eric Blake 已提交
5015
    .domainSnapshotGetParent = esxDomainSnapshotGetParent, /* 0.9.7 */
5016 5017 5018
    .domainSnapshotCurrent = esxDomainSnapshotCurrent, /* 0.8.0 */
    .domainRevertToSnapshot = esxDomainRevertToSnapshot, /* 0.8.0 */
    .domainSnapshotDelete = esxDomainSnapshotDelete, /* 0.8.0 */
5019
    .isAlive = esxIsAlive, /* 0.9.8 */
5020 5021 5022 5023 5024 5025 5026
};



int
esxRegister(void)
{
5027 5028 5029 5030 5031
    if (virRegisterDriver(&esxDriver) < 0 ||
        esxInterfaceRegister() < 0 ||
        esxNetworkRegister() < 0 ||
        esxStorageRegister() < 0 ||
        esxDeviceRegister() < 0 ||
M
Matthias Bolte 已提交
5032 5033
        esxSecretRegister() < 0 ||
        esxNWFilterRegister() < 0) {
5034 5035
        return -1;
    }
5036 5037 5038

    return 0;
}