esx_driver.c 137.9 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 Red Hat, Inc.
6
 * Copyright (C) 2009-2010 Matthias Bolte <matthias.bolte@googlemail.com>
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
 * Copyright (C) 2009 Maximilian Wilhelm <max@rfc2324.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 */

#include <config.h>

#include "internal.h"
#include "domain_conf.h"
29
#include "authhelper.h"
30 31 32 33 34
#include "util.h"
#include "memory.h"
#include "logging.h"
#include "uuid.h"
#include "esx_driver.h"
35 36 37 38 39
#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 已提交
40
#include "esx_nwfilter_driver.h"
41
#include "esx_private.h"
42 43 44 45 46 47 48 49 50
#include "esx_vi.h"
#include "esx_vi_methods.h"
#include "esx_util.h"
#include "esx_vmx.h"

#define VIR_FROM_THIS VIR_FROM_ESX

static int esxDomainGetMaxVcpus(virDomainPtr domain);

51 52 53 54 55 56 57 58 59 60
typedef struct _esxVMX_Data esxVMX_Data;

struct _esxVMX_Data {
    esxVI_Context *ctx;
    const char *datastoreName;
    const char *directoryName;
};



61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
/*
 * Parse a file name from a .vmx file and convert it to datastore path format.
 * A .vmx file can contain file names in various formats:
 *
 * - A single name referencing a file in the same directory as the .vmx file:
 *
 *     test1.vmdk
 *
 * - An absolute file name referencing a file in a datastore that is mounted at
 *   /vmfs/volumes/<datastore>:
 *
 *     /vmfs/volumes/b24b7a78-9d82b4f5/test1/test1.vmdk
 *     /vmfs/volumes/datastore1/test1/test1.vmdk
 *
 *   The actual mount directory is /vmfs/volumes/b24b7a78-9d82b4f5, the second
 *   form is a symlink to it using the datastore name. This is the typical
 *   setup on an ESX(i) server.
 *
 * - With GSX installed on Windows there are also Windows style file names
 *   including UNC file names:
 *
 *     C:\Virtual Machines\test1\test1.vmdk
 *     \\nas1\storage1\test1\test1.vmdk
 *
 * The datastore path format typically looks like this:
 *
 *  [datastore1] test1/test1.vmdk
 *
 * Firstly this functions checks if the given file name contains a separator.
 * If it doesn't then the referenced file is in the same directory as the .vmx
 * file. The datastore name and directory of the .vmx file are passed to this
 * function via the opaque paramater by the caller of esxVMX_ParseConfig.
 *
 * 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.
 */
102
static char *
103
esxParseVMXFileName(const char *fileName, void *opaque)
104
{
105 106
    char *datastorePath = NULL;
    esxVMX_Data *data = opaque;
107
    esxVI_String *propertyNameList = NULL;
108
    esxVI_ObjectContent *datastoreList = NULL;
109
    esxVI_ObjectContent *datastore = NULL;
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    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 */
        if (virAsprintf(&datastorePath, "[%s] %s/%s", data->datastoreName,
                        data->directoryName, fileName) < 0) {
            virReportOOMError();
            goto cleanup;
        }
    } else {
        if (esxVI_String_AppendValueToList(&propertyNameList,
                                           "summary.name") < 0 ||
            esxVI_LookupDatastoreList(data->ctx, propertyNameList,
                                      &datastoreList) < 0) {
            return NULL;
        }
132

133 134 135 136 137
        /* Search for datastore by mount path */
        for (datastore = datastoreList; datastore != NULL;
             datastore = datastore->_next) {
            esxVI_DatastoreHostMount_Free(&hostMount);
            datastoreName = NULL;
138

139 140 141 142 143 144
            if (esxVI_LookupDatastoreHostMount(data->ctx, datastore->obj,
                                               &hostMount) < 0 ||
                esxVI_GetStringValue(datastore, "summary.name", &datastoreName,
                                     esxVI_Occurrence_RequiredItem) < 0) {
                goto cleanup;
            }
145

146
            tmp = (char *)STRSKIP(fileName, hostMount->mountInfo->path);
147

148 149 150
            if (tmp == NULL) {
                continue;
            }
151

152 153 154 155
            /* Found a match. Strip leading separators */
            while (*tmp == '/' || *tmp == '\\') {
                ++tmp;
            }
156

157 158 159
            if (esxVI_String_DeepCopyValue(&strippedFileName, tmp) < 0) {
                goto cleanup;
            }
160

161
            tmp = strippedFileName;
162

163 164 165 166 167
            /* Convert \ to / */
            while (*tmp != '\0') {
                if (*tmp == '\\') {
                    *tmp = '/';
                }
168

169 170
                ++tmp;
            }
171

172 173 174 175 176
            if (virAsprintf(&datastorePath, "[%s] %s", datastoreName,
                            strippedFileName) < 0) {
                virReportOOMError();
                goto cleanup;
            }
177

178 179
            break;
        }
180

181 182 183 184 185
        /* Fallback to direct datastore name match */
        if (datastorePath == NULL && STRPREFIX(fileName, "/vmfs/volumes/")) {
            if (esxVI_String_DeepCopyValue(&copyOfFileName, fileName) < 0) {
                goto cleanup;
            }
186

187 188 189 190 191 192 193 194 195
            /* 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;
            }
196

197
            esxVI_ObjectContent_Free(&datastoreList);
198

199 200 201 202 203
            if (esxVI_LookupDatastoreByName(data->ctx, datastoreName,
                                            NULL, &datastoreList,
                                            esxVI_Occurrence_OptionalItem) < 0) {
                goto cleanup;
            }
204

205 206 207 208 209 210
            if (datastoreList == NULL) {
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                          _("File name '%s' refers to non-existing datastore '%s'"),
                          fileName, datastoreName);
                goto cleanup;
            }
211

212 213 214 215 216
            if (virAsprintf(&datastorePath, "[%s] %s", datastoreName,
                            directoryAndFileName) < 0) {
                virReportOOMError();
                goto cleanup;
            }
217 218
        }

219 220 221 222
        if (datastorePath == NULL) {
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                      _("Could not find datastore for '%s'"), fileName);
            goto cleanup;
223
        }
224
    }
225

226 227 228 229 230 231
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&datastoreList);
    esxVI_DatastoreHostMount_Free(&hostMount);
    VIR_FREE(strippedFileName);
    VIR_FREE(copyOfFileName);
232

233
    return datastorePath;
234 235 236 237
}



238 239 240 241 242 243 244 245 246 247 248 249 250
/*
 * This function does the inverse of esxParseVMXFileName. It takes an file name
 * in datastore path format and converts it to a file name that can be used in
 * a .vmx file.
 *
 * The datastore path format and the formats found in a .vmx file are described
 * in the documentation of esxParseVMXFileName.
 *
 * Firstly parse the datastore path. Then use the datastore name to lookup the
 * datastore and it's mount path. Finally concatenate the mount path, directory
 * and file name to an absolute path and return it. Detect the seperator type
 * based on the mount path.
 */
251
static char *
252
esxFormatVMXFileName(const char *datastorePath, void *opaque)
253 254
{
    bool success = false;
255
    esxVMX_Data *data = opaque;
256 257 258
    char *datastoreName = NULL;
    char *directoryName = NULL;
    char *fileName = NULL;
259 260 261 262 263 264
    esxVI_ObjectContent *datastore = NULL;
    esxVI_DatastoreHostMount *hostMount = NULL;
    char separator = '/';
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    char *tmp;
    int length;
265 266
    char *absolutePath = NULL;

267 268 269 270 271
    /* Parse datastore path and lookup datastore */
    if (esxUtil_ParseDatastorePath(datastorePath, &datastoreName,
                                   &directoryName, &fileName) < 0) {
        goto cleanup;
    }
272

273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
    if (esxVI_LookupDatastoreByName(data->ctx, datastoreName,
                                    NULL, &datastore,
                                    esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_LookupDatastoreHostMount(data->ctx, datastore->obj,
                                       &hostMount) < 0) {
        goto cleanup;
    }

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

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

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

    /* Format as <mount>[/<directory>]/<file> */
    virBufferAdd(&buffer, hostMount->mountInfo->path, length);

    if (directoryName != NULL) {
        /* Convert / to \ when necessary */
        if (separator != '/') {
            tmp = directoryName;

            while (*tmp != '\0') {
                if (*tmp == '/') {
                    *tmp = separator;
                }

                ++tmp;
307 308 309
            }
        }

310 311 312 313 314 315 316 317 318
        virBufferAddChar(&buffer, separator);
        virBufferAdd(&buffer, directoryName, -1);
    }

    virBufferAddChar(&buffer, separator);
    virBufferAdd(&buffer, fileName, -1);

    if (virBufferError(&buffer)) {
        virReportOOMError();
319 320 321
        goto cleanup;
    }

322 323
    absolutePath = virBufferContentAndReset(&buffer);

324 325 326 327 328 329
    /* FIXME: Check if referenced path/file really exists */

    success = true;

  cleanup:
    if (! success) {
330
        virBufferFreeAndReset(&buffer);
331 332 333 334 335 336
        VIR_FREE(absolutePath);
    }

    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
    VIR_FREE(fileName);
337 338
    esxVI_ObjectContent_Free(&datastore);
    esxVI_DatastoreHostMount_Free(&hostMount);
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507

    return absolutePath;
}



static int
esxAutodetectSCSIControllerModel(virDomainDiskDefPtr def, int *model,
                                 void *opaque)
{
    int result = -1;
    esxVMX_Data *data = opaque;
    char *datastoreName = NULL;
    char *directoryName = NULL;
    char *fileName = NULL;
    char *datastorePath = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *datastore = NULL;
    esxVI_ManagedObjectReference *hostDatastoreBrowser = NULL;
    esxVI_HostDatastoreBrowserSearchSpec *searchSpec = NULL;
    esxVI_VmDiskFileQuery *vmDiskFileQuery = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
    esxVI_TaskInfo *taskInfo = NULL;
    esxVI_HostDatastoreBrowserSearchResults *searchResults = NULL;
    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;
    }

    if (esxUtil_ParseDatastorePath(def->src, &datastoreName, &directoryName,
                                   &fileName) < 0) {
        goto cleanup;
    }

    if (directoryName == NULL) {
        if (virAsprintf(&datastorePath, "[%s]", datastoreName) < 0) {
            virReportOOMError();
            goto cleanup;
        }
    } else {
        if (virAsprintf(&datastorePath, "[%s] %s", datastoreName,
                        directoryName) < 0) {
            virReportOOMError();
            goto cleanup;
        }
    }

    /* Lookup HostDatastoreBrowser */
    if (esxVI_String_AppendValueToList(&propertyNameList, "browser") < 0 ||
        esxVI_LookupDatastoreByName(data->ctx, datastoreName, propertyNameList,
                                    &datastore,
                                    esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_GetManagedObjectReference(datastore, "browser",
                                        &hostDatastoreBrowser,
                                        esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    /* Build HostDatastoreBrowserSearchSpec */
    if (esxVI_HostDatastoreBrowserSearchSpec_Alloc(&searchSpec) < 0 ||
        esxVI_FileQueryFlags_Alloc(&searchSpec->details) < 0) {
        goto cleanup;
    }

    searchSpec->details->fileType = esxVI_Boolean_True;
    searchSpec->details->fileSize = esxVI_Boolean_False;
    searchSpec->details->modification = esxVI_Boolean_False;

    if (esxVI_VmDiskFileQuery_Alloc(&vmDiskFileQuery) < 0 ||
        esxVI_VmDiskFileQueryFlags_Alloc(&vmDiskFileQuery->details) < 0 ||
        esxVI_FileQuery_AppendToList
          (&searchSpec->query,
           esxVI_FileQuery_DynamicCast(vmDiskFileQuery)) < 0) {
        goto cleanup;
    }

    vmDiskFileQuery->details->diskType = esxVI_Boolean_False;
    vmDiskFileQuery->details->capacityKb = esxVI_Boolean_False;
    vmDiskFileQuery->details->hardwareVersion = esxVI_Boolean_False;
    vmDiskFileQuery->details->controllerType = esxVI_Boolean_True;
    vmDiskFileQuery->details->diskExtents = esxVI_Boolean_False;

    if (esxVI_String_Alloc(&searchSpec->matchPattern) < 0) {
        goto cleanup;
    }

    searchSpec->matchPattern->value = fileName;

    /* Search datastore for file */
    if (esxVI_SearchDatastore_Task(data->ctx, hostDatastoreBrowser,
                                   datastorePath, searchSpec, &task) < 0 ||
        esxVI_WaitForTaskCompletion(data->ctx, task, NULL, esxVI_Occurrence_None,
                                    esxVI_Boolean_False, &taskInfoState) < 0) {
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not serach in datastore '%s'"), datastoreName);
        goto cleanup;
    }

    if (esxVI_LookupTaskInfoByTask(data->ctx, task, &taskInfo) < 0 ||
        esxVI_HostDatastoreBrowserSearchResults_CastFromAnyType
          (taskInfo->result, &searchResults) < 0) {
        goto cleanup;
    }

    /* Interpret search result */
    vmDiskFileInfo = esxVI_VmDiskFileInfo_DynamicCast(searchResults->file);

    if (vmDiskFileInfo == NULL || vmDiskFileInfo->controllerType == NULL) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not lookup controller model for '%s'"), def->src);
        goto cleanup;
    }

    if (STRCASEEQ(vmDiskFileInfo->controllerType,
                  "VirtualBusLogicController")) {
        *model = VIR_DOMAIN_CONTROLLER_MODEL_BUSLOGIC;
    } else if (STRCASEEQ(vmDiskFileInfo->controllerType,
                         "VirtualLsiLogicController")) {
        *model = VIR_DOMAIN_CONTROLLER_MODEL_LSILOGIC;
    } else if (STRCASEEQ(vmDiskFileInfo->controllerType,
                         "VirtualLsiLogicSASController")) {
        *model = VIR_DOMAIN_CONTROLLER_MODEL_LSISAS1068;
    } else if (STRCASEEQ(vmDiskFileInfo->controllerType,
                         "ParaVirtualSCSIController")) {
        *model = VIR_DOMAIN_CONTROLLER_MODEL_VMPVSCSI;
    } else {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Found unexpected controller model '%s' for disk '%s'"),
                  vmDiskFileInfo->controllerType, def->src);
        goto cleanup;
    }

    result = 0;

  cleanup:
    /* Don't double free fileName */
    if (searchSpec != NULL && searchSpec->matchPattern != NULL) {
        searchSpec->matchPattern->value = NULL;
    }

    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
    VIR_FREE(fileName);
    VIR_FREE(datastorePath);
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&datastore);
    esxVI_ManagedObjectReference_Free(&hostDatastoreBrowser);
    esxVI_HostDatastoreBrowserSearchSpec_Free(&searchSpec);
    esxVI_ManagedObjectReference_Free(&task);
    esxVI_TaskInfo_Free(&taskInfo);
    esxVI_HostDatastoreBrowserSearchResults_Free(&searchResults);

    return result;
}

508 509


510
static esxVI_Boolean
511
esxSupportsLongMode(esxPrivate *priv)
512 513 514 515 516 517
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_HostCpuIdInfo *hostCpuIdInfoList = NULL;
    esxVI_HostCpuIdInfo *hostCpuIdInfo = NULL;
518
    esxVI_ParsedHostCpuIdInfo parsedHostCpuIdInfo;
519 520 521 522 523 524
    char edxLongModeBit = '?';

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

525
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
526
        return esxVI_Boolean_Undefined;
527 528
    }

529
    if (esxVI_String_AppendValueToList(&propertyNameList,
530
                                       "hardware.cpuFeature") < 0 ||
531 532
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
533
        goto cleanup;
534 535 536
    }

    if (hostSystem == NULL) {
537 538
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
539
        goto cleanup;
540 541 542 543 544 545
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuFeature")) {
            if (esxVI_HostCpuIdInfo_CastListFromAnyType
546
                  (dynamicProperty->val, &hostCpuIdInfoList) < 0) {
M
Matthias Bolte 已提交
547
                goto cleanup;
548 549 550 551 552
            }

            for (hostCpuIdInfo = hostCpuIdInfoList; hostCpuIdInfo != NULL;
                 hostCpuIdInfo = hostCpuIdInfo->_next) {
                if (hostCpuIdInfo->level->value == -2147483647) { /* 0x80000001 */
553 554
                    if (esxVI_ParseHostCpuIdInfo(&parsedHostCpuIdInfo,
                                                 hostCpuIdInfo) < 0) {
M
Matthias Bolte 已提交
555
                        goto cleanup;
556 557
                    }

558
                    edxLongModeBit = parsedHostCpuIdInfo.edx[29];
559 560 561 562 563 564

                    if (edxLongModeBit == '1') {
                        priv->supportsLongMode = esxVI_Boolean_True;
                    } else if (edxLongModeBit == '0') {
                        priv->supportsLongMode = esxVI_Boolean_False;
                    } else {
565
                        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
566 567 568 569
                                  _("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 已提交
570
                        goto cleanup;
571 572 573 574 575 576 577 578 579 580 581 582 583
                    }

                    break;
                }
            }

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

  cleanup:
M
Matthias Bolte 已提交
584 585 586 587
    /*
     * 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.
     */
588 589 590 591 592 593 594 595 596
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_HostCpuIdInfo_Free(&hostCpuIdInfoList);

    return priv->supportsLongMode;
}



597 598 599 600 601 602 603 604
static int
esxLookupHostSystemBiosUuid(esxPrivate *priv, unsigned char *uuid)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

605
    if (esxVI_EnsureSession(priv->primary) < 0) {
606 607 608 609 610
        return -1;
    }

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "hardware.systemInfo.uuid") < 0 ||
611 612
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
        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) {
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                              _("Could not parse UUID from string '%s'"),
                              dynamicProperty->val->string);
                    goto cleanup;
                }
            } 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;
}



659
static virCapsPtr
660
esxCapsInit(esxPrivate *priv)
661
{
662
    esxVI_Boolean supportsLongMode = esxSupportsLongMode(priv);
663 664 665
    virCapsPtr caps = NULL;
    virCapsGuestPtr guest = NULL;

666 667 668 669 670 671 672 673 674
    if (supportsLongMode == esxVI_Boolean_Undefined) {
        return NULL;
    }

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

    if (caps == NULL) {
677
        virReportOOMError();
678 679 680
        return NULL;
    }

681
    virCapabilitiesSetMacPrefix(caps, (unsigned char[]){ 0x00, 0x0c, 0x29 });
682
    virCapabilitiesAddHostMigrateTransport(caps, "vpxmigr");
683

684 685
    caps->hasWideScsiBus = true;

686 687 688 689
    if (esxLookupHostSystemBiosUuid(priv, caps->host.host_uuid) < 0) {
        goto failure;
    }

690 691 692
    /* i686 */
    guest = virCapabilitiesAddGuest(caps, "hvm", "i686", 32, NULL, NULL, 0,
                                    NULL);
693 694 695 696 697 698 699 700 701 702 703 704 705 706

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

    /*
     * FIXME: Maybe distinguish betwen ESX and GSX here, see
     * esxVMX_ParseConfig() and VIR_DOMAIN_VIRT_VMWARE
     */
    if (virCapabilitiesAddGuestDomain(guest, "vmware", NULL, NULL, 0,
                                      NULL) == NULL) {
        goto failure;
    }

707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
    /* x86_64 */
    if (supportsLongMode == esxVI_Boolean_True) {
        guest = virCapabilitiesAddGuest(caps, "hvm", "x86_64", 64, NULL, NULL,
                                        0, NULL);

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

        /*
         * FIXME: Maybe distinguish betwen ESX and GSX here, see
         * esxVMX_ParseConfig() and VIR_DOMAIN_VIRT_VMWARE
         */
        if (virCapabilitiesAddGuestDomain(guest, "vmware", NULL, NULL, 0,
                                          NULL) == NULL) {
            goto failure;
        }
    }

726 727 728 729 730 731 732 733 734 735
    return caps;

  failure:
    virCapabilitiesFree(caps);

    return NULL;
}



736 737 738 739
static int
esxConnectToHost(esxPrivate *priv, virConnectAuthPtr auth,
                 const char *hostname, int port,
                 const char *predefinedUsername,
M
Matthias Bolte 已提交
740
                 esxUtil_ParsedUri *parsedUri,
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
                 esxVI_ProductVersion expectedProductVersion,
                 char **vCenterIpAddress)
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
    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;
        }
    }

    password = virRequestPassword(auth, username, hostname);

    if (password == NULL) {
        ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
        goto cleanup;
    }

    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->transport, hostname,
                    port) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    if (esxVI_Context_Alloc(&priv->host) < 0 ||
        esxVI_Context_Connect(priv->host, url, ipAddress, username, password,
793 794
                              parsedUri) < 0 ||
        esxVI_Context_LookupObjectsByPath(priv->host, parsedUri) < 0) {
795 796 797 798 799
        goto cleanup;
    }

    if (expectedProductVersion == esxVI_ProductVersion_ESX) {
        if (priv->host->productVersion != esxVI_ProductVersion_ESX35 &&
M
Matthias Bolte 已提交
800 801 802
            priv->host->productVersion != esxVI_ProductVersion_ESX40 &&
            priv->host->productVersion != esxVI_ProductVersion_ESX41 &&
            priv->host->productVersion != esxVI_ProductVersion_ESX4x) {
803
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
M
Matthias Bolte 已提交
804
                      _("%s is neither an ESX 3.5 host nor an ESX 4.x host"),
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
                      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 ||
820 821
        esxVI_LookupHostSystemProperties(priv->host, propertyNameList,
                                         &hostSystem) < 0 ||
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
        esxVI_GetBoolean(hostSystem, "runtime.inMaintenanceMode",
                         &inMaintenanceMode,
                         esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_GetStringValue(hostSystem, "summary.managementServerIp",
                             vCenterIpAddress,
                             esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
    }

    /* Warn if host is in maintenance mode */
    if (inMaintenanceMode == esxVI_Boolean_True) {
        VIR_WARN0("The server is in maintenance mode");
    }

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

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

    result = 0;

  cleanup:
    VIR_FREE(password);
    VIR_FREE(username);
    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,
863
                    const char *hostSystemIpAddress,
M
Matthias Bolte 已提交
864
                    esxUtil_ParsedUri *parsedUri)
865 866 867 868 869 870 871
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
    char *password = NULL;
    char *url = NULL;

872 873 874 875 876 877 878 879
    if (hostSystemIpAddress == NULL &&
        (parsedUri->path_datacenter == NULL ||
         parsedUri->path_computeResource == NULL)) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Path has to specify the datacenter and compute resource"));
        return -1;
    }

880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
    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;
        }
    }

    password = virRequestPassword(auth, username, hostname);

    if (password == NULL) {
        ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
        goto cleanup;
    }

    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->transport, hostname,
                    port) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    if (esxVI_Context_Alloc(&priv->vCenter) < 0 ||
        esxVI_Context_Connect(priv->vCenter, url, ipAddress, username,
M
Matthias Bolte 已提交
915
                              password, parsedUri) < 0) {
916 917 918 919
        goto cleanup;
    }

    if (priv->vCenter->productVersion != esxVI_ProductVersion_VPX25 &&
M
Matthias Bolte 已提交
920 921 922
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX40 &&
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX41 &&
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX4x) {
923 924
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("%s is neither a vCenter 2.5 server nor a vCenter "
M
Matthias Bolte 已提交
925
                    "4.x server"), hostname);
926 927 928
        goto cleanup;
    }

929 930 931 932 933 934 935 936 937 938 939
    if (hostSystemIpAddress != NULL) {
        if (esxVI_Context_LookupObjectsByHostSystemIp(priv->vCenter,
                                                      hostSystemIpAddress) < 0) {
            goto cleanup;
        }
    } else {
        if (esxVI_Context_LookupObjectsByPath(priv->vCenter, parsedUri) < 0) {
            goto cleanup;
        }
    }

940 941 942 943 944 945 946 947 948 949 950 951
    result = 0;

  cleanup:
    VIR_FREE(password);
    VIR_FREE(username);
    VIR_FREE(url);

    return result;
}



952
/*
953 954
 * URI format: {vpx|esx|gsx}://[<username>@]<hostname>[:<port>]/[<path>][?<query parameter> ...]
 *             <path> = <datacenter>/<computeresource>[/<hostsystem>]
955
 *
956 957
 * If no port is specified the default port is set dependent on the scheme and
 * transport parameter:
958 959
 * - vpx+http  80
 * - vpx+https 443
960
 * - esx+http  80
961
 * - esx+https 443
962 963 964
 * - gsx+http  8222
 * - gsx+https 8333
 *
965 966 967 968 969
 * For a vpx:// connection <path> references a host managed by the vCenter.
 * In case the host is part of a cluster then <computeresource> is the cluster
 * name. Otherwise <computeresource> and <hostsystem> are equal and the later
 * can be omitted.
 *
970 971
 * Optional query parameters:
 * - transport={http|https}
972
 * - vcenter={<vcenter>|*}             only useful for an esx:// connection
973 974
 * - no_verify={0|1}
 * - auto_answer={0|1}
M
Matthias Bolte 已提交
975
 * - proxy=[{http|socks|socks4|socks4a|socks5}://]<hostname>[:<port>]
976
 *
977 978 979
 * If no transport parameter is specified https is used.
 *
 * The vcenter parameter is only necessary for migration, because the vCenter
980
 * server is in charge to initiate a migration between two ESX hosts. The
981
 * vcenter parameter can be set to an explicitly hostname or to *. If set to *,
982 983
 * 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.
984 985
 *
 * If the no_verify parameter is set to 1, this disables libcurl client checks
986
 * of the server's certificate. The default value it 0.
987 988 989 990
 *
 * 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 已提交
991 992 993 994
 *
 * 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.
995 996 997 998
 */
static virDrvOpenStatus
esxOpen(virConnectPtr conn, virConnectAuthPtr auth, int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
999
    virDrvOpenStatus result = VIR_DRV_OPEN_ERROR;
1000
    esxPrivate *priv = NULL;
M
Matthias Bolte 已提交
1001
    esxUtil_ParsedUri *parsedUri = NULL;
1002
    char *potentialVCenterIpAddress = NULL;
M
Matthias Bolte 已提交
1003
    char vCenterIpAddress[NI_MAXHOST] = "";
1004

1005
    /* Decline if the URI is NULL or the scheme is not one of {vpx|esx|gsx} */
1006
    if (conn->uri == NULL || conn->uri->scheme == NULL ||
1007 1008
        (STRCASENEQ(conn->uri->scheme, "vpx") &&
         STRCASENEQ(conn->uri->scheme, "esx") &&
1009
         STRCASENEQ(conn->uri->scheme, "gsx"))) {
1010 1011 1012
        return VIR_DRV_OPEN_DECLINED;
    }

M
Matthias Bolte 已提交
1013 1014 1015
    /* Decline URIs without server part, or missing auth */
    if (conn->uri->server == NULL || auth == NULL || auth->cb == NULL) {
        return VIR_DRV_OPEN_DECLINED;
1016 1017 1018 1019
    }

    /* Allocate per-connection private data */
    if (VIR_ALLOC(priv) < 0) {
1020
        virReportOOMError();
M
Matthias Bolte 已提交
1021
        goto cleanup;
1022 1023
    }

M
Matthias Bolte 已提交
1024
    if (esxUtil_ParseUri(&parsedUri, conn->uri) < 0) {
1025 1026 1027
        goto cleanup;
    }

M
Matthias Bolte 已提交
1028 1029
    priv->transport = parsedUri->transport;
    parsedUri->transport = NULL;
1030

M
Matthias Bolte 已提交
1031 1032
    priv->maxVcpus = -1;
    priv->supportsVMotion = esxVI_Boolean_Undefined;
1033
    priv->supportsLongMode = esxVI_Boolean_Undefined;
M
Matthias Bolte 已提交
1034 1035
    priv->autoAnswer = parsedUri->autoAnswer ? esxVI_Boolean_True
                                             : esxVI_Boolean_False;
1036 1037
    priv->usedCpuTimeCounterId = -1;

M
Matthias Bolte 已提交
1038 1039 1040 1041 1042 1043 1044
    /*
     * 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) {
1045 1046
        if (STRCASEEQ(conn->uri->scheme, "vpx") ||
            STRCASEEQ(conn->uri->scheme, "esx")) {
M
Matthias Bolte 已提交
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
            if (STRCASEEQ(priv->transport, "https")) {
                conn->uri->port = 443;
            } else {
                conn->uri->port = 80;
            }
        } else { /* GSX */
            if (STRCASEEQ(priv->transport, "https")) {
                conn->uri->port = 8333;
            } else {
                conn->uri->port = 8222;
            }
1058
        }
M
Matthias Bolte 已提交
1059
    }
1060

1061 1062 1063 1064
    if (STRCASEEQ(conn->uri->scheme, "esx") ||
        STRCASEEQ(conn->uri->scheme, "gsx")) {
        /* Connect to host */
        if (esxConnectToHost(priv, auth, conn->uri->server, conn->uri->port,
M
Matthias Bolte 已提交
1065
                             conn->uri->user, parsedUri,
1066 1067 1068 1069
                             STRCASEEQ(conn->uri->scheme, "esx")
                               ? esxVI_ProductVersion_ESX
                               : esxVI_ProductVersion_GSX,
                             &potentialVCenterIpAddress) < 0) {
M
Matthias Bolte 已提交
1070
            goto cleanup;
1071
        }
1072

1073
        /* Connect to vCenter */
M
Matthias Bolte 已提交
1074 1075
        if (parsedUri->vCenter != NULL) {
            if (STREQ(parsedUri->vCenter, "*")) {
1076 1077 1078
                if (potentialVCenterIpAddress == NULL) {
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                              _("This host is not managed by a vCenter"));
M
Matthias Bolte 已提交
1079
                    goto cleanup;
1080 1081
                }

1082 1083 1084 1085 1086 1087 1088 1089
                if (virStrcpyStatic(vCenterIpAddress,
                                    potentialVCenterIpAddress) == NULL) {
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                              _("vCenter IP address %s too big for destination"),
                              potentialVCenterIpAddress);
                    goto cleanup;
                }
            } else {
M
Matthias Bolte 已提交
1090
                if (esxUtil_ResolveHostname(parsedUri->vCenter,
1091 1092 1093
                                            vCenterIpAddress, NI_MAXHOST) < 0) {
                    goto cleanup;
                }
1094

1095 1096
                if (potentialVCenterIpAddress != NULL &&
                    STRNEQ(vCenterIpAddress, potentialVCenterIpAddress)) {
1097
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1098 1099 1100
                              _("This host is managed by a vCenter with IP "
                                "address %s, but a mismachting vCenter '%s' "
                                "(%s) has been specified"),
M
Matthias Bolte 已提交
1101
                              potentialVCenterIpAddress, parsedUri->vCenter,
1102
                              vCenterIpAddress);
M
Matthias Bolte 已提交
1103
                    goto cleanup;
1104 1105
                }
            }
1106

1107
            if (esxConnectToVCenter(priv, auth, vCenterIpAddress,
1108 1109
                                    conn->uri->port, NULL,
                                    priv->host->ipAddress, parsedUri) < 0) {
1110 1111
                goto cleanup;
            }
1112 1113
        }

1114 1115 1116 1117
        priv->primary = priv->host;
    } else { /* VPX */
        /* Connect to vCenter */
        if (esxConnectToVCenter(priv, auth, conn->uri->server, conn->uri->port,
1118
                                conn->uri->user, NULL, parsedUri) < 0) {
M
Matthias Bolte 已提交
1119
            goto cleanup;
1120 1121
        }

1122
        priv->primary = priv->vCenter;
1123 1124 1125
    }

    conn->privateData = priv;
1126

M
Matthias Bolte 已提交
1127
    /* Setup capabilities */
1128
    priv->caps = esxCapsInit(priv);
1129

M
Matthias Bolte 已提交
1130
    if (priv->caps == NULL) {
M
Matthias Bolte 已提交
1131
        goto cleanup;
1132 1133
    }

M
Matthias Bolte 已提交
1134
    result = VIR_DRV_OPEN_SUCCESS;
1135

M
Matthias Bolte 已提交
1136 1137
  cleanup:
    if (result == VIR_DRV_OPEN_ERROR && priv != NULL) {
1138
        esxVI_Context_Free(&priv->host);
M
Matthias Bolte 已提交
1139
        esxVI_Context_Free(&priv->vCenter);
1140

1141 1142
        virCapabilitiesFree(priv->caps);

M
Matthias Bolte 已提交
1143
        VIR_FREE(priv->transport);
1144 1145 1146
        VIR_FREE(priv);
    }

M
Matthias Bolte 已提交
1147
    esxUtil_FreeParsedUri(&parsedUri);
1148
    VIR_FREE(potentialVCenterIpAddress);
1149

M
Matthias Bolte 已提交
1150
    return result;
1151 1152 1153 1154 1155 1156 1157
}



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

1161 1162 1163 1164 1165
    if (priv->host != NULL) {
        if (esxVI_EnsureSession(priv->host) < 0 ||
            esxVI_Logout(priv->host) < 0) {
            result = -1;
        }
1166

1167 1168
        esxVI_Context_Free(&priv->host);
    }
1169

M
Matthias Bolte 已提交
1170
    if (priv->vCenter != NULL) {
E
Eric Blake 已提交
1171 1172 1173 1174
        if (esxVI_EnsureSession(priv->vCenter) < 0 ||
            esxVI_Logout(priv->vCenter) < 0) {
            result = -1;
        }
1175

M
Matthias Bolte 已提交
1176
        esxVI_Context_Free(&priv->vCenter);
1177 1178
    }

1179 1180
    virCapabilitiesFree(priv->caps);

1181 1182 1183 1184 1185
    VIR_FREE(priv->transport);
    VIR_FREE(priv);

    conn->privateData = NULL;

E
Eric Blake 已提交
1186
    return result;
1187 1188 1189 1190 1191
}



static esxVI_Boolean
1192
esxSupportsVMotion(esxPrivate *priv)
1193 1194 1195 1196
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;

M
Matthias Bolte 已提交
1197 1198
    if (priv->supportsVMotion != esxVI_Boolean_Undefined) {
        return priv->supportsVMotion;
1199 1200
    }

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

1205
    if (esxVI_String_AppendValueToList(&propertyNameList,
1206
                                       "capability.vmotionSupported") < 0 ||
1207 1208
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1209
        goto cleanup;
1210 1211 1212
    }

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

1218 1219 1220 1221
    if (esxVI_GetBoolean(hostSystem, "capability.vmotionSupported",
                         &priv->supportsVMotion,
                         esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
1222 1223 1224
    }

  cleanup:
M
Matthias Bolte 已提交
1225 1226 1227 1228
    /*
     * 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.
     */
1229 1230 1231
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
1232
    return priv->supportsVMotion;
1233 1234 1235 1236 1237 1238 1239
}



static int
esxSupportsFeature(virConnectPtr conn, int feature)
{
M
Matthias Bolte 已提交
1240
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1241
    esxVI_Boolean supportsVMotion = esxVI_Boolean_Undefined;
1242 1243 1244

    switch (feature) {
      case VIR_DRV_FEATURE_MIGRATION_V1:
1245
        supportsVMotion = esxSupportsVMotion(priv);
1246

M
Matthias Bolte 已提交
1247
        if (supportsVMotion == esxVI_Boolean_Undefined) {
1248 1249 1250
            return -1;
        }

M
Matthias Bolte 已提交
1251 1252 1253
        /* Migration is only possible via a vCenter and if VMotion is enabled */
        return priv->vCenter != NULL &&
               supportsVMotion == esxVI_Boolean_True ? 1 : 0;
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272

      default:
        return 0;
    }
}



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



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

1275
    if (virParseVersionString(priv->primary->service->about->version,
1276 1277
                              version) < 0) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1278
                  _("Could not parse version number from '%s'"),
1279
                  priv->primary->service->about->version);
1280

1281
        return -1;
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
    }

    return 0;
}



static char *
esxGetHostname(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1292
    esxPrivate *priv = conn->privateData;
1293 1294 1295 1296 1297 1298 1299
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    const char *hostName = NULL;
    const char *domainName = NULL;
    char *complete = NULL;

1300
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1301
        return NULL;
1302 1303 1304
    }

    if (esxVI_String_AppendValueListToList
1305
          (&propertyNameList,
1306 1307
           "config.network.dnsConfig.hostName\0"
           "config.network.dnsConfig.domainName\0") < 0 ||
1308 1309
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1310
        goto cleanup;
1311 1312 1313
    }

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

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name,
                  "config.network.dnsConfig.hostName")) {
1323
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1324
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1325
                goto cleanup;
1326 1327 1328 1329 1330
            }

            hostName = dynamicProperty->val->string;
        } else if (STREQ(dynamicProperty->name,
                         "config.network.dnsConfig.domainName")) {
1331
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1332
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1333
                goto cleanup;
1334 1335 1336 1337 1338 1339 1340 1341
            }

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

M
Matthias Bolte 已提交
1342
    if (hostName == NULL || strlen(hostName) < 1) {
1343 1344
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Missing or empty 'hostName' property"));
M
Matthias Bolte 已提交
1345
        goto cleanup;
1346 1347
    }

M
Matthias Bolte 已提交
1348
    if (domainName == NULL || strlen(domainName) < 1) {
1349
        complete = strdup(hostName);
1350

1351
        if (complete == NULL) {
1352
            virReportOOMError();
M
Matthias Bolte 已提交
1353
            goto cleanup;
1354 1355 1356
        }
    } else {
        if (virAsprintf(&complete, "%s.%s", hostName, domainName) < 0) {
1357
            virReportOOMError();
M
Matthias Bolte 已提交
1358
            goto cleanup;
1359
        }
1360 1361 1362
    }

  cleanup:
M
Matthias Bolte 已提交
1363 1364 1365 1366 1367
    /*
     * 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
     */
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return complete;
}



static int
esxNodeGetInfo(virConnectPtr conn, virNodeInfoPtr nodeinfo)
{
M
Matthias Bolte 已提交
1379
    int result = -1;
M
Matthias Bolte 已提交
1380
    esxPrivate *priv = conn->privateData;
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
    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 已提交
1392
    memset(nodeinfo, 0, sizeof (*nodeinfo));
1393

1394
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1395
        return -1;
1396 1397
    }

1398
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1399 1400 1401 1402 1403 1404 1405
                                           "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 ||
1406 1407
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1408
        goto cleanup;
1409 1410 1411
    }

    if (hostSystem == NULL) {
1412 1413
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
1414
        goto cleanup;
1415 1416 1417 1418 1419
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuInfo.hz")) {
1420
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1421
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1422
                goto cleanup;
1423 1424 1425 1426 1427
            }

            cpuInfo_hz = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuCores")) {
1428
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1429
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1430
                goto cleanup;
1431 1432 1433 1434 1435
            }

            cpuInfo_numCpuCores = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuPackages")) {
1436
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1437
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1438
                goto cleanup;
1439 1440 1441 1442 1443
            }

            cpuInfo_numCpuPackages = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuThreads")) {
1444
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1445
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1446
                goto cleanup;
1447 1448 1449 1450
            }

            cpuInfo_numCpuThreads = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name, "hardware.memorySize")) {
1451
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1452
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1453
                goto cleanup;
1454 1455 1456 1457 1458
            }

            memorySize = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.numaInfo.numNodes")) {
1459
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1460
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1461
                goto cleanup;
1462 1463 1464 1465 1466
            }

            numaInfo_numNodes = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "summary.hardware.cpuModel")) {
1467
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1468
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1469
                goto cleanup;
1470 1471 1472 1473 1474 1475
            }

            ptr = dynamicProperty->val->string;

            /* Strip the string to fit more relevant information in 32 chars */
            while (*ptr != '\0') {
M
Matthias Bolte 已提交
1476 1477
                if (STRPREFIX(ptr, "  ")) {
                    memmove(ptr, ptr + 1, strlen(ptr + 1) + 1);
1478
                    continue;
1479
                } else if (STRPREFIX(ptr, "(R)") || STRPREFIX(ptr, "(C)")) {
M
Matthias Bolte 已提交
1480
                    memmove(ptr, ptr + 3, strlen(ptr + 3) + 1);
1481
                    continue;
1482 1483 1484
                } else if (STRPREFIX(ptr, "(TM)")) {
                    memmove(ptr, ptr + 4, strlen(ptr + 4) + 1);
                    continue;
1485 1486 1487 1488 1489
                }

                ++ptr;
            }

C
Chris Lalancette 已提交
1490 1491 1492
            if (virStrncpy(nodeinfo->model, dynamicProperty->val->string,
                           sizeof(nodeinfo->model) - 1,
                           sizeof(nodeinfo->model)) == NULL) {
1493
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1494
                          _("CPU Model %s too long for destination"),
C
Chris Lalancette 已提交
1495
                          dynamicProperty->val->string);
M
Matthias Bolte 已提交
1496
                goto cleanup;
C
Chris Lalancette 已提交
1497
            }
1498 1499 1500 1501 1502 1503 1504
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    nodeinfo->memory = memorySize / 1024; /* Scale from bytes to kilobytes */
    nodeinfo->cpus = cpuInfo_numCpuCores;
1505
    nodeinfo->mhz = cpuInfo_hz / (1000 * 1000); /* Scale from hz to mhz */
1506 1507 1508 1509 1510 1511 1512 1513 1514
    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 已提交
1515 1516
    result = 0;

1517 1518 1519 1520 1521 1522 1523 1524 1525
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



1526 1527 1528
static char *
esxGetCapabilities(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1529
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1530
    char *xml = virCapabilitiesFormatXML(priv->caps);
1531 1532

    if (xml == NULL) {
1533
        virReportOOMError();
1534 1535 1536 1537 1538 1539 1540 1541
        return NULL;
    }

    return xml;
}



1542 1543 1544
static int
esxListDomains(virConnectPtr conn, int *ids, int maxids)
{
M
Matthias Bolte 已提交
1545
    bool success = false;
M
Matthias Bolte 已提交
1546
    esxPrivate *priv = conn->privateData;
1547 1548 1549 1550 1551 1552 1553
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;

    if (ids == NULL || maxids < 0) {
1554 1555
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
1556 1557 1558 1559 1560 1561
    }

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

1562
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1563
        return -1;
1564 1565
    }

1566
    if (esxVI_String_AppendValueToList(&propertyNameList,
1567
                                       "runtime.powerState") < 0 ||
1568 1569
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1570
        goto cleanup;
1571 1572 1573 1574
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
1575
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1576
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1577
            goto cleanup;
1578 1579 1580 1581 1582 1583 1584 1585 1586
        }

        if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

        if (esxUtil_ParseVirtualMachineIDString(virtualMachine->obj->value,
                                                &ids[count]) < 0 ||
            ids[count] <= 0) {
1587
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1588
                      _("Failed to parse positive integer from '%s'"),
1589
                      virtualMachine->obj->value);
M
Matthias Bolte 已提交
1590
            goto cleanup;
1591 1592 1593 1594 1595 1596 1597 1598 1599
        }

        count++;

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

M
Matthias Bolte 已提交
1600 1601
    success = true;

1602 1603 1604 1605
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
1606
    return success ? count : -1;
1607 1608 1609 1610 1611 1612 1613
}



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

1616
    if (esxVI_EnsureSession(priv->primary) < 0) {
1617 1618 1619
        return -1;
    }

1620
    return esxVI_LookupNumberOfDomainsByPowerState
1621
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn,
1622 1623 1624 1625 1626 1627 1628 1629
              esxVI_Boolean_False);
}



static virDomainPtr
esxDomainLookupByID(virConnectPtr conn, int id)
{
M
Matthias Bolte 已提交
1630
    esxPrivate *priv = conn->privateData;
1631 1632 1633 1634
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
M
Matthias Bolte 已提交
1635 1636 1637
    int id_candidate = -1;
    char *name_candidate = NULL;
    unsigned char uuid_candidate[VIR_UUID_BUFLEN];
1638 1639
    virDomainPtr domain = NULL;

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

1644
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1645
                                           "configStatus\0"
1646 1647
                                           "name\0"
                                           "runtime.powerState\0"
1648
                                           "config.uuid\0") < 0 ||
1649 1650
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1651
        goto cleanup;
1652 1653 1654 1655
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
1656
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1657
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1658
            goto cleanup;
1659 1660 1661 1662 1663 1664 1665
        }

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

M
Matthias Bolte 已提交
1666
        VIR_FREE(name_candidate);
1667

1668
        if (esxVI_GetVirtualMachineIdentity(virtualMachine,
M
Matthias Bolte 已提交
1669 1670
                                            &id_candidate, &name_candidate,
                                            uuid_candidate) < 0) {
M
Matthias Bolte 已提交
1671
            goto cleanup;
1672 1673
        }

M
Matthias Bolte 已提交
1674
        if (id != id_candidate) {
1675 1676 1677
            continue;
        }

M
Matthias Bolte 已提交
1678
        domain = virGetDomain(conn, name_candidate, uuid_candidate);
1679 1680

        if (domain == NULL) {
M
Matthias Bolte 已提交
1681
            goto cleanup;
1682 1683 1684 1685 1686 1687 1688 1689
        }

        domain->id = id;

        break;
    }

    if (domain == NULL) {
1690
        ESX_ERROR(VIR_ERR_NO_DOMAIN, _("No domain with ID %d"), id);
1691 1692 1693 1694 1695
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
M
Matthias Bolte 已提交
1696
    VIR_FREE(name_candidate);
1697 1698 1699 1700 1701 1702 1703 1704 1705

    return domain;
}



static virDomainPtr
esxDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
M
Matthias Bolte 已提交
1706
    esxPrivate *priv = conn->privateData;
1707 1708 1709
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1710 1711
    int id = -1;
    char *name = NULL;
1712 1713
    virDomainPtr domain = NULL;

1714
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1715
        return NULL;
1716 1717
    }

1718
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1719
                                           "name\0"
1720
                                           "runtime.powerState\0") < 0 ||
1721
        esxVI_LookupVirtualMachineByUuid(priv->primary, uuid, propertyNameList,
1722
                                         &virtualMachine,
M
Matthias Bolte 已提交
1723
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1724 1725
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, &name, NULL) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1726
        goto cleanup;
1727 1728
    }

1729
    domain = virGetDomain(conn, name, uuid);
1730 1731

    if (domain == NULL) {
M
Matthias Bolte 已提交
1732
        goto cleanup;
1733
    }
1734

1735 1736 1737 1738 1739
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1740 1741 1742 1743
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1744 1745
    esxVI_ObjectContent_Free(&virtualMachine);
    VIR_FREE(name);
1746 1747 1748 1749 1750 1751 1752 1753 1754

    return domain;
}



static virDomainPtr
esxDomainLookupByName(virConnectPtr conn, const char *name)
{
M
Matthias Bolte 已提交
1755
    esxPrivate *priv = conn->privateData;
1756 1757 1758
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1759 1760
    int id = -1;
    unsigned char uuid[VIR_UUID_BUFLEN];
1761 1762
    virDomainPtr domain = NULL;

1763
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1764
        return NULL;
1765 1766
    }

1767
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1768
                                           "configStatus\0"
1769
                                           "runtime.powerState\0"
1770
                                           "config.uuid\0") < 0 ||
1771
        esxVI_LookupVirtualMachineByName(priv->primary, name, propertyNameList,
1772 1773
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
1774
        goto cleanup;
1775 1776
    }

1777
    if (virtualMachine == NULL) {
1778
        ESX_ERROR(VIR_ERR_NO_DOMAIN, _("No domain with name '%s'"), name);
M
Matthias Bolte 已提交
1779
        goto cleanup;
1780
    }
1781 1782


M
Matthias Bolte 已提交
1783 1784 1785
    if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, uuid) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
1786
    }
1787

1788
    domain = virGetDomain(conn, name, uuid);
1789

1790
    if (domain == NULL) {
M
Matthias Bolte 已提交
1791
        goto cleanup;
1792 1793
    }

1794 1795 1796 1797 1798
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1799 1800 1801 1802
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1803
    esxVI_ObjectContent_Free(&virtualMachine);
1804 1805 1806 1807 1808 1809 1810 1811 1812

    return domain;
}



static int
esxDomainSuspend(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1813
    int result = -1;
M
Matthias Bolte 已提交
1814
    esxPrivate *priv = domain->conn->privateData;
1815 1816 1817 1818 1819 1820
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1821
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1822
        return -1;
1823 1824
    }

1825
    if (esxVI_String_AppendValueToList(&propertyNameList,
1826
                                       "runtime.powerState") < 0 ||
1827
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1828
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1829 1830
           priv->autoAnswer) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1831
        goto cleanup;
1832 1833 1834
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1835 1836
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1837
        goto cleanup;
1838 1839
    }

1840 1841
    if (esxVI_SuspendVM_Task(priv->primary, virtualMachine->obj, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1842
                                    esxVI_Occurrence_RequiredItem,
1843
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
1844
        goto cleanup;
1845 1846 1847
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1848
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not suspend domain"));
M
Matthias Bolte 已提交
1849
        goto cleanup;
1850 1851
    }

M
Matthias Bolte 已提交
1852 1853
    result = 0;

1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainResume(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1867
    int result = -1;
M
Matthias Bolte 已提交
1868
    esxPrivate *priv = domain->conn->privateData;
1869 1870 1871 1872 1873 1874
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

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

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

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

1893
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
1894
                             &task) < 0 ||
1895
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1896
                                    esxVI_Occurrence_RequiredItem,
1897
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
1898
        goto cleanup;
1899 1900 1901
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1902
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not resume domain"));
M
Matthias Bolte 已提交
1903
        goto cleanup;
1904 1905
    }

M
Matthias Bolte 已提交
1906 1907
    result = 0;

1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainShutdown(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1921
    int result = -1;
M
Matthias Bolte 已提交
1922
    esxPrivate *priv = domain->conn->privateData;
1923 1924 1925 1926
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

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

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

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

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

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

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

    return result;
}



static int
esxDomainReboot(virDomainPtr domain, unsigned int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
1964
    int result = -1;
M
Matthias Bolte 已提交
1965
    esxPrivate *priv = domain->conn->privateData;
1966 1967 1968 1969
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1970
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1971
        return -1;
1972 1973
    }

1974
    if (esxVI_String_AppendValueToList(&propertyNameList,
1975
                                       "runtime.powerState") < 0 ||
1976
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1977
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1978
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1979
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1980
        goto cleanup;
1981 1982 1983
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1984 1985
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1986
        goto cleanup;
1987 1988
    }

1989
    if (esxVI_RebootGuest(priv->primary, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1990
        goto cleanup;
1991 1992
    }

M
Matthias Bolte 已提交
1993 1994
    result = 0;

1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
esxDomainDestroy(virDomainPtr domain)
{
M
Matthias Bolte 已提交
2007
    int result = -1;
M
Matthias Bolte 已提交
2008
    esxPrivate *priv = domain->conn->privateData;
2009
    esxVI_Context *ctx = NULL;
2010 2011 2012 2013 2014 2015
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

2016 2017 2018 2019 2020 2021
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

2022
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
2023
        return -1;
2024 2025
    }

2026
    if (esxVI_String_AppendValueToList(&propertyNameList,
2027
                                       "runtime.powerState") < 0 ||
2028
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2029
          (ctx, domain->uuid, propertyNameList, &virtualMachine,
2030
           priv->autoAnswer) < 0 ||
2031
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
2032
        goto cleanup;
2033 2034 2035
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
2036 2037
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
2038
        goto cleanup;
2039 2040
    }

2041
    if (esxVI_PowerOffVM_Task(ctx, virtualMachine->obj, &task) < 0 ||
2042 2043 2044
        esxVI_WaitForTaskCompletion(ctx, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2045
        goto cleanup;
2046 2047 2048
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2049
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not destroy domain"));
M
Matthias Bolte 已提交
2050
        goto cleanup;
2051 2052
    }

2053
    domain->id = -1;
M
Matthias Bolte 已提交
2054 2055
    result = 0;

2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static char *
2067
esxDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED)
2068
{
2069 2070 2071
    char *osType = strdup("hvm");

    if (osType == NULL) {
2072
        virReportOOMError();
2073 2074 2075 2076
        return NULL;
    }

    return osType;
2077 2078 2079 2080 2081 2082 2083
}



static unsigned long
esxDomainGetMaxMemory(virDomainPtr domain)
{
M
Matthias Bolte 已提交
2084
    esxPrivate *priv = domain->conn->privateData;
2085 2086 2087 2088 2089
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    unsigned long memoryMB = 0;

2090
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2091
        return 0;
2092 2093
    }

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

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2105
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2106
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2107
                goto cleanup;
2108 2109 2110
            }

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

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

2147
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2148
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2149
           priv->autoAnswer) < 0 ||
2150 2151
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Long_Alloc(&spec->memoryMB) < 0) {
M
Matthias Bolte 已提交
2152
        goto cleanup;
2153 2154 2155 2156 2157
    }

    spec->memoryMB->value =
      memory / 1024; /* Scale from kilobytes to megabytes */

2158
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2159
                              &task) < 0 ||
2160
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2161
                                    esxVI_Occurrence_RequiredItem,
2162
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2163
        goto cleanup;
2164 2165 2166
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2167
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2168
                  _("Could not set max-memory to %lu kilobytes"), memory);
M
Matthias Bolte 已提交
2169
        goto cleanup;
2170 2171
    }

M
Matthias Bolte 已提交
2172 2173
    result = 0;

2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainSetMemory(virDomainPtr domain, unsigned long memory)
{
M
Matthias Bolte 已提交
2187
    int result = -1;
M
Matthias Bolte 已提交
2188
    esxPrivate *priv = domain->conn->privateData;
2189 2190 2191 2192 2193
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

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

2198
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2199
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2200
           priv->autoAnswer) < 0 ||
2201 2202 2203
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0 ||
        esxVI_Long_Alloc(&spec->memoryAllocation->limit) < 0) {
M
Matthias Bolte 已提交
2204
        goto cleanup;
2205 2206 2207 2208 2209
    }

    spec->memoryAllocation->limit->value =
      memory / 1024; /* Scale from kilobytes to megabytes */

2210
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2211
                              &task) < 0 ||
2212
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2213
                                    esxVI_Occurrence_RequiredItem,
2214
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2215
        goto cleanup;
2216 2217 2218
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2219
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2220
                  _("Could not set memory to %lu kilobytes"), memory);
M
Matthias Bolte 已提交
2221
        goto cleanup;
2222 2223
    }

M
Matthias Bolte 已提交
2224 2225
    result = 0;

2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info)
{
M
Matthias Bolte 已提交
2239
    int result = -1;
M
Matthias Bolte 已提交
2240
    esxPrivate *priv = domain->conn->privateData;
2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int64_t memory_limit = -1;
    esxVI_PerfMetricId *perfMetricId = NULL;
    esxVI_PerfMetricId *perfMetricIdList = NULL;
    esxVI_Int *counterId = NULL;
    esxVI_Int *counterIdList = NULL;
    esxVI_PerfCounterInfo *perfCounterInfo = NULL;
    esxVI_PerfCounterInfo *perfCounterInfoList = NULL;
    esxVI_PerfQuerySpec *querySpec = NULL;
2253 2254
    esxVI_PerfEntityMetricBase *perfEntityMetricBase = NULL;
    esxVI_PerfEntityMetricBase *perfEntityMetricBaseList = NULL;
2255 2256 2257 2258
    esxVI_PerfEntityMetric *perfEntityMetric = NULL;
    esxVI_PerfMetricIntSeries *perfMetricIntSeries = NULL;
    esxVI_Long *value = NULL;

M
Matthias Bolte 已提交
2259 2260
    memset(info, 0, sizeof (*info));

2261
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2262
        return -1;
2263 2264
    }

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

    info->state = VIR_DOMAIN_NOSTATE;

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

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

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

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

            memory_limit = dynamicProperty->val->int64;

            if (memory_limit > 0) {
                memory_limit *= 1024; /* Scale from megabyte to kilobyte */
            }
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    /* memory_limit < 0 means no memory limit is set */
    info->memory = memory_limit < 0 ? info->maxMem : memory_limit;

    /* Verify the cached 'used CPU time' performance counter ID */
2323 2324 2325 2326 2327 2328
    /* 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;
            }
2329

2330
            counterId->value = priv->usedCpuTimeCounterId;
2331

2332 2333 2334
            if (esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                goto cleanup;
            }
2335

2336 2337 2338 2339
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfo) < 0) {
                goto cleanup;
            }
2340

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

2347 2348 2349 2350 2351
                priv->usedCpuTimeCounterId = -1;
            }

            esxVI_Int_Free(&counterIdList);
            esxVI_PerfCounterInfo_Free(&perfCounterInfo);
2352 2353
        }

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

2365 2366 2367 2368
            for (perfMetricId = perfMetricIdList; perfMetricId != NULL;
                 perfMetricId = perfMetricId->_next) {
                VIR_DEBUG("perfMetricId counterId %d, instance '%s'",
                          perfMetricId->counterId->value, perfMetricId->instance);
2369

2370
                counterId = NULL;
2371

2372 2373 2374 2375 2376
                if (esxVI_Int_DeepCopy(&counterId, perfMetricId->counterId) < 0 ||
                    esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                    goto cleanup;
                }
            }
2377

2378 2379
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfoList) < 0) {
M
Matthias Bolte 已提交
2380
                goto cleanup;
2381 2382
            }

2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399
            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;
                }
2400 2401
            }

2402 2403 2404
            if (priv->usedCpuTimeCounterId < 0) {
                VIR_WARN0("Could not find 'used CPU time' performance counter");
            }
2405 2406
        }

2407 2408 2409 2410 2411 2412
        /*
         * 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);
2413

2414 2415 2416 2417 2418 2419
            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;
            }
2420

2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433
            querySpec->entity = virtualMachine->obj;
            querySpec->maxSample->value = 1;
            querySpec->metricId->counterId->value = priv->usedCpuTimeCounterId;
            querySpec->metricId->instance = (char *)"";
            querySpec->format = (char *)"normal";

            if (esxVI_QueryPerf(priv->host, querySpec,
                                &perfEntityMetricBaseList) < 0) {
                querySpec->entity = NULL;
                querySpec->metricId->instance = NULL;
                querySpec->format = NULL;
                goto cleanup;
            }
2434

2435 2436 2437 2438
            for (perfEntityMetricBase = perfEntityMetricBaseList;
                 perfEntityMetricBase != NULL;
                 perfEntityMetricBase = perfEntityMetricBase->_next) {
                VIR_DEBUG0("perfEntityMetric ...");
2439

2440 2441
                perfEntityMetric =
                  esxVI_PerfEntityMetric_DynamicCast(perfEntityMetricBase);
2442

2443 2444 2445
                if (perfMetricIntSeries == NULL) {
                    VIR_ERROR0(_("QueryPerf returned object with unexpected type"));
                }
2446

2447 2448
                perfMetricIntSeries =
                  esxVI_PerfMetricIntSeries_DynamicCast(perfEntityMetric->value);
2449

2450 2451 2452
                if (perfMetricIntSeries == NULL) {
                    VIR_ERROR0(_("QueryPerf returned object with unexpected type"));
                }
2453

2454 2455 2456
                for (; perfMetricIntSeries != NULL;
                     perfMetricIntSeries = perfMetricIntSeries->_next) {
                    VIR_DEBUG0("perfMetricIntSeries ...");
2457

2458 2459 2460 2461 2462
                    for (value = perfMetricIntSeries->value;
                         value != NULL;
                         value = value->_next) {
                        VIR_DEBUG("value %lld", (long long int)value->value);
                    }
2463 2464 2465
                }
            }

2466 2467 2468
            querySpec->entity = NULL;
            querySpec->metricId->instance = NULL;
            querySpec->format = NULL;
2469

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

2472 2473 2474 2475 2476
            /*
             * FIXME: Cannot map between realtive used-cpu-time and absolute
             *        info->cpuTime
             */
        }
2477 2478
    }

M
Matthias Bolte 已提交
2479 2480
    result = 0;

2481 2482 2483 2484 2485 2486 2487
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_PerfMetricId_Free(&perfMetricIdList);
    esxVI_Int_Free(&counterIdList);
    esxVI_PerfCounterInfo_Free(&perfCounterInfoList);
    esxVI_PerfQuerySpec_Free(&querySpec);
2488
    esxVI_PerfEntityMetricBase_Free(&perfEntityMetricBaseList);
2489 2490 2491 2492 2493 2494 2495 2496 2497

    return result;
}



static int
esxDomainSetVcpus(virDomainPtr domain, unsigned int nvcpus)
{
M
Matthias Bolte 已提交
2498
    int result = -1;
M
Matthias Bolte 已提交
2499
    esxPrivate *priv = domain->conn->privateData;
M
Matthias Bolte 已提交
2500
    int maxVcpus;
2501 2502 2503 2504 2505 2506
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

    if (nvcpus < 1) {
2507 2508
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Requested number of virtual CPUs must at least be 1"));
M
Matthias Bolte 已提交
2509
        return -1;
2510 2511
    }

2512
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2513
        return -1;
2514 2515
    }

M
Matthias Bolte 已提交
2516
    maxVcpus = esxDomainGetMaxVcpus(domain);
2517

M
Matthias Bolte 已提交
2518
    if (maxVcpus < 0) {
M
Matthias Bolte 已提交
2519
        return -1;
2520 2521
    }

M
Matthias Bolte 已提交
2522
    if (nvcpus > maxVcpus) {
2523
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2524 2525
                  _("Requested number of virtual CPUs is greater than max "
                    "allowable number of virtual CPUs for the domain: %d > %d"),
M
Matthias Bolte 已提交
2526
                  nvcpus, maxVcpus);
M
Matthias Bolte 已提交
2527
        return -1;
2528 2529
    }

2530
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2531
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2532
           priv->autoAnswer) < 0 ||
2533 2534
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Int_Alloc(&spec->numCPUs) < 0) {
M
Matthias Bolte 已提交
2535
        goto cleanup;
2536 2537 2538 2539
    }

    spec->numCPUs->value = nvcpus;

2540
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2541
                              &task) < 0 ||
2542
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2543
                                    esxVI_Occurrence_RequiredItem,
2544
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2545
        goto cleanup;
2546 2547 2548
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2549
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2550
                  _("Could not set number of virtual CPUs to %d"), nvcpus);
M
Matthias Bolte 已提交
2551
        goto cleanup;
2552 2553
    }

M
Matthias Bolte 已提交
2554 2555
    result = 0;

2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainGetMaxVcpus(virDomainPtr domain)
{
M
Matthias Bolte 已提交
2569
    esxPrivate *priv = domain->conn->privateData;
2570 2571 2572 2573
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

M
Matthias Bolte 已提交
2574 2575
    if (priv->maxVcpus > 0) {
        return priv->maxVcpus;
2576 2577
    }

M
Matthias Bolte 已提交
2578 2579
    priv->maxVcpus = -1;

2580
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2581
        return -1;
2582 2583
    }

2584
    if (esxVI_String_AppendValueToList(&propertyNameList,
2585
                                       "capability.maxSupportedVcpus") < 0 ||
2586 2587
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
2588
        goto cleanup;
2589 2590 2591
    }

    if (hostSystem == NULL) {
2592 2593
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
2594
        goto cleanup;
2595 2596 2597 2598 2599
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "capability.maxSupportedVcpus")) {
2600
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2601
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2602
                goto cleanup;
2603 2604
            }

M
Matthias Bolte 已提交
2605
            priv->maxVcpus = dynamicProperty->val->int32;
2606 2607 2608 2609 2610 2611 2612 2613 2614 2615
            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

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

M
Matthias Bolte 已提交
2616
    return priv->maxVcpus;
2617 2618 2619 2620 2621 2622 2623
}



static char *
esxDomainDumpXML(virDomainPtr domain, int flags)
{
M
Matthias Bolte 已提交
2624
    esxPrivate *priv = domain->conn->privateData;
2625 2626
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
2627 2628
    esxVI_VirtualMachinePowerState powerState;
    int id;
2629
    char *vmPathName = NULL;
2630
    char *datastoreName = NULL;
M
Matthias Bolte 已提交
2631 2632
    char *directoryName = NULL;
    char *fileName = NULL;
2633
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
2634 2635
    char *url = NULL;
    char *vmx = NULL;
2636 2637
    esxVMX_Context ctx;
    esxVMX_Data data;
2638 2639 2640
    virDomainDefPtr def = NULL;
    char *xml = NULL;

2641
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2642
        return NULL;
2643 2644
    }

2645 2646 2647
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "config.files.vmPathName\0"
                                           "runtime.powerState\0") < 0 ||
2648
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2649
                                         propertyNameList, &virtualMachine,
2650
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2651 2652
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0 ||
2653 2654
        esxVI_GetStringValue(virtualMachine, "config.files.vmPathName",
                             &vmPathName, esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2655
        goto cleanup;
2656 2657
    }

2658 2659
    if (esxUtil_ParseDatastorePath(vmPathName, &datastoreName, &directoryName,
                                   &fileName) < 0) {
M
Matthias Bolte 已提交
2660
        goto cleanup;
2661 2662
    }

2663 2664
    virBufferVSprintf(&buffer, "%s://%s:%d/folder/", priv->transport,
                      domain->conn->uri->server, domain->conn->uri->port);
M
Matthias Bolte 已提交
2665 2666 2667 2668 2669 2670 2671

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

    virBufferURIEncodeString(&buffer, fileName);
2672
    virBufferAddLit(&buffer, "?dcPath=");
2673
    virBufferURIEncodeString(&buffer, priv->primary->datacenter->name);
2674 2675 2676 2677
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
2678
        virReportOOMError();
M
Matthias Bolte 已提交
2679
        goto cleanup;
2680 2681
    }

2682 2683
    url = virBufferContentAndReset(&buffer);

2684
    if (esxVI_Context_DownloadFile(priv->primary, url, &vmx) < 0) {
M
Matthias Bolte 已提交
2685
        goto cleanup;
2686 2687
    }

2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698
    data.ctx = priv->primary;
    data.datastoreName = datastoreName;
    data.directoryName = directoryName;

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

    def = esxVMX_ParseConfig(&ctx, priv->caps, vmx,
                             priv->primary->productVersion);
2699 2700

    if (def != NULL) {
2701 2702 2703 2704
        if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
            def->id = id;
        }

2705
        xml = virDomainDefFormat(def, flags);
2706 2707 2708
    }

  cleanup:
M
Matthias Bolte 已提交
2709 2710 2711 2712
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

2713 2714
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2715
    VIR_FREE(datastoreName);
M
Matthias Bolte 已提交
2716 2717
    VIR_FREE(directoryName);
    VIR_FREE(fileName);
2718 2719
    VIR_FREE(url);
    VIR_FREE(vmx);
2720
    virDomainDefFree(def);
2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731

    return xml;
}



static char *
esxDomainXMLFromNative(virConnectPtr conn, const char *nativeFormat,
                       const char *nativeConfig,
                       unsigned int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2732
    esxPrivate *priv = conn->privateData;
2733 2734
    esxVMX_Context ctx;
    esxVMX_Data data;
2735 2736 2737 2738
    virDomainDefPtr def = NULL;
    char *xml = NULL;

    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2739
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2740
                  _("Unsupported config format '%s'"), nativeFormat);
2741
        return NULL;
2742 2743
    }

2744 2745 2746 2747 2748 2749 2750 2751 2752 2753
    data.ctx = priv->primary;
    data.datastoreName = "?";
    data.directoryName = "?";

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

    def = esxVMX_ParseConfig(&ctx, priv->caps, nativeConfig,
2754
                             priv->primary->productVersion);
2755 2756

    if (def != NULL) {
2757
        xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
2758 2759 2760 2761 2762 2763 2764 2765 2766
    }

    virDomainDefFree(def);

    return xml;
}



M
Matthias Bolte 已提交
2767 2768 2769 2770 2771
static char *
esxDomainXMLToNative(virConnectPtr conn, const char *nativeFormat,
                     const char *domainXml,
                     unsigned int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2772
    esxPrivate *priv = conn->privateData;
2773 2774
    esxVMX_Context ctx;
    esxVMX_Data data;
M
Matthias Bolte 已提交
2775 2776 2777 2778
    virDomainDefPtr def = NULL;
    char *vmx = NULL;

    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2779
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2780
                  _("Unsupported config format '%s'"), nativeFormat);
M
Matthias Bolte 已提交
2781 2782 2783
        return NULL;
    }

2784
    def = virDomainDefParseString(priv->caps, domainXml, 0);
M
Matthias Bolte 已提交
2785 2786 2787 2788 2789

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

2790 2791 2792 2793 2794 2795 2796 2797 2798 2799
    data.ctx = priv->primary;
    data.datastoreName = NULL;
    data.directoryName = NULL;

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

    vmx = esxVMX_FormatConfig(&ctx, priv->caps, def,
2800
                              priv->primary->productVersion);
M
Matthias Bolte 已提交
2801 2802 2803 2804 2805 2806 2807 2808

    virDomainDefFree(def);

    return vmx;
}



2809 2810 2811
static int
esxListDefinedDomains(virConnectPtr conn, char **const names, int maxnames)
{
M
Matthias Bolte 已提交
2812
    bool success = false;
M
Matthias Bolte 已提交
2813
    esxPrivate *priv = conn->privateData;
2814 2815 2816 2817 2818 2819
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;
2820
    int i;
2821 2822

    if (names == NULL || maxnames < 0) {
2823 2824
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
2825 2826 2827 2828 2829 2830
    }

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

2831
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2832
        return -1;
2833 2834
    }

2835
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2836 2837
                                           "name\0"
                                           "runtime.powerState\0") < 0 ||
2838 2839
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2840
        goto cleanup;
2841 2842 2843 2844
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
2845
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
2846
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
2847
            goto cleanup;
2848 2849 2850 2851 2852 2853 2854 2855 2856 2857
        }

        if (powerState == esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

        for (dynamicProperty = virtualMachine->propSet;
             dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "name")) {
2858
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2859
                                             esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
2860
                    goto cleanup;
2861 2862 2863 2864 2865
                }

                names[count] = strdup(dynamicProperty->val->string);

                if (names[count] == NULL) {
2866
                    virReportOOMError();
M
Matthias Bolte 已提交
2867
                    goto cleanup;
2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879
                }

                count++;
                break;
            }
        }

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

M
Matthias Bolte 已提交
2880
    success = true;
2881

M
Matthias Bolte 已提交
2882 2883 2884 2885 2886
  cleanup:
    if (! success) {
        for (i = 0; i < count; ++i) {
            VIR_FREE(names[i]);
        }
2887

M
Matthias Bolte 已提交
2888
        count = -1;
2889 2890
    }

M
Matthias Bolte 已提交
2891 2892
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
2893

M
Matthias Bolte 已提交
2894
    return count;
2895 2896 2897 2898 2899 2900 2901
}



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

2904
    if (esxVI_EnsureSession(priv->primary) < 0) {
2905 2906 2907
        return -1;
    }

2908
    return esxVI_LookupNumberOfDomainsByPowerState
2909
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn,
2910 2911 2912 2913 2914 2915
              esxVI_Boolean_True);
}



static int
2916
esxDomainCreateWithFlags(virDomainPtr domain, unsigned int flags)
2917
{
M
Matthias Bolte 已提交
2918
    int result = -1;
M
Matthias Bolte 已提交
2919
    esxPrivate *priv = domain->conn->privateData;
2920 2921 2922
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
2923
    int id = -1;
2924 2925 2926
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

2927 2928
    virCheckFlags(0, -1);

2929
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2930
        return -1;
2931 2932
    }

2933
    if (esxVI_String_AppendValueToList(&propertyNameList,
2934
                                       "runtime.powerState") < 0 ||
2935
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2936
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
2937
           priv->autoAnswer) < 0 ||
2938 2939
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0) {
M
Matthias Bolte 已提交
2940
        goto cleanup;
2941 2942 2943
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2944 2945
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered off"));
M
Matthias Bolte 已提交
2946
        goto cleanup;
2947 2948
    }

2949
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
2950
                             &task) < 0 ||
2951
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2952
                                    esxVI_Occurrence_RequiredItem,
2953
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2954
        goto cleanup;
2955 2956 2957
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2958
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not start domain"));
M
Matthias Bolte 已提交
2959
        goto cleanup;
2960 2961
    }

2962
    domain->id = id;
M
Matthias Bolte 已提交
2963 2964
    result = 0;

2965 2966 2967 2968 2969 2970 2971 2972
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}

2973 2974 2975 2976 2977
static int
esxDomainCreate(virDomainPtr domain)
{
    return esxDomainCreateWithFlags(domain, 0);
}
2978

M
Matthias Bolte 已提交
2979 2980 2981
static virDomainPtr
esxDomainDefineXML(virConnectPtr conn, const char *xml ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2982
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
2983 2984
    virDomainDefPtr def = NULL;
    char *vmx = NULL;
2985 2986
    int i;
    virDomainDiskDefPtr disk = NULL;
M
Matthias Bolte 已提交
2987
    esxVI_ObjectContent *virtualMachine = NULL;
2988 2989
    esxVMX_Context ctx;
    esxVMX_Data data;
M
Matthias Bolte 已提交
2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002
    char *datastoreName = NULL;
    char *directoryName = NULL;
    char *fileName = NULL;
    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;
    virDomainPtr domain = NULL;

3003
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3004
        return NULL;
M
Matthias Bolte 已提交
3005 3006 3007
    }

    /* Parse domain XML */
3008
    def = virDomainDefParseString(priv->caps, xml,
M
Matthias Bolte 已提交
3009 3010 3011
                                  VIR_DOMAIN_XML_INACTIVE);

    if (def == NULL) {
M
Matthias Bolte 已提交
3012
        return NULL;
M
Matthias Bolte 已提交
3013 3014 3015
    }

    /* Check if an existing domain should be edited */
3016
    if (esxVI_LookupVirtualMachineByUuid(priv->primary, def->uuid, NULL,
M
Matthias Bolte 已提交
3017
                                         &virtualMachine,
M
Matthias Bolte 已提交
3018
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
3019
        goto cleanup;
M
Matthias Bolte 已提交
3020 3021 3022 3023
    }

    if (virtualMachine != NULL) {
        /* FIXME */
3024 3025 3026
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Domain already exists, editing existing domains is not "
                    "supported yet"));
M
Matthias Bolte 已提交
3027
        goto cleanup;
M
Matthias Bolte 已提交
3028 3029 3030
    }

    /* Build VMX from domain XML */
3031 3032 3033 3034 3035 3036 3037 3038 3039 3040
    data.ctx = priv->primary;
    data.datastoreName = NULL;
    data.directoryName = NULL;

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

    vmx = esxVMX_FormatConfig(&ctx, priv->caps, def,
3041
                              priv->primary->productVersion);
M
Matthias Bolte 已提交
3042 3043

    if (vmx == NULL) {
M
Matthias Bolte 已提交
3044
        goto cleanup;
M
Matthias Bolte 已提交
3045 3046
    }

3047 3048 3049 3050 3051 3052 3053
    /*
     * 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 已提交
3054
    if (def->ndisks < 1) {
3055 3056 3057
        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 已提交
3058
        goto cleanup;
3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069
    }

    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) {
3070 3071 3072
        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 已提交
3073
        goto cleanup;
M
Matthias Bolte 已提交
3074 3075
    }

3076
    if (disk->src == NULL) {
3077 3078 3079
        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 已提交
3080
        goto cleanup;
M
Matthias Bolte 已提交
3081 3082
    }

3083 3084
    if (esxUtil_ParseDatastorePath(disk->src, &datastoreName, &directoryName,
                                   &fileName) < 0) {
M
Matthias Bolte 已提交
3085
        goto cleanup;
M
Matthias Bolte 已提交
3086 3087
    }

3088
    if (! virFileHasSuffix(fileName, ".vmdk")) {
3089
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3090 3091
                  _("Expecting source '%s' of first file-based harddisk to "
                    "be a VMDK image"), disk->src);
M
Matthias Bolte 已提交
3092
        goto cleanup;
M
Matthias Bolte 已提交
3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104
    }

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

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

    virBufferURIEncodeString(&buffer, def->name);
    virBufferAddLit(&buffer, ".vmx?dcPath=");
3105
    virBufferURIEncodeString(&buffer, priv->primary->datacenter->name);
M
Matthias Bolte 已提交
3106 3107 3108 3109
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
3110
        virReportOOMError();
M
Matthias Bolte 已提交
3111
        goto cleanup;
M
Matthias Bolte 已提交
3112 3113 3114 3115 3116 3117 3118
    }

    url = virBufferContentAndReset(&buffer);

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

    /* Check, if VMX file already exists */
    /* FIXME */

    /* Upload VMX file */
3134
    if (esxVI_Context_UploadFile(priv->primary, url, vmx) < 0) {
M
Matthias Bolte 已提交
3135
        goto cleanup;
M
Matthias Bolte 已提交
3136 3137 3138
    }

    /* Register the domain */
3139
    if (esxVI_RegisterVM_Task(priv->primary, priv->primary->datacenter->vmFolder,
M
Matthias Bolte 已提交
3140
                              datastoreRelatedPath, NULL, esxVI_Boolean_False,
3141 3142 3143 3144
                              priv->primary->computeResource->resourcePool,
                              priv->primary->hostSystem->_reference,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, def->uuid,
3145
                                    esxVI_Occurrence_OptionalItem,
3146
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3147
        goto cleanup;
M
Matthias Bolte 已提交
3148 3149 3150
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3151
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not define domain"));
M
Matthias Bolte 已提交
3152
        goto cleanup;
M
Matthias Bolte 已提交
3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163
    }

    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 已提交
3164 3165 3166 3167
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

M
Matthias Bolte 已提交
3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185
    virDomainDefFree(def);
    VIR_FREE(vmx);
    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
    VIR_FREE(fileName);
    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);

    return domain;
}



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

3196 3197 3198 3199 3200 3201
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

3202
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
3203
        return -1;
3204 3205
    }

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

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

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

M
Matthias Bolte 已提交
3226 3227
    result = 0;

3228 3229 3230 3231 3232 3233 3234 3235 3236
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248
/*
 * The scheduler interface exposes basically the CPU ResourceAllocationInfo:
 *
 * - http://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.ResourceAllocationInfo.html
 * - http://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.SharesInfo.html
 * - http://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.SharesInfo.Level.html
 *
 *
 * Available parameters:
 *
 * - reservation (VIR_DOMAIN_SCHED_FIELD_LLONG >= 0, in megaherz)
 *
3249
 *   The amount of CPU resource that is guaranteed to be available to the domain.
3250 3251 3252 3253
 *
 *
 * - limit (VIR_DOMAIN_SCHED_FIELD_LLONG >= 0, or -1, in megaherz)
 *
3254 3255
 *   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
3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266
 *   utilization of the domain is unlimited. If the limit is not set to -1, it
 *   must be greater than or equal to the reservation.
 *
 *
 * - shares (VIR_DOMAIN_SCHED_FIELD_INT >= 0, or in {-1, -2, -3}, no unit)
 *
 *   Shares are used to determine relative CPU allocation between domains. In
 *   general, a domain with more shares gets proportionally more of the CPU
 *   resource. The special values -1, -2 and -3 represent the predefined
 *   SharesLevel 'low', 'normal' and 'high'.
 */
3267
static char *
3268
esxDomainGetSchedulerType(virDomainPtr domain ATTRIBUTE_UNUSED, int *nparams)
3269 3270 3271 3272
{
    char *type = strdup("allocation");

    if (type == NULL) {
3273
        virReportOOMError();
3274
        return NULL;
3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287
    }

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

    return type;
}



static int
esxDomainGetSchedulerParameters(virDomainPtr domain,
                                virSchedParameterPtr params, int *nparams)
{
M
Matthias Bolte 已提交
3288
    int result = -1;
M
Matthias Bolte 已提交
3289
    esxPrivate *priv = domain->conn->privateData;
3290 3291 3292 3293 3294 3295 3296 3297
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    unsigned int mask = 0;
    int i = 0;

    if (*nparams < 3) {
3298 3299
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Parameter array must have space for 3 items"));
M
Matthias Bolte 已提交
3300
        return -1;
3301 3302
    }

3303
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3304
        return -1;
3305 3306
    }

3307
    if (esxVI_String_AppendValueListToList(&propertyNameList,
3308 3309 3310
                                           "config.cpuAllocation.reservation\0"
                                           "config.cpuAllocation.limit\0"
                                           "config.cpuAllocation.shares\0") < 0 ||
3311
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
3312
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3313
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3314
        goto cleanup;
3315 3316 3317 3318 3319 3320
    }

    for (dynamicProperty = virtualMachine->propSet;
         dynamicProperty != NULL && mask != 7 && i < 3;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.cpuAllocation.reservation") &&
M
Matthias Bolte 已提交
3321
            ! (mask & (1 << 0))) {
3322 3323 3324 3325 3326
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "reservation");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_LLONG;

3327
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3328
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3329
                goto cleanup;
3330 3331 3332 3333 3334 3335 3336
            }

            params[i].value.l = dynamicProperty->val->int64;
            mask |= 1 << 0;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.limit") &&
M
Matthias Bolte 已提交
3337
                   ! (mask & (1 << 1))) {
3338 3339 3340 3341 3342
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "limit");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_LLONG;

3343
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3344
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3345
                goto cleanup;
3346 3347 3348 3349 3350 3351 3352
            }

            params[i].value.l = dynamicProperty->val->int64;
            mask |= 1 << 1;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.shares") &&
M
Matthias Bolte 已提交
3353
                   ! (mask & (1 << 2))) {
3354 3355 3356 3357 3358
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "shares");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_INT;

3359
            if (esxVI_SharesInfo_CastFromAnyType(dynamicProperty->val,
3360
                                                 &sharesInfo) < 0) {
M
Matthias Bolte 已提交
3361
                goto cleanup;
3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381
            }

            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:
3382
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3383
                          _("Shares level has unknown value %d"),
3384
                          (int)sharesInfo->level);
M
Matthias Bolte 已提交
3385
                goto cleanup;
3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397
            }

            esxVI_SharesInfo_Free(&sharesInfo);

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

    *nparams = i;
M
Matthias Bolte 已提交
3398
    result = 0;
3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412

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

    return result;
}



static int
esxDomainSetSchedulerParameters(virDomainPtr domain,
                                virSchedParameterPtr params, int nparams)
{
M
Matthias Bolte 已提交
3413
    int result = -1;
M
Matthias Bolte 已提交
3414
    esxPrivate *priv = domain->conn->privateData;
3415 3416 3417 3418 3419 3420 3421
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
    int i;

3422
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3423
        return -1;
3424 3425
    }

3426
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3427
          (priv->primary, domain->uuid, NULL, &virtualMachine,
3428
           priv->autoAnswer) < 0 ||
3429 3430
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->cpuAllocation) < 0) {
M
Matthias Bolte 已提交
3431
        goto cleanup;
3432 3433 3434 3435 3436
    }

    for (i = 0; i < nparams; ++i) {
        if (STREQ (params[i].field, "reservation") &&
            params[i].type == VIR_DOMAIN_SCHED_FIELD_LLONG) {
3437
            if (esxVI_Long_Alloc(&spec->cpuAllocation->reservation) < 0) {
M
Matthias Bolte 已提交
3438
                goto cleanup;
3439 3440 3441
            }

            if (params[i].value.l < 0) {
3442
                ESX_ERROR(VIR_ERR_INVALID_ARG,
3443 3444
                          _("Could not set reservation to %lld MHz, expecting "
                            "positive value"), params[i].value.l);
M
Matthias Bolte 已提交
3445
                goto cleanup;
3446 3447 3448 3449 3450
            }

            spec->cpuAllocation->reservation->value = params[i].value.l;
        } else if (STREQ (params[i].field, "limit") &&
                   params[i].type == VIR_DOMAIN_SCHED_FIELD_LLONG) {
3451
            if (esxVI_Long_Alloc(&spec->cpuAllocation->limit) < 0) {
M
Matthias Bolte 已提交
3452
                goto cleanup;
3453 3454 3455
            }

            if (params[i].value.l < -1) {
3456
                ESX_ERROR(VIR_ERR_INVALID_ARG,
3457 3458
                          _("Could not set limit to %lld MHz, expecting "
                            "positive value or -1 (unlimited)"),
3459
                          params[i].value.l);
M
Matthias Bolte 已提交
3460
                goto cleanup;
3461 3462 3463 3464
            }

            spec->cpuAllocation->limit->value = params[i].value.l;
        } else if (STREQ (params[i].field, "shares") &&
3465
                   params[i].type == VIR_DOMAIN_SCHED_FIELD_INT) {
3466 3467
            if (esxVI_SharesInfo_Alloc(&sharesInfo) < 0 ||
                esxVI_Int_Alloc(&sharesInfo->shares) < 0) {
M
Matthias Bolte 已提交
3468
                goto cleanup;
3469 3470 3471 3472
            }

            spec->cpuAllocation->shares = sharesInfo;

3473
            if (params[i].value.i >= 0) {
3474
                spec->cpuAllocation->shares->level = esxVI_SharesLevel_Custom;
3475
                spec->cpuAllocation->shares->shares->value = params[i].value.i;
3476
            } else {
3477
                switch (params[i].value.i) {
3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495
                  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:
3496
                    ESX_ERROR(VIR_ERR_INVALID_ARG,
3497 3498
                              _("Could not set shares to %d, expecting positive "
                                "value or -1 (low), -2 (normal) or -3 (high)"),
3499
                              params[i].value.i);
M
Matthias Bolte 已提交
3500
                    goto cleanup;
3501 3502 3503
                }
            }
        } else {
3504
            ESX_ERROR(VIR_ERR_INVALID_ARG, _("Unknown field '%s'"),
3505
                      params[i].field);
M
Matthias Bolte 已提交
3506
            goto cleanup;
3507 3508 3509
        }
    }

3510
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
3511
                              &task) < 0 ||
3512
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3513
                                    esxVI_Occurrence_RequiredItem,
3514
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3515
        goto cleanup;
3516 3517 3518
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3519 3520
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not change scheduler parameters"));
M
Matthias Bolte 已提交
3521
        goto cleanup;
3522 3523
    }

M
Matthias Bolte 已提交
3524 3525
    result = 0;

3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainMigratePrepare(virConnectPtr dconn,
                        char **cookie ATTRIBUTE_UNUSED,
                        int *cookielen ATTRIBUTE_UNUSED,
3540 3541
                        const char *uri_in ATTRIBUTE_UNUSED,
                        char **uri_out,
3542 3543 3544 3545
                        unsigned long flags ATTRIBUTE_UNUSED,
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
3546
    esxPrivate *priv = dconn->privateData;
3547 3548

    if (uri_in == NULL) {
3549 3550 3551 3552
        if (virAsprintf(uri_out, "vpxmigr://%s/%s/%s",
                        priv->vCenter->ipAddress,
                        priv->vCenter->computeResource->resourcePool->value,
                        priv->vCenter->hostSystem->_reference->value) < 0) {
3553
            virReportOOMError();
3554
            return -1;
3555 3556 3557
        }
    }

3558
    return 0;
3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571
}



static int
esxDomainMigratePerform(virDomainPtr domain,
                        const char *cookie ATTRIBUTE_UNUSED,
                        int cookielen ATTRIBUTE_UNUSED,
                        const char *uri,
                        unsigned long flags ATTRIBUTE_UNUSED,
                        const char *dname,
                        unsigned long bandwidth ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
3572
    int result = -1;
M
Matthias Bolte 已提交
3573
    esxPrivate *priv = domain->conn->privateData;
3574 3575 3576 3577
    xmlURIPtr parsedUri = NULL;
    char *saveptr;
    char *path_resourcePool;
    char *path_hostSystem;
3578
    esxVI_ObjectContent *virtualMachine = NULL;
3579 3580
    esxVI_ManagedObjectReference resourcePool;
    esxVI_ManagedObjectReference hostSystem;
3581 3582 3583 3584
    esxVI_Event *eventList = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

M
Matthias Bolte 已提交
3585
    if (priv->vCenter == NULL) {
3586 3587
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Migration not possible without a vCenter"));
M
Matthias Bolte 已提交
3588
        return -1;
3589 3590 3591
    }

    if (dname != NULL) {
3592 3593
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Renaming domains on migration not supported"));
M
Matthias Bolte 已提交
3594
        return -1;
3595 3596
    }

3597
    if (esxVI_EnsureSession(priv->vCenter) < 0) {
M
Matthias Bolte 已提交
3598
        return -1;
3599 3600
    }

3601 3602
    /* Parse migration URI */
    parsedUri = xmlParseURI(uri);
3603

3604
    if (parsedUri == NULL) {
3605
        virReportOOMError();
M
Matthias Bolte 已提交
3606
        return -1;
3607 3608
    }

3609 3610 3611
    if (parsedUri->scheme == NULL || STRCASENEQ(parsedUri->scheme, "vpxmigr")) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Only vpxmigr:// migration URIs are supported"));
M
Matthias Bolte 已提交
3612
        goto cleanup;
3613 3614
    }

3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627
    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 已提交
3628
        goto cleanup;
3629 3630
    }

3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644
    resourcePool._next = NULL;
    resourcePool._type = esxVI_Type_ManagedObjectReference;
    resourcePool.type = (char *)"ResourcePool";
    resourcePool.value = path_resourcePool;

    hostSystem._next = NULL;
    hostSystem._type = esxVI_Type_ManagedObjectReference;
    hostSystem.type = (char *)"HostSystem";
    hostSystem.value = path_hostSystem;

    /* Lookup VirtualMachine */
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->vCenter, domain->uuid, NULL, &virtualMachine,
           priv->autoAnswer) < 0) {
M
Matthias Bolte 已提交
3645
        goto cleanup;
3646 3647 3648
    }

    /* Validate the purposed migration */
3649
    if (esxVI_ValidateMigration(priv->vCenter, virtualMachine->obj,
3650 3651
                                esxVI_VirtualMachinePowerState_Undefined, NULL,
                                &resourcePool, &hostSystem, &eventList) < 0) {
M
Matthias Bolte 已提交
3652
        goto cleanup;
3653 3654 3655 3656 3657 3658 3659 3660
    }

    if (eventList != NULL) {
        /*
         * FIXME: Need to report the complete list of events. Limit reporting
         *        to the first event for now.
         */
        if (eventList->fullFormattedMessage != NULL) {
3661
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3662 3663
                      _("Could not migrate domain, validation reported a "
                        "problem: %s"), eventList->fullFormattedMessage);
3664
        } else {
3665 3666 3667
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                      _("Could not migrate domain, validation reported a "
                        "problem"));
3668 3669
        }

M
Matthias Bolte 已提交
3670
        goto cleanup;
3671 3672 3673
    }

    /* Perform the purposed migration */
3674 3675
    if (esxVI_MigrateVM_Task(priv->vCenter, virtualMachine->obj,
                             &resourcePool, &hostSystem,
3676 3677 3678
                             esxVI_VirtualMachineMovePriority_DefaultPriority,
                             esxVI_VirtualMachinePowerState_Undefined,
                             &task) < 0 ||
3679
        esxVI_WaitForTaskCompletion(priv->vCenter, task, domain->uuid,
3680
                                    esxVI_Occurrence_RequiredItem,
3681
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3682
        goto cleanup;
3683 3684 3685
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3686 3687 3688
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not migrate domain, migration task finished with "
                    "an error"));
M
Matthias Bolte 已提交
3689
        goto cleanup;
3690 3691
    }

M
Matthias Bolte 已提交
3692 3693
    result = 0;

3694
  cleanup:
3695
    xmlFreeURI(parsedUri);
3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Event_Free(&eventList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static virDomainPtr
esxDomainMigrateFinish(virConnectPtr dconn, const char *dname,
                       const char *cookie ATTRIBUTE_UNUSED,
                       int cookielen ATTRIBUTE_UNUSED,
                       const char *uri ATTRIBUTE_UNUSED,
                       unsigned long flags ATTRIBUTE_UNUSED)
{
    return esxDomainLookupByName(dconn, dname);
}



M
Matthias Bolte 已提交
3717 3718 3719 3720
static unsigned long long
esxNodeGetFreeMemory(virConnectPtr conn)
{
    unsigned long long result = 0;
M
Matthias Bolte 已提交
3721
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
3722 3723 3724 3725 3726
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *resourcePool = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ResourcePoolResourceUsage *resourcePoolResourceUsage = NULL;

3727
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3728
        return 0;
M
Matthias Bolte 已提交
3729 3730 3731
    }

    /* Get memory usage of resource pool */
3732
    if (esxVI_String_AppendValueToList(&propertyNameList,
M
Matthias Bolte 已提交
3733
                                       "runtime.memory") < 0 ||
3734 3735
        esxVI_LookupObjectContentByType(priv->primary,
                                        priv->primary->computeResource->resourcePool,
3736 3737
                                        "ResourcePool", propertyNameList,
                                        &resourcePool) < 0) {
M
Matthias Bolte 已提交
3738
        goto cleanup;
M
Matthias Bolte 已提交
3739 3740 3741 3742 3743 3744
    }

    for (dynamicProperty = resourcePool->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.memory")) {
            if (esxVI_ResourcePoolResourceUsage_CastFromAnyType
3745
                  (dynamicProperty->val, &resourcePoolResourceUsage) < 0) {
M
Matthias Bolte 已提交
3746
                goto cleanup;
M
Matthias Bolte 已提交
3747 3748 3749 3750 3751 3752 3753 3754 3755
            }

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

    if (resourcePoolResourceUsage == NULL) {
3756 3757
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve memory usage of resource pool"));
M
Matthias Bolte 已提交
3758
        goto cleanup;
M
Matthias Bolte 已提交
3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772
    }

    result = resourcePoolResourceUsage->unreservedForVm->value;

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

    return result;
}



3773 3774 3775
static int
esxIsEncrypted(virConnectPtr conn)
{
M
Matthias Bolte 已提交
3776
    esxPrivate *priv = conn->privateData;
3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789

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



static int
esxIsSecure(virConnectPtr conn)
{
M
Matthias Bolte 已提交
3790
    esxPrivate *priv = conn->privateData;
3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803

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



static int
esxDomainIsActive(virDomainPtr domain)
{
M
Matthias Bolte 已提交
3804
    int result = -1;
M
Matthias Bolte 已提交
3805
    esxPrivate *priv = domain->conn->privateData;
3806 3807 3808 3809
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

3810
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3811
        return -1;
3812 3813
    }

3814
    if (esxVI_String_AppendValueToList(&propertyNameList,
3815
                                       "runtime.powerState") < 0 ||
3816
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
3817
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3818
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3819
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
3820
        goto cleanup;
3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846
    }

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



3847 3848
static virDomainSnapshotPtr
esxDomainSnapshotCreateXML(virDomainPtr domain, const char *xmlDesc,
3849
                           unsigned int flags)
3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860
{
    esxPrivate *priv = domain->conn->privateData;
    virDomainSnapshotDefPtr def = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
    virDomainSnapshotPtr snapshot = NULL;

3861 3862
    virCheckFlags(0, NULL);

3863
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3864
        return NULL;
3865 3866 3867 3868 3869
    }

    def = virDomainSnapshotDefParseString(xmlDesc, 1);

    if (def == NULL) {
M
Matthias Bolte 已提交
3870
        return NULL;
3871 3872 3873
    }

    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3874
          (priv->primary, domain->uuid, NULL, &virtualMachine,
3875
           priv->autoAnswer) < 0 ||
3876
        esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
3877 3878 3879 3880
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, def->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
3881
        goto cleanup;
3882 3883 3884 3885 3886
    }

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

3890
    if (esxVI_CreateSnapshot_Task(priv->primary, virtualMachine->obj,
3891 3892 3893
                                  def->name, def->description,
                                  esxVI_Boolean_True,
                                  esxVI_Boolean_False, &task) < 0 ||
3894
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3895
                                    esxVI_Occurrence_RequiredItem,
3896
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3897
        goto cleanup;
3898 3899 3900 3901
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not create snapshot"));
M
Matthias Bolte 已提交
3902
        goto cleanup;
3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919
    }

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

  cleanup:
    virDomainSnapshotDefFree(def);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);

    return snapshot;
}



static char *
esxDomainSnapshotDumpXML(virDomainSnapshotPtr snapshot,
3920
                         unsigned int flags)
3921 3922 3923 3924 3925 3926 3927 3928 3929
{
    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;

3930 3931
    virCheckFlags(0, NULL);

M
Matthias Bolte 已提交
3932
    memset(&def, 0, sizeof (def));
3933

3934
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3935
        return NULL;
3936 3937
    }

3938
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
3939 3940 3941 3942
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3943
        goto cleanup;
3944 3945 3946 3947 3948 3949 3950 3951
    }

    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 已提交
3952
        goto cleanup;
3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970
    }

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

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

    xml = virDomainSnapshotDefFormat(uuid_string, &def, 0);

  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return xml;
}



static int
3971
esxDomainSnapshotNum(virDomainPtr domain, unsigned int flags)
3972
{
M
Matthias Bolte 已提交
3973
    int count;
3974 3975 3976
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;

3977 3978
    virCheckFlags(0, -1);

3979
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3980
        return -1;
3981 3982
    }

3983
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
3984
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
3985
        return -1;
3986 3987
    }

M
Matthias Bolte 已提交
3988
    count = esxVI_GetNumberOfSnapshotTrees(rootSnapshotTreeList);
3989 3990 3991

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

M
Matthias Bolte 已提交
3992
    return count;
3993 3994 3995 3996 3997 3998
}



static int
esxDomainSnapshotListNames(virDomainPtr domain, char **names, int nameslen,
3999
                           unsigned int flags)
4000
{
M
Matthias Bolte 已提交
4001
    int result;
4002 4003 4004
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;

4005 4006
    virCheckFlags(0, -1);

4007 4008 4009 4010 4011 4012 4013 4014 4015
    if (names == NULL || nameslen < 0) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
    }

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

4016
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4017
        return -1;
4018 4019
    }

4020
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4021
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4022
        return -1;
4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035
    }

    result = esxVI_GetSnapshotTreeNames(rootSnapshotTreeList, names, nameslen);

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



static virDomainSnapshotPtr
esxDomainSnapshotLookupByName(virDomainPtr domain, const char *name,
4036
                              unsigned int flags)
4037 4038 4039 4040 4041 4042 4043
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    virDomainSnapshotPtr snapshot = NULL;

4044 4045
    virCheckFlags(0, NULL);

4046
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4047
        return NULL;
4048 4049
    }

4050
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073
                                         &rootSnapshotTreeList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotTreeList, name, &snapshotTree,
                                    &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    snapshot = virGetDomainSnapshot(domain, name);

  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return snapshot;
}



static int
esxDomainHasCurrentSnapshot(virDomainPtr domain, unsigned int flags)
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *currentSnapshotTree = NULL;

4074
    virCheckFlags(0, -1);
4075

4076
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4077
        return -1;
4078 4079
    }

4080
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4081 4082
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4083
        return -1;
4084 4085 4086
    }

    if (currentSnapshotTree != NULL) {
M
Matthias Bolte 已提交
4087 4088
        esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);
        return 1;
4089 4090
    }

M
Matthias Bolte 已提交
4091
    return 0;
4092 4093 4094 4095 4096 4097 4098 4099 4100
}



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

4103
    virCheckFlags(0, NULL);
4104

4105
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4106
        return NULL;
4107 4108
    }

4109
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4110 4111
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4112
        return NULL;
4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126
    }

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

    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return snapshot;
}



static int
esxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4127
    int result = -1;
4128 4129 4130 4131 4132 4133 4134
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

4135
    virCheckFlags(0, -1);
4136

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

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

4149
    if (esxVI_RevertToSnapshot_Task(priv->primary, snapshotTree->snapshot, NULL,
4150
                                    &task) < 0 ||
4151
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4152
                                    esxVI_Occurrence_RequiredItem,
4153
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
4154
        goto cleanup;
4155 4156 4157 4158 4159
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not revert to snapshot '%s'"), snapshot->name);
M
Matthias Bolte 已提交
4160
        goto cleanup;
4161 4162
    }

M
Matthias Bolte 已提交
4163 4164
    result = 0;

4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainSnapshotDelete(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4177
    int result = -1;
4178 4179 4180 4181 4182 4183 4184 4185
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    esxVI_Boolean removeChildren = esxVI_Boolean_False;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

4186 4187
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN, -1);

4188
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4189
        return -1;
4190 4191 4192 4193 4194 4195
    }

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

4196
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4197 4198 4199 4200
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4201
        goto cleanup;
4202 4203
    }

4204
    if (esxVI_RemoveSnapshot_Task(priv->primary, snapshotTree->snapshot,
4205
                                  removeChildren, &task) < 0 ||
4206
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4207
                                    esxVI_Occurrence_RequiredItem,
4208
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
4209
        goto cleanup;
4210 4211 4212 4213 4214
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not delete snapshot '%s'"), snapshot->name);
M
Matthias Bolte 已提交
4215
        goto cleanup;
4216 4217
    }

M
Matthias Bolte 已提交
4218 4219
    result = 0;

4220 4221 4222 4223 4224 4225 4226 4227 4228
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



4229 4230 4231 4232 4233 4234 4235 4236
static virDriver esxDriver = {
    VIR_DRV_ESX,
    "ESX",
    esxOpen,                         /* open */
    esxClose,                        /* close */
    esxSupportsFeature,              /* supports_feature */
    esxGetType,                      /* type */
    esxGetVersion,                   /* version */
4237
    NULL,                            /* libvirtVersion (impl. in libvirt.c) */
4238 4239 4240
    esxGetHostname,                  /* hostname */
    NULL,                            /* getMaxVcpus */
    esxNodeGetInfo,                  /* nodeGetInfo */
4241
    esxGetCapabilities,              /* getCapabilities */
4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267
    esxListDomains,                  /* listDomains */
    esxNumberOfDomains,              /* numOfDomains */
    NULL,                            /* domainCreateXML */
    esxDomainLookupByID,             /* domainLookupByID */
    esxDomainLookupByUUID,           /* domainLookupByUUID */
    esxDomainLookupByName,           /* domainLookupByName */
    esxDomainSuspend,                /* domainSuspend */
    esxDomainResume,                 /* domainResume */
    esxDomainShutdown,               /* domainShutdown */
    esxDomainReboot,                 /* domainReboot */
    esxDomainDestroy,                /* domainDestroy */
    esxDomainGetOSType,              /* domainGetOSType */
    esxDomainGetMaxMemory,           /* domainGetMaxMemory */
    esxDomainSetMaxMemory,           /* domainSetMaxMemory */
    esxDomainSetMemory,              /* domainSetMemory */
    esxDomainGetInfo,                /* domainGetInfo */
    NULL,                            /* domainSave */
    NULL,                            /* domainRestore */
    NULL,                            /* domainCoreDump */
    esxDomainSetVcpus,               /* domainSetVcpus */
    NULL,                            /* domainPinVcpu */
    NULL,                            /* domainGetVcpus */
    esxDomainGetMaxVcpus,            /* domainGetMaxVcpus */
    NULL,                            /* domainGetSecurityLabel */
    NULL,                            /* nodeGetSecurityModel */
    esxDomainDumpXML,                /* domainDumpXML */
4268
    esxDomainXMLFromNative,          /* domainXMLFromNative */
M
Matthias Bolte 已提交
4269
    esxDomainXMLToNative,            /* domainXMLToNative */
4270 4271 4272
    esxListDefinedDomains,           /* listDefinedDomains */
    esxNumberOfDefinedDomains,       /* numOfDefinedDomains */
    esxDomainCreate,                 /* domainCreate */
4273
    esxDomainCreateWithFlags,        /* domainCreateWithFlags */
M
Matthias Bolte 已提交
4274
    esxDomainDefineXML,              /* domainDefineXML */
4275
    esxDomainUndefine,               /* domainUndefine */
4276
    NULL,                            /* domainAttachDevice */
4277
    NULL,                            /* domainAttachDeviceFlags */
4278
    NULL,                            /* domainDetachDevice */
4279
    NULL,                            /* domainDetachDeviceFlags */
4280
    NULL,                            /* domainUpdateDeviceFlags */
4281 4282 4283 4284 4285 4286 4287 4288 4289 4290
    NULL,                            /* domainGetAutostart */
    NULL,                            /* domainSetAutostart */
    esxDomainGetSchedulerType,       /* domainGetSchedulerType */
    esxDomainGetSchedulerParameters, /* domainGetSchedulerParameters */
    esxDomainSetSchedulerParameters, /* domainSetSchedulerParameters */
    esxDomainMigratePrepare,         /* domainMigratePrepare */
    esxDomainMigratePerform,         /* domainMigratePerform */
    esxDomainMigrateFinish,          /* domainMigrateFinish */
    NULL,                            /* domainBlockStats */
    NULL,                            /* domainInterfaceStats */
4291
    NULL,                            /* domainMemoryStats */
4292 4293
    NULL,                            /* domainBlockPeek */
    NULL,                            /* domainMemoryPeek */
4294
    NULL,                            /* domainGetBlockInfo */
4295
    NULL,                            /* nodeGetCellsFreeMemory */
M
Matthias Bolte 已提交
4296
    esxNodeGetFreeMemory,            /* nodeGetFreeMemory */
4297 4298 4299 4300 4301 4302 4303
    NULL,                            /* domainEventRegister */
    NULL,                            /* domainEventDeregister */
    NULL,                            /* domainMigratePrepare2 */
    NULL,                            /* domainMigrateFinish2 */
    NULL,                            /* nodeDeviceDettach */
    NULL,                            /* nodeDeviceReAttach */
    NULL,                            /* nodeDeviceReset */
C
Chris Lalancette 已提交
4304
    NULL,                            /* domainMigratePrepareTunnel */
4305 4306 4307 4308
    esxIsEncrypted,                  /* isEncrypted */
    esxIsSecure,                     /* isSecure */
    esxDomainIsActive,               /* domainIsActive */
    esxDomainIsPersistent,           /* domainIsPersistent */
J
Jiri Denemark 已提交
4309
    NULL,                            /* cpuCompare */
4310
    NULL,                            /* cpuBaseline */
4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327
    NULL,                            /* domainGetJobInfo */
    NULL,                            /* domainAbortJob */
    NULL,                            /* domainMigrateSetMaxDowntime */
    NULL,                            /* domainEventRegisterAny */
    NULL,                            /* domainEventDeregisterAny */
    NULL,                            /* domainManagedSave */
    NULL,                            /* domainHasManagedSaveImage */
    NULL,                            /* domainManagedSaveRemove */
    esxDomainSnapshotCreateXML,      /* domainSnapshotCreateXML */
    esxDomainSnapshotDumpXML,        /* domainSnapshotDumpXML */
    esxDomainSnapshotNum,            /* domainSnapshotNum */
    esxDomainSnapshotListNames,      /* domainSnapshotListNames */
    esxDomainSnapshotLookupByName,   /* domainSnapshotLookupByName */
    esxDomainHasCurrentSnapshot,     /* domainHasCurrentSnapshot */
    esxDomainSnapshotCurrent,        /* domainSnapshotCurrent */
    esxDomainRevertToSnapshot,       /* domainRevertToSnapshot */
    esxDomainSnapshotDelete,         /* domainSnapshotDelete */
C
Chris Lalancette 已提交
4328
    NULL,                            /* qemuDomainMonitorCommand */
4329 4330 4331 4332 4333 4334 4335
};



int
esxRegister(void)
{
4336 4337 4338 4339 4340
    if (virRegisterDriver(&esxDriver) < 0 ||
        esxInterfaceRegister() < 0 ||
        esxNetworkRegister() < 0 ||
        esxStorageRegister() < 0 ||
        esxDeviceRegister() < 0 ||
M
Matthias Bolte 已提交
4341 4342
        esxSecretRegister() < 0 ||
        esxNWFilterRegister() < 0) {
4343 4344
        return -1;
    }
4345 4346 4347

    return 0;
}