esx_driver.c 169.7 KB
Newer Older
1 2

/*
3
 * esx_driver.c: core driver functions for managing VMware ESX hosts
4
 *
5
 * Copyright (C) 2010-2012 Red Hat, Inc.
6
 * Copyright (C) 2009-2012 Matthias Bolte <matthias.bolte@googlemail.com>
7 8 9 10 11 12 13 14 15 16 17 18 19
 * 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
20
 * License along with this library.  If not, see
O
Osier Yang 已提交
21
 * <http://www.gnu.org/licenses/>.
22 23 24 25 26 27 28
 *
 */

#include <config.h>

#include "internal.h"
#include "domain_conf.h"
29
#include "snapshot_conf.h"
30
#include "virauth.h"
31 32 33 34
#include "util.h"
#include "memory.h"
#include "logging.h"
#include "uuid.h"
35
#include "vmx.h"
36
#include "virtypedparam.h"
37
#include "esx_driver.h"
38 39 40 41 42
#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 已提交
43
#include "esx_nwfilter_driver.h"
44
#include "esx_private.h"
45 46 47
#include "esx_vi.h"
#include "esx_vi_methods.h"
#include "esx_util.h"
M
Martin Kletzander 已提交
48
#include "viruri.h"
49 50 51 52 53

#define VIR_FROM_THIS VIR_FROM_ESX

static int esxDomainGetMaxVcpus(virDomainPtr domain);

54 55 56 57
typedef struct _esxVMX_Data esxVMX_Data;

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



63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
static void
esxFreePrivate(esxPrivate **priv)
{
    if (priv == NULL || *priv == NULL) {
        return;
    }

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



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

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

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

173
            tmp = (char *)STRSKIP(fileName, hostMount->mountInfo->path);
174

175 176 177
            if (tmp == NULL) {
                continue;
            }
178

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

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

188
            tmp = strippedFileName;
189

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

196 197
                ++tmp;
            }
198

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

205 206
            break;
        }
207

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

214 215 216 217
            /* 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) {
218 219 220
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("File name '%s' doesn't have expected format "
                                 "'/vmfs/volumes/<datastore>/<path>'"), fileName);
221 222
                goto cleanup;
            }
223

224
            esxVI_ObjectContent_Free(&datastoreList);
225

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

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

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

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

        if (result == NULL) {
255 256
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not handle file name '%s'"), fileName);
257
            goto cleanup;
258
        }
259
    }
260

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

268
    return result;
269 270 271 272
}



273
/*
E
Eric Blake 已提交
274
 * This function does the inverse of esxParseVMXFileName. It takes a file name
275 276
 * in datastore path format or in absolute format and converts it to a file
 * name that can be used in a .vmx file.
277 278 279 280 281 282
 *
 * The datastore path format and the formats found in a .vmx file are described
 * in the documentation of esxParseVMXFileName.
 *
 * Firstly parse the datastore path. Then use the datastore name to lookup the
 * datastore and it's mount path. Finally concatenate the mount path, directory
E
Eric Blake 已提交
283
 * and file name to an absolute path and return it. Detect the separator type
284 285
 * based on the mount path.
 */
286
static char *
287
esxFormatVMXFileName(const char *fileName, void *opaque)
288 289
{
    bool success = false;
290
    char *result = NULL;
291
    esxVMX_Data *data = opaque;
292
    char *datastoreName = NULL;
293
    char *directoryAndFileName = NULL;
294 295 296 297 298
    esxVI_ObjectContent *datastore = NULL;
    esxVI_DatastoreHostMount *hostMount = NULL;
    char separator = '/';
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    char *tmp;
299
    size_t length;
300

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

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

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

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

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

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

331 332
        if (separator != '/') {
            tmp = directoryAndFileName;
333

334 335 336 337
            while (*tmp != '\0') {
                if (*tmp == '/') {
                    *tmp = separator;
                }
338

339 340
                ++tmp;
            }
341
        }
342

343 344
        virBufferAddChar(&buffer, separator);
        virBufferAdd(&buffer, directoryAndFileName, -1);
345

346 347 348 349 350 351 352 353 354 355 356 357
        if (virBufferError(&buffer)) {
            virReportOOMError();
            goto cleanup;
        }

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

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

    success = true;

  cleanup:
    if (! success) {
369
        virBufferFreeAndReset(&buffer);
370
        VIR_FREE(result);
371 372 373
    }

    VIR_FREE(datastoreName);
374
    VIR_FREE(directoryAndFileName);
375 376
    esxVI_ObjectContent_Free(&datastore);
    esxVI_DatastoreHostMount_Free(&hostMount);
377

378
    return result;
379 380 381 382 383 384 385 386 387 388
}



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

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

410
    vmDiskFileInfo = esxVI_VmDiskFileInfo_DynamicCast(fileInfo);
411 412

    if (vmDiskFileInfo == NULL || vmDiskFileInfo->controllerType == NULL) {
413 414
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not lookup controller model for '%s'"), def->src);
415 416 417 418 419
        goto cleanup;
    }

    if (STRCASEEQ(vmDiskFileInfo->controllerType,
                  "VirtualBusLogicController")) {
420
        *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_BUSLOGIC;
421 422
    } else if (STRCASEEQ(vmDiskFileInfo->controllerType,
                         "VirtualLsiLogicController")) {
423
        *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC;
424 425
    } else if (STRCASEEQ(vmDiskFileInfo->controllerType,
                         "VirtualLsiLogicSASController")) {
426
        *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSISAS1068;
427 428
    } else if (STRCASEEQ(vmDiskFileInfo->controllerType,
                         "ParaVirtualSCSIController")) {
429
        *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VMPVSCSI;
430
    } else {
431 432 433
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Found unexpected controller model '%s' for disk '%s'"),
                       vmDiskFileInfo->controllerType, def->src);
434 435 436 437 438 439
        goto cleanup;
    }

    result = 0;

  cleanup:
440
    esxVI_FileInfo_Free(&fileInfo);
441 442 443 444

    return result;
}

445 446


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

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

462
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
463
        return esxVI_Boolean_Undefined;
464 465
    }

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

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

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

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

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

                    break;
                }
            }

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

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

    return priv->supportsLongMode;
}



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

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

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "hardware.systemInfo.uuid") < 0 ||
542
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
543 544 545
                                         &hostSystem) < 0 ||
        esxVI_GetStringValue(hostSystem, "hardware.systemInfo.uuid",
                             &uuid_string, esxVI_Occurrence_RequiredItem) < 0) {
546 547 548
        goto cleanup;
    }

549 550 551
    if (strlen(uuid_string) > 0) {
        if (virUUIDParse(uuid_string, uuid) < 0) {
            VIR_WARN("Could not parse host UUID from string '%s'", uuid_string);
552

553 554
            /* HostSystem has an invalid UUID, ignore it */
            memset(uuid, 0, VIR_UUID_BUFLEN);
555
        }
556 557 558
    } else {
        /* HostSystem has an empty UUID */
        memset(uuid, 0, VIR_UUID_BUFLEN);
559 560 561 562 563 564 565 566 567 568 569 570
    }

    result = 0;

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

    return result;
}


571 572
static int esxDefaultConsoleType(const char *ostype ATTRIBUTE_UNUSED,
                                 const char *arch ATTRIBUTE_UNUSED)
573 574 575 576
{
    return VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL;
}

577

578
static virCapsPtr
579
esxCapsInit(esxPrivate *priv)
580
{
581
    esxVI_Boolean supportsLongMode = esxSupportsLongMode(priv);
582 583 584
    virCapsPtr caps = NULL;
    virCapsGuestPtr guest = NULL;

585 586 587 588 589 590 591 592 593
    if (supportsLongMode == esxVI_Boolean_Undefined) {
        return NULL;
    }

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

    if (caps == NULL) {
596
        virReportOOMError();
597 598 599
        return NULL;
    }

600
    virCapabilitiesSetMacPrefix(caps, (unsigned char[]){ 0x00, 0x0c, 0x29 });
601
    virCapabilitiesAddHostMigrateTransport(caps, "vpxmigr");
602

603
    caps->hasWideScsiBus = true;
604
    caps->defaultConsoleTargetType = esxDefaultConsoleType;
605

606 607 608 609
    if (esxLookupHostSystemBiosUuid(priv, caps->host.host_uuid) < 0) {
        goto failure;
    }

610 611 612
    /* i686 */
    guest = virCapabilitiesAddGuest(caps, "hvm", "i686", 32, NULL, NULL, 0,
                                    NULL);
613 614 615 616 617 618 619 620 621 622

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

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

623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
    /* x86_64 */
    if (supportsLongMode == esxVI_Boolean_True) {
        guest = virCapabilitiesAddGuest(caps, "hvm", "x86_64", 64, NULL, NULL,
                                        0, NULL);

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

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

638 639 640 641 642 643 644 645 646 647
    return caps;

  failure:
    virCapabilitiesFree(caps);

    return NULL;
}



648
static int
649 650
esxConnectToHost(virConnectPtr conn,
                 virConnectAuthPtr auth,
651 652 653 654 655
                 char **vCenterIpAddress)
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
M
Matthias Bolte 已提交
656
    char *unescapedPassword = NULL;
657 658 659 660 661
    char *password = NULL;
    char *url = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_Boolean inMaintenanceMode = esxVI_Boolean_Undefined;
662 663 664 665
    esxPrivate *priv = conn->privateData;
    esxVI_ProductVersion expectedProductVersion = STRCASEEQ(conn->uri->scheme, "esx")
        ? esxVI_ProductVersion_ESX
        : esxVI_ProductVersion_GSX;
666 667

    if (vCenterIpAddress == NULL || *vCenterIpAddress != NULL) {
668
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
669 670 671
        return -1;
    }

672
    if (esxUtil_ResolveHostname(conn->uri->server, ipAddress, NI_MAXHOST) < 0) {
673 674 675
        return -1;
    }

676 677
    if (conn->uri->user != NULL) {
        username = strdup(conn->uri->user);
678 679 680 681 682 683

        if (username == NULL) {
            virReportOOMError();
            goto cleanup;
        }
    } else {
684
        username = virAuthGetUsername(conn, auth, "esx", "root", conn->uri->server);
685 686

        if (username == NULL) {
687
            virReportError(VIR_ERR_AUTH_FAILED, "%s", _("Username request failed"));
688 689 690 691
            goto cleanup;
        }
    }

692
    unescapedPassword = virAuthGetPassword(conn, auth, "esx", username, conn->uri->server);
693

M
Matthias Bolte 已提交
694
    if (unescapedPassword == NULL) {
695
        virReportError(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
696 697 698
        goto cleanup;
    }

M
Matthias Bolte 已提交
699 700 701 702 703 704
    password = esxUtil_EscapeForXml(unescapedPassword);

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

705
    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->parsedUri->transport,
706
                    conn->uri->server, conn->uri->port) < 0) {
707 708 709 710 711 712
        virReportOOMError();
        goto cleanup;
    }

    if (esxVI_Context_Alloc(&priv->host) < 0 ||
        esxVI_Context_Connect(priv->host, url, ipAddress, username, password,
713
                              priv->parsedUri) < 0 ||
714
        esxVI_Context_LookupManagedObjects(priv->host) < 0) {
715 716 717 718 719
        goto cleanup;
    }

    if (expectedProductVersion == esxVI_ProductVersion_ESX) {
        if (priv->host->productVersion != esxVI_ProductVersion_ESX35 &&
M
Matthias Bolte 已提交
720 721
            priv->host->productVersion != esxVI_ProductVersion_ESX40 &&
            priv->host->productVersion != esxVI_ProductVersion_ESX41 &&
P
Patrice LACHANCE 已提交
722 723
            priv->host->productVersion != esxVI_ProductVersion_ESX4x &&
            priv->host->productVersion != esxVI_ProductVersion_ESX50 &&
M
Martin Kletzander 已提交
724
            priv->host->productVersion != esxVI_ProductVersion_ESX51 &&
P
Patrice LACHANCE 已提交
725
            priv->host->productVersion != esxVI_ProductVersion_ESX5x) {
726 727 728
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("%s is neither an ESX 3.5, 4.x nor 5.x host"),
                           conn->uri->server);
729 730 731 732
            goto cleanup;
        }
    } else { /* GSX */
        if (priv->host->productVersion != esxVI_ProductVersion_GSX20) {
733 734
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("%s isn't a GSX 2.0 host"), conn->uri->server);
735 736 737 738 739 740 741 742
            goto cleanup;
        }
    }

    /* Query the host for maintenance mode and vCenter IP address */
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "runtime.inMaintenanceMode\0"
                                           "summary.managementServerIp\0") < 0 ||
743 744
        esxVI_LookupHostSystemProperties(priv->host, propertyNameList,
                                         &hostSystem) < 0 ||
745 746 747 748 749 750 751 752 753 754 755
        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) {
756
        VIR_WARN("The server is in maintenance mode");
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
    }

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

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

    result = 0;

  cleanup:
    VIR_FREE(username);
M
Matthias Bolte 已提交
772 773
    VIR_FREE(unescapedPassword);
    VIR_FREE(password);
774 775 776 777 778 779 780 781 782 783
    VIR_FREE(url);
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



static int
784 785 786
esxConnectToVCenter(virConnectPtr conn,
                    virConnectAuthPtr auth,
                    const char *hostname,
787
                    const char *hostSystemIpAddress)
788 789 790 791
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
M
Matthias Bolte 已提交
792
    char *unescapedPassword = NULL;
793 794
    char *password = NULL;
    char *url = NULL;
795
    esxPrivate *priv = conn->privateData;
796

797
    if (hostSystemIpAddress == NULL &&
798
        (priv->parsedUri->path == NULL || STREQ(priv->parsedUri->path, "/"))) {
799 800
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Path has to specify the datacenter and compute resource"));
801 802 803
        return -1;
    }

804 805 806 807
    if (esxUtil_ResolveHostname(hostname, ipAddress, NI_MAXHOST) < 0) {
        return -1;
    }

808 809
    if (conn->uri->user != NULL) {
        username = strdup(conn->uri->user);
810 811 812 813 814 815

        if (username == NULL) {
            virReportOOMError();
            goto cleanup;
        }
    } else {
816
        username = virAuthGetUsername(conn, auth, "esx", "administrator", hostname);
817 818

        if (username == NULL) {
819
            virReportError(VIR_ERR_AUTH_FAILED, "%s", _("Username request failed"));
820 821 822 823
            goto cleanup;
        }
    }

824
    unescapedPassword = virAuthGetPassword(conn, auth, "esx", username, hostname);
825

M
Matthias Bolte 已提交
826
    if (unescapedPassword == NULL) {
827
        virReportError(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
828 829 830
        goto cleanup;
    }

M
Matthias Bolte 已提交
831 832 833 834 835 836
    password = esxUtil_EscapeForXml(unescapedPassword);

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

837
    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->parsedUri->transport,
838
                    hostname, conn->uri->port) < 0) {
839 840 841 842 843 844
        virReportOOMError();
        goto cleanup;
    }

    if (esxVI_Context_Alloc(&priv->vCenter) < 0 ||
        esxVI_Context_Connect(priv->vCenter, url, ipAddress, username,
845
                              password, priv->parsedUri) < 0) {
846 847 848 849
        goto cleanup;
    }

    if (priv->vCenter->productVersion != esxVI_ProductVersion_VPX25 &&
M
Matthias Bolte 已提交
850 851
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX40 &&
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX41 &&
P
Patrice LACHANCE 已提交
852 853
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX4x &&
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX50 &&
M
Martin Kletzander 已提交
854
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX51 &&
P
Patrice LACHANCE 已提交
855
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX5x) {
856 857 858
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("%s is neither a vCenter 2.5, 4.x nor 5.x server"),
                       hostname);
859 860 861
        goto cleanup;
    }

862
    if (hostSystemIpAddress != NULL) {
863 864
        if (esxVI_Context_LookupManagedObjectsByHostSystemIp
              (priv->vCenter, hostSystemIpAddress) < 0) {
865 866 867
            goto cleanup;
        }
    } else {
868 869
        if (esxVI_Context_LookupManagedObjectsByPath(priv->vCenter,
                                                     priv->parsedUri->path) < 0) {
870 871 872 873
            goto cleanup;
        }
    }

874 875 876 877
    result = 0;

  cleanup:
    VIR_FREE(username);
M
Matthias Bolte 已提交
878 879
    VIR_FREE(unescapedPassword);
    VIR_FREE(password);
880 881 882 883 884 885 886
    VIR_FREE(url);

    return result;
}



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

E
Eric Blake 已提交
942 943
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

944 945
    /* Decline if the URI is NULL or the scheme is NULL */
    if (conn->uri == NULL || conn->uri->scheme == NULL) {
946 947 948
        return VIR_DRV_OPEN_DECLINED;
    }

949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
    /* Decline if the scheme is not one of {vpx|esx|gsx} */
    plus = strchr(conn->uri->scheme, '+');

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

966 967 968
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Transport '%s' in URI scheme is not supported, try again "
                         "without the transport part"), plus + 1);
969 970 971
        return VIR_DRV_OPEN_ERROR;
    }

972 973 974 975 976 977
    if (STRCASENEQ(conn->uri->scheme, "vpx") &&
        conn->uri->path != NULL && STRNEQ(conn->uri->path, "/")) {
        VIR_WARN("Ignoring unexpected path '%s' for non-vpx scheme '%s'",
                 conn->uri->path, conn->uri->scheme);
    }

978 979
    /* Require server part */
    if (conn->uri->server == NULL) {
980 981
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("URI is missing the server part"));
982 983 984 985 986
        return VIR_DRV_OPEN_ERROR;
    }

    /* Require auth */
    if (auth == NULL || auth->cb == NULL) {
987 988
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Missing or invalid auth pointer"));
989
        return VIR_DRV_OPEN_ERROR;
990 991 992 993
    }

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

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

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

1007 1008
    conn->privateData = priv;

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

1032 1033 1034
    if (STRCASEEQ(conn->uri->scheme, "esx") ||
        STRCASEEQ(conn->uri->scheme, "gsx")) {
        /* Connect to host */
1035
        if (esxConnectToHost(conn, auth,
1036
                             &potentialVCenterIpAddress) < 0) {
M
Matthias Bolte 已提交
1037
            goto cleanup;
1038
        }
1039

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

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

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

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

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

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

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

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

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

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

1107
    VIR_FREE(potentialVCenterIpAddress);
1108

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



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

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

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

1134
    esxFreePrivate(&priv);
1135 1136 1137

    conn->privateData = NULL;

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



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

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

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

1157
    if (esxVI_String_AppendValueToList(&propertyNameList,
1158
                                       "capability.vmotionSupported") < 0 ||
1159
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
1160 1161
                                         &hostSystem) < 0 ||
        esxVI_GetBoolean(hostSystem, "capability.vmotionSupported",
1162 1163 1164
                         &priv->supportsVMotion,
                         esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
1165 1166 1167
    }

  cleanup:
M
Matthias Bolte 已提交
1168 1169 1170 1171
    /*
     * 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.
     */
1172 1173 1174
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
1175
    return priv->supportsVMotion;
1176 1177 1178 1179 1180 1181 1182
}



static int
esxSupportsFeature(virConnectPtr conn, int feature)
{
M
Matthias Bolte 已提交
1183
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1184
    esxVI_Boolean supportsVMotion = esxVI_Boolean_Undefined;
1185 1186 1187

    switch (feature) {
      case VIR_DRV_FEATURE_MIGRATION_V1:
1188
        supportsVMotion = esxSupportsVMotion(priv);
1189

M
Matthias Bolte 已提交
1190
        if (supportsVMotion == esxVI_Boolean_Undefined) {
1191 1192 1193
            return -1;
        }

M
Matthias Bolte 已提交
1194 1195 1196
        /* Migration is only possible via a vCenter and if VMotion is enabled */
        return priv->vCenter != NULL &&
               supportsVMotion == esxVI_Boolean_True ? 1 : 0;
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215

      default:
        return 0;
    }
}



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



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

1218
    if (virParseVersionString(priv->primary->service->about->version,
1219
                              version, false) < 0) {
1220 1221 1222
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not parse version number from '%s'"),
                       priv->primary->service->about->version);
1223

1224
        return -1;
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
    }

    return 0;
}



static char *
esxGetHostname(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1235
    esxPrivate *priv = conn->privateData;
1236 1237 1238 1239 1240 1241 1242
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    const char *hostName = NULL;
    const char *domainName = NULL;
    char *complete = NULL;

1243
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1244
        return NULL;
1245 1246 1247
    }

    if (esxVI_String_AppendValueListToList
1248
          (&propertyNameList,
1249 1250
           "config.network.dnsConfig.hostName\0"
           "config.network.dnsConfig.domainName\0") < 0 ||
1251 1252
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1253
        goto cleanup;
1254 1255 1256 1257 1258 1259
    }

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

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

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

M
Matthias Bolte 已提交
1279
    if (hostName == NULL || strlen(hostName) < 1) {
1280 1281
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing or empty 'hostName' property"));
M
Matthias Bolte 已提交
1282
        goto cleanup;
1283 1284
    }

M
Matthias Bolte 已提交
1285
    if (domainName == NULL || strlen(domainName) < 1) {
1286
        complete = strdup(hostName);
1287

1288
        if (complete == NULL) {
1289
            virReportOOMError();
M
Matthias Bolte 已提交
1290
            goto cleanup;
1291 1292 1293
        }
    } else {
        if (virAsprintf(&complete, "%s.%s", hostName, domainName) < 0) {
1294
            virReportOOMError();
M
Matthias Bolte 已提交
1295
            goto cleanup;
1296
        }
1297 1298 1299
    }

  cleanup:
M
Matthias Bolte 已提交
1300 1301 1302 1303 1304
    /*
     * 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
     */
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return complete;
}



static int
esxNodeGetInfo(virConnectPtr conn, virNodeInfoPtr nodeinfo)
{
M
Matthias Bolte 已提交
1316
    int result = -1;
M
Matthias Bolte 已提交
1317
    esxPrivate *priv = conn->privateData;
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
    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;

1329
    memset(nodeinfo, 0, sizeof(*nodeinfo));
1330

1331
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1332
        return -1;
1333 1334
    }

1335
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1336 1337 1338 1339 1340 1341 1342
                                           "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 ||
1343 1344
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1345
        goto cleanup;
1346 1347 1348 1349 1350
    }

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

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

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

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

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

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

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

            ptr = dynamicProperty->val->string;

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

                ++ptr;
            }

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

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

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

    return result;
}



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

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

    return xml;
}



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

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

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

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

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

        if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

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

        count++;

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

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

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

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



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

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

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



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

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

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

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

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

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

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

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

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

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

        domain->id = id;

        break;
    }

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

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

    return domain;
}



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

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

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

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

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

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

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

    return domain;
}



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

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

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

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

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

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

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

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

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

    return domain;
}



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

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

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

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

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

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

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

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

    return result;
}



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

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

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

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

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

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

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

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

    return result;
}



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

1859 1860
    virCheckFlags(0, -1);

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

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

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

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

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

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

    return result;
}


1894 1895 1896 1897 1898 1899
static int
esxDomainShutdown(virDomainPtr domain)
{
    return esxDomainShutdownFlags(domain, 0);
}

1900 1901

static int
E
Eric Blake 已提交
1902
esxDomainReboot(virDomainPtr domain, unsigned int flags)
1903
{
M
Matthias Bolte 已提交
1904
    int result = -1;
M
Matthias Bolte 已提交
1905
    esxPrivate *priv = domain->conn->privateData;
1906 1907 1908 1909
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

E
Eric Blake 已提交
1910 1911
    virCheckFlags(0, -1);

1912
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1913
        return -1;
1914 1915
    }

1916
    if (esxVI_String_AppendValueToList(&propertyNameList,
1917
                                       "runtime.powerState") < 0 ||
1918
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1919
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1920
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1921
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1922
        goto cleanup;
1923 1924 1925
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1926 1927
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1928
        goto cleanup;
1929 1930
    }

1931
    if (esxVI_RebootGuest(priv->primary, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1932
        goto cleanup;
1933 1934
    }

M
Matthias Bolte 已提交
1935 1936
    result = 0;

1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
1947 1948
esxDomainDestroyFlags(virDomainPtr domain,
                      unsigned int flags)
1949
{
M
Matthias Bolte 已提交
1950
    int result = -1;
M
Matthias Bolte 已提交
1951
    esxPrivate *priv = domain->conn->privateData;
1952
    esxVI_Context *ctx = NULL;
1953 1954 1955 1956 1957
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1958
    char *taskInfoErrorMessage = NULL;
1959

1960 1961
    virCheckFlags(0, -1);

1962 1963 1964 1965 1966 1967
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

1968
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
1969
        return -1;
1970 1971
    }

1972
    if (esxVI_String_AppendValueToList(&propertyNameList,
1973
                                       "runtime.powerState") < 0 ||
1974
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1975
          (ctx, domain->uuid, propertyNameList, &virtualMachine,
1976
           priv->parsedUri->autoAnswer) < 0 ||
1977
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1978
        goto cleanup;
1979 1980 1981
    }

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

1987
    if (esxVI_PowerOffVM_Task(ctx, virtualMachine->obj, &task) < 0 ||
1988 1989
        esxVI_WaitForTaskCompletion(ctx, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
1990
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1991
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1992
        goto cleanup;
1993 1994 1995
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1996 1997
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not destroy domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
1998
        goto cleanup;
1999 2000
    }

2001
    domain->id = -1;
M
Matthias Bolte 已提交
2002 2003
    result = 0;

2004 2005 2006 2007
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
2008
    VIR_FREE(taskInfoErrorMessage);
2009 2010 2011 2012 2013

    return result;
}


2014 2015 2016 2017 2018 2019
static int
esxDomainDestroy(virDomainPtr dom)
{
    return esxDomainDestroyFlags(dom, 0);
}

2020 2021

static char *
2022
esxDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED)
2023
{
2024 2025 2026
    char *osType = strdup("hvm");

    if (osType == NULL) {
2027
        virReportOOMError();
2028 2029 2030 2031
        return NULL;
    }

    return osType;
2032 2033 2034 2035
}



2036
static unsigned long long
2037 2038
esxDomainGetMaxMemory(virDomainPtr domain)
{
M
Matthias Bolte 已提交
2039
    esxPrivate *priv = domain->conn->privateData;
2040 2041 2042 2043 2044
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    unsigned long memoryMB = 0;

2045
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2046
        return 0;
2047 2048
    }

2049
    if (esxVI_String_AppendValueToList(&propertyNameList,
2050
                                       "config.hardware.memoryMB") < 0 ||
2051
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2052
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2053
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2054
        goto cleanup;
2055 2056 2057 2058 2059
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2060
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2061
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2062
                goto cleanup;
2063 2064 2065
            }

            if (dynamicProperty->val->int32 < 0) {
2066 2067 2068
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Got invalid memory size %d"),
                               dynamicProperty->val->int32);
2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090
            } 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 已提交
2091
    int result = -1;
M
Matthias Bolte 已提交
2092
    esxPrivate *priv = domain->conn->privateData;
2093
    esxVI_String *propertyNameList = NULL;
2094
    esxVI_ObjectContent *virtualMachine = NULL;
2095
    esxVI_VirtualMachinePowerState powerState;
2096 2097 2098
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2099
    char *taskInfoErrorMessage = NULL;
2100

2101
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2102
        return -1;
2103 2104
    }

2105 2106 2107 2108
    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "runtime.powerState") < 0 ||
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
2109
           priv->parsedUri->autoAnswer) < 0 ||
2110 2111 2112 2113 2114
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2115 2116
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered off"));
2117 2118 2119 2120
        goto cleanup;
    }

    if (esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
2121
        esxVI_Long_Alloc(&spec->memoryMB) < 0) {
M
Matthias Bolte 已提交
2122
        goto cleanup;
2123 2124
    }

2125
    /* max-memory must be a multiple of 4096 kilobyte */
2126
    spec->memoryMB->value =
2127
      VIR_DIV_UP(memory, 4096) * 4; /* Scale from kilobytes to megabytes */
2128

2129
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2130
                              &task) < 0 ||
2131
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2132
                                    esxVI_Occurrence_RequiredItem,
2133
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2134
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2135
        goto cleanup;
2136 2137 2138
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2139 2140 2141
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set max-memory to %lu kilobytes: %s"), memory,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2142
        goto cleanup;
2143 2144
    }

M
Matthias Bolte 已提交
2145 2146
    result = 0;

2147
  cleanup:
2148
    esxVI_String_Free(&propertyNameList);
2149 2150 2151
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2152
    VIR_FREE(taskInfoErrorMessage);
2153 2154 2155 2156 2157 2158 2159 2160 2161

    return result;
}



static int
esxDomainSetMemory(virDomainPtr domain, unsigned long memory)
{
M
Matthias Bolte 已提交
2162
    int result = -1;
M
Matthias Bolte 已提交
2163
    esxPrivate *priv = domain->conn->privateData;
2164 2165 2166 2167
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2168
    char *taskInfoErrorMessage = NULL;
2169

2170
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2171
        return -1;
2172 2173
    }

2174
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2175
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2176
           priv->parsedUri->autoAnswer) < 0 ||
2177 2178 2179
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0 ||
        esxVI_Long_Alloc(&spec->memoryAllocation->limit) < 0) {
M
Matthias Bolte 已提交
2180
        goto cleanup;
2181 2182 2183
    }

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

2186
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2187
                              &task) < 0 ||
2188
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2189
                                    esxVI_Occurrence_RequiredItem,
2190
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2191
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2192
        goto cleanup;
2193 2194 2195
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2196 2197 2198
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set memory to %lu kilobytes: %s"), memory,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2199
        goto cleanup;
2200 2201
    }

M
Matthias Bolte 已提交
2202 2203
    result = 0;

2204 2205 2206 2207
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2208
    VIR_FREE(taskInfoErrorMessage);
2209 2210 2211 2212 2213 2214

    return result;
}



2215 2216 2217 2218 2219 2220 2221 2222 2223
/*
 * libvirt exposed virtual CPU usage in absolute time, ESX doesn't provide this
 * information in this format. It exposes it in 20 seconds slots, but it's hard
 * to get a reliable absolute time from this. Therefore, disable the code that
 * queries the performance counters here for now, but keep it as example for how
 * to query a selected performance counter for its values.
 */
#define ESX_QUERY_FOR_USED_CPU_TIME 0

2224 2225 2226
static int
esxDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info)
{
M
Matthias Bolte 已提交
2227
    int result = -1;
M
Matthias Bolte 已提交
2228
    esxPrivate *priv = domain->conn->privateData;
2229 2230 2231 2232 2233
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int64_t memory_limit = -1;
2234
#if ESX_QUERY_FOR_USED_CPU_TIME
2235 2236 2237 2238 2239 2240 2241
    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;
2242 2243
    esxVI_PerfEntityMetricBase *perfEntityMetricBase = NULL;
    esxVI_PerfEntityMetricBase *perfEntityMetricBaseList = NULL;
2244 2245 2246
    esxVI_PerfEntityMetric *perfEntityMetric = NULL;
    esxVI_PerfMetricIntSeries *perfMetricIntSeries = NULL;
    esxVI_Long *value = NULL;
2247
#endif
2248

2249
    memset(info, 0, sizeof(*info));
M
Matthias Bolte 已提交
2250

2251
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2252
        return -1;
2253 2254
    }

2255
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2256 2257 2258 2259
                                           "runtime.powerState\0"
                                           "config.hardware.memoryMB\0"
                                           "config.hardware.numCPU\0"
                                           "config.memoryAllocation.limit\0") < 0 ||
2260
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2261
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2262
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2263
        goto cleanup;
2264 2265 2266 2267 2268 2269 2270 2271
    }

    info->state = VIR_DOMAIN_NOSTATE;

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

2276 2277
            info->state = esxVI_VirtualMachinePowerState_ConvertToLibvirt
                            (powerState);
2278
        } else if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2279
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2280
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2281
                goto cleanup;
2282 2283 2284 2285
            }

            info->maxMem = dynamicProperty->val->int32 * 1024; /* Scale from megabyte to kilobyte */
        } else if (STREQ(dynamicProperty->name, "config.hardware.numCPU")) {
2286
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2287
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2288
                goto cleanup;
2289 2290 2291 2292 2293
            }

            info->nrVirtCpu = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "config.memoryAllocation.limit")) {
2294
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2295
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
2296
                goto cleanup;
2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311
            }

            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;

2312
#if ESX_QUERY_FOR_USED_CPU_TIME
2313
    /* Verify the cached 'used CPU time' performance counter ID */
2314 2315 2316 2317 2318 2319
    /* 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;
            }
2320

2321
            counterId->value = priv->usedCpuTimeCounterId;
2322

2323 2324 2325
            if (esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                goto cleanup;
            }
2326

2327 2328 2329 2330
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfo) < 0) {
                goto cleanup;
            }
2331

2332 2333 2334 2335 2336
            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);
2337

2338 2339 2340 2341 2342
                priv->usedCpuTimeCounterId = -1;
            }

            esxVI_Int_Free(&counterIdList);
            esxVI_PerfCounterInfo_Free(&perfCounterInfo);
2343 2344
        }

2345 2346 2347 2348 2349 2350 2351 2352 2353 2354
        /*
         * 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;
            }
2355

2356 2357 2358 2359
            for (perfMetricId = perfMetricIdList; perfMetricId != NULL;
                 perfMetricId = perfMetricId->_next) {
                VIR_DEBUG("perfMetricId counterId %d, instance '%s'",
                          perfMetricId->counterId->value, perfMetricId->instance);
2360

2361
                counterId = NULL;
2362

2363 2364 2365 2366 2367
                if (esxVI_Int_DeepCopy(&counterId, perfMetricId->counterId) < 0 ||
                    esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                    goto cleanup;
                }
            }
2368

2369 2370
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfoList) < 0) {
M
Matthias Bolte 已提交
2371
                goto cleanup;
2372 2373
            }

2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390
            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;
                }
2391 2392
            }

2393
            if (priv->usedCpuTimeCounterId < 0) {
2394
                VIR_WARN("Could not find 'used CPU time' performance counter");
2395
            }
2396 2397
        }

2398 2399 2400 2401 2402 2403
        /*
         * 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);
2404

2405 2406 2407 2408 2409 2410
            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;
            }
2411

2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
            querySpec->entity = virtualMachine->obj;
            querySpec->maxSample->value = 1;
            querySpec->metricId->counterId->value = priv->usedCpuTimeCounterId;
            querySpec->metricId->instance = (char *)"";
            querySpec->format = (char *)"normal";

            if (esxVI_QueryPerf(priv->host, querySpec,
                                &perfEntityMetricBaseList) < 0) {
                goto cleanup;
            }
2422

2423 2424 2425
            for (perfEntityMetricBase = perfEntityMetricBaseList;
                 perfEntityMetricBase != NULL;
                 perfEntityMetricBase = perfEntityMetricBase->_next) {
2426
                VIR_DEBUG("perfEntityMetric ...");
2427

2428 2429
                perfEntityMetric =
                  esxVI_PerfEntityMetric_DynamicCast(perfEntityMetricBase);
2430

2431
                if (perfEntityMetric == NULL) {
2432 2433 2434
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("QueryPerf returned object with unexpected type '%s'"),
                                   esxVI_Type_ToString(perfEntityMetricBase->_type));
2435
                    goto cleanup;
2436
                }
2437

2438 2439
                perfMetricIntSeries =
                  esxVI_PerfMetricIntSeries_DynamicCast(perfEntityMetric->value);
2440

2441
                if (perfMetricIntSeries == NULL) {
2442 2443 2444
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("QueryPerf returned object with unexpected type '%s'"),
                                   esxVI_Type_ToString(perfEntityMetric->value->_type));
2445
                    goto cleanup;
2446
                }
2447

2448 2449
                for (; perfMetricIntSeries != NULL;
                     perfMetricIntSeries = perfMetricIntSeries->_next) {
2450
                    VIR_DEBUG("perfMetricIntSeries ...");
2451

2452 2453 2454 2455 2456
                    for (value = perfMetricIntSeries->value;
                         value != NULL;
                         value = value->_next) {
                        VIR_DEBUG("value %lld", (long long int)value->value);
                    }
2457 2458 2459
                }
            }

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

2462
            /*
E
Eric Blake 已提交
2463
             * FIXME: Cannot map between relative used-cpu-time and absolute
2464 2465 2466
             *        info->cpuTime
             */
        }
2467
    }
2468
#endif
2469

M
Matthias Bolte 已提交
2470 2471
    result = 0;

2472
  cleanup:
2473
#if ESX_QUERY_FOR_USED_CPU_TIME
2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485
    /*
     * Remove values owned by data structures to prevent them from being freed
     * by the call to esxVI_PerfQuerySpec_Free().
     */
    if (querySpec != NULL) {
        querySpec->entity = NULL;
        querySpec->format = NULL;

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

2488 2489
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2490
#if ESX_QUERY_FOR_USED_CPU_TIME
2491 2492 2493 2494
    esxVI_PerfMetricId_Free(&perfMetricIdList);
    esxVI_Int_Free(&counterIdList);
    esxVI_PerfCounterInfo_Free(&perfCounterInfoList);
    esxVI_PerfQuerySpec_Free(&querySpec);
2495
    esxVI_PerfEntityMetricBase_Free(&perfEntityMetricBaseList);
2496
#endif
2497 2498 2499 2500 2501 2502

    return result;
}



2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545
static int
esxDomainGetState(virDomainPtr domain,
                  int *state,
                  int *reason,
                  unsigned int flags)
{
    int result = -1;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;

    virCheckFlags(0, -1);

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

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

    *state = esxVI_VirtualMachinePowerState_ConvertToLibvirt(powerState);

    if (reason)
        *reason = 0;

    result = 0;

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

    return result;
}



2546
static int
2547 2548
esxDomainSetVcpusFlags(virDomainPtr domain, unsigned int nvcpus,
                       unsigned int flags)
2549
{
M
Matthias Bolte 已提交
2550
    int result = -1;
M
Matthias Bolte 已提交
2551
    esxPrivate *priv = domain->conn->privateData;
M
Matthias Bolte 已提交
2552
    int maxVcpus;
2553 2554 2555 2556
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2557
    char *taskInfoErrorMessage = NULL;
2558

2559
    if (flags != VIR_DOMAIN_AFFECT_LIVE) {
2560
        virReportError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
2561 2562 2563
        return -1;
    }

2564
    if (nvcpus < 1) {
2565 2566
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Requested number of virtual CPUs must at least be 1"));
M
Matthias Bolte 已提交
2567
        return -1;
2568 2569
    }

2570
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2571
        return -1;
2572 2573
    }

M
Matthias Bolte 已提交
2574
    maxVcpus = esxDomainGetMaxVcpus(domain);
2575

M
Matthias Bolte 已提交
2576
    if (maxVcpus < 0) {
M
Matthias Bolte 已提交
2577
        return -1;
2578 2579
    }

M
Matthias Bolte 已提交
2580
    if (nvcpus > maxVcpus) {
2581 2582 2583 2584
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Requested number of virtual CPUs is greater than max "
                         "allowable number of virtual CPUs for the domain: %d > %d"),
                       nvcpus, maxVcpus);
M
Matthias Bolte 已提交
2585
        return -1;
2586 2587
    }

2588
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2589
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2590
           priv->parsedUri->autoAnswer) < 0 ||
2591 2592
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Int_Alloc(&spec->numCPUs) < 0) {
M
Matthias Bolte 已提交
2593
        goto cleanup;
2594 2595 2596 2597
    }

    spec->numCPUs->value = nvcpus;

2598
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2599
                              &task) < 0 ||
2600
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2601
                                    esxVI_Occurrence_RequiredItem,
2602
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2603
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2604
        goto cleanup;
2605 2606 2607
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2608 2609 2610
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set number of virtual CPUs to %d: %s"), nvcpus,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2611
        goto cleanup;
2612 2613
    }

M
Matthias Bolte 已提交
2614 2615
    result = 0;

2616 2617 2618 2619
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2620
    VIR_FREE(taskInfoErrorMessage);
2621 2622 2623 2624 2625

    return result;
}


M
Matthias Bolte 已提交
2626

2627 2628 2629
static int
esxDomainSetVcpus(virDomainPtr domain, unsigned int nvcpus)
{
2630
    return esxDomainSetVcpusFlags(domain, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
2631 2632
}

2633

M
Matthias Bolte 已提交
2634

2635
static int
2636
esxDomainGetVcpusFlags(virDomainPtr domain, unsigned int flags)
2637
{
M
Matthias Bolte 已提交
2638
    esxPrivate *priv = domain->conn->privateData;
2639 2640 2641 2642
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

2643
    if (flags != (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_VCPU_MAXIMUM)) {
2644
        virReportError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
2645 2646 2647
        return -1;
    }

M
Matthias Bolte 已提交
2648 2649
    if (priv->maxVcpus > 0) {
        return priv->maxVcpus;
2650 2651
    }

M
Matthias Bolte 已提交
2652 2653
    priv->maxVcpus = -1;

2654
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2655
        return -1;
2656 2657
    }

2658
    if (esxVI_String_AppendValueToList(&propertyNameList,
2659
                                       "capability.maxSupportedVcpus") < 0 ||
2660 2661
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
2662
        goto cleanup;
2663 2664 2665 2666 2667
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "capability.maxSupportedVcpus")) {
2668
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2669
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2670
                goto cleanup;
2671 2672
            }

M
Matthias Bolte 已提交
2673
            priv->maxVcpus = dynamicProperty->val->int32;
2674 2675 2676 2677 2678 2679 2680 2681 2682 2683
            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

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

M
Matthias Bolte 已提交
2684
    return priv->maxVcpus;
2685 2686
}

M
Matthias Bolte 已提交
2687 2688


2689 2690 2691
static int
esxDomainGetMaxVcpus(virDomainPtr domain)
{
2692
    return esxDomainGetVcpusFlags(domain, (VIR_DOMAIN_AFFECT_LIVE |
2693 2694
                                           VIR_DOMAIN_VCPU_MAXIMUM));
}
2695

M
Matthias Bolte 已提交
2696 2697


2698
static char *
2699
esxDomainGetXMLDesc(virDomainPtr domain, unsigned int flags)
2700
{
M
Matthias Bolte 已提交
2701
    esxPrivate *priv = domain->conn->privateData;
2702 2703
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
2704 2705
    esxVI_VirtualMachinePowerState powerState;
    int id;
2706
    char *vmPathName = NULL;
2707
    char *datastoreName = NULL;
M
Matthias Bolte 已提交
2708
    char *directoryName = NULL;
2709
    char *directoryAndFileName = NULL;
2710
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
2711 2712
    char *url = NULL;
    char *vmx = NULL;
2713
    virVMXContext ctx;
2714
    esxVMX_Data data;
2715 2716 2717
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2718 2719
    /* Flags checked by virDomainDefFormat */

2720
    memset(&data, 0, sizeof(data));
2721

2722
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2723
        return NULL;
2724 2725
    }

2726 2727 2728
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "config.files.vmPathName\0"
                                           "runtime.powerState\0") < 0 ||
2729
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2730
                                         propertyNameList, &virtualMachine,
2731
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2732 2733
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0 ||
2734 2735
        esxVI_GetStringValue(virtualMachine, "config.files.vmPathName",
                             &vmPathName, esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2736
        goto cleanup;
2737 2738
    }

2739
    if (esxUtil_ParseDatastorePath(vmPathName, &datastoreName, &directoryName,
2740
                                   &directoryAndFileName) < 0) {
M
Matthias Bolte 已提交
2741
        goto cleanup;
2742 2743
    }

2744
    virBufferAsprintf(&buffer, "%s://%s:%d/folder/", priv->parsedUri->transport,
2745
                      domain->conn->uri->server, domain->conn->uri->port);
2746
    virBufferURIEncodeString(&buffer, directoryAndFileName);
2747
    virBufferAddLit(&buffer, "?dcPath=");
2748
    virBufferURIEncodeString(&buffer, priv->primary->datacenterPath);
2749 2750 2751 2752
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
2753
        virReportOOMError();
M
Matthias Bolte 已提交
2754
        goto cleanup;
2755 2756
    }

2757 2758
    url = virBufferContentAndReset(&buffer);

2759
    if (esxVI_CURL_Download(priv->primary->curl, url, &vmx, 0, NULL) < 0) {
M
Matthias Bolte 已提交
2760
        goto cleanup;
2761 2762
    }

2763
    data.ctx = priv->primary;
2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777

    if (directoryName == NULL) {
        if (virAsprintf(&data.datastorePathWithoutFileName, "[%s]",
                        datastoreName) < 0) {
            virReportOOMError();
            goto cleanup;
        }
    } else {
        if (virAsprintf(&data.datastorePathWithoutFileName, "[%s] %s",
                        datastoreName, directoryName) < 0) {
            virReportOOMError();
            goto cleanup;
        }
    }
2778 2779 2780 2781 2782 2783

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

2784
    def = virVMXParseConfig(&ctx, priv->caps, vmx);
2785 2786

    if (def != NULL) {
2787 2788 2789 2790
        if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
            def->id = id;
        }

2791
        xml = virDomainDefFormat(def, flags);
2792 2793 2794
    }

  cleanup:
M
Matthias Bolte 已提交
2795 2796 2797 2798
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

2799 2800
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2801
    VIR_FREE(datastoreName);
M
Matthias Bolte 已提交
2802
    VIR_FREE(directoryName);
2803
    VIR_FREE(directoryAndFileName);
2804
    VIR_FREE(url);
2805
    VIR_FREE(data.datastorePathWithoutFileName);
2806
    VIR_FREE(vmx);
2807
    virDomainDefFree(def);
2808 2809 2810 2811 2812 2813 2814 2815 2816

    return xml;
}



static char *
esxDomainXMLFromNative(virConnectPtr conn, const char *nativeFormat,
                       const char *nativeConfig,
E
Eric Blake 已提交
2817
                       unsigned int flags)
2818
{
M
Matthias Bolte 已提交
2819
    esxPrivate *priv = conn->privateData;
2820
    virVMXContext ctx;
2821
    esxVMX_Data data;
2822 2823 2824
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2825 2826
    virCheckFlags(0, NULL);

2827
    memset(&data, 0, sizeof(data));
2828

2829
    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2830 2831
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Unsupported config format '%s'"), nativeFormat);
2832
        return NULL;
2833 2834
    }

2835
    data.ctx = priv->primary;
2836
    data.datastorePathWithoutFileName = (char *)"[?] ?";
2837 2838 2839 2840 2841 2842

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

2843
    def = virVMXParseConfig(&ctx, priv->caps, nativeConfig);
2844 2845

    if (def != NULL) {
2846
        xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
2847 2848 2849 2850 2851 2852 2853 2854 2855
    }

    virDomainDefFree(def);

    return xml;
}



M
Matthias Bolte 已提交
2856 2857 2858
static char *
esxDomainXMLToNative(virConnectPtr conn, const char *nativeFormat,
                     const char *domainXml,
E
Eric Blake 已提交
2859
                     unsigned int flags)
M
Matthias Bolte 已提交
2860
{
M
Matthias Bolte 已提交
2861
    esxPrivate *priv = conn->privateData;
2862 2863
    int virtualHW_version;
    virVMXContext ctx;
2864
    esxVMX_Data data;
M
Matthias Bolte 已提交
2865 2866 2867
    virDomainDefPtr def = NULL;
    char *vmx = NULL;

E
Eric Blake 已提交
2868 2869
    virCheckFlags(0, NULL);

2870
    memset(&data, 0, sizeof(data));
2871

M
Matthias Bolte 已提交
2872
    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2873 2874
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Unsupported config format '%s'"), nativeFormat);
M
Matthias Bolte 已提交
2875 2876 2877
        return NULL;
    }

2878 2879 2880 2881 2882 2883 2884
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        return NULL;
    }

M
Matthias Bolte 已提交
2885 2886
    def = virDomainDefParseString(priv->caps, domainXml,
                                  1 << VIR_DOMAIN_VIRT_VMWARE, 0);
M
Matthias Bolte 已提交
2887 2888 2889 2890 2891

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

2892
    data.ctx = priv->primary;
2893
    data.datastorePathWithoutFileName = NULL;
2894 2895 2896 2897 2898 2899

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

2900
    vmx = virVMXFormatConfig(&ctx, priv->caps, def, virtualHW_version);
M
Matthias Bolte 已提交
2901 2902 2903 2904 2905 2906 2907 2908

    virDomainDefFree(def);

    return vmx;
}



2909 2910 2911
static int
esxListDefinedDomains(virConnectPtr conn, char **const names, int maxnames)
{
M
Matthias Bolte 已提交
2912
    bool success = false;
M
Matthias Bolte 已提交
2913
    esxPrivate *priv = conn->privateData;
2914 2915 2916 2917 2918
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;
2919
    int i;
2920 2921 2922 2923 2924

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

2925
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2926
        return -1;
2927 2928
    }

2929
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2930 2931
                                           "name\0"
                                           "runtime.powerState\0") < 0 ||
2932 2933
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2934
        goto cleanup;
2935 2936 2937 2938
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
2939
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
2940
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
2941
            goto cleanup;
2942 2943 2944 2945 2946 2947
        }

        if (powerState == esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

2948
        names[count] = NULL;
2949

2950 2951 2952
        if (esxVI_GetVirtualMachineIdentity(virtualMachine, NULL, &names[count],
                                            NULL) < 0) {
            goto cleanup;
2953 2954
        }

2955 2956
        ++count;

2957 2958 2959 2960 2961
        if (count >= maxnames) {
            break;
        }
    }

M
Matthias Bolte 已提交
2962
    success = true;
2963

M
Matthias Bolte 已提交
2964 2965 2966 2967 2968
  cleanup:
    if (! success) {
        for (i = 0; i < count; ++i) {
            VIR_FREE(names[i]);
        }
2969

M
Matthias Bolte 已提交
2970
        count = -1;
2971 2972
    }

M
Matthias Bolte 已提交
2973 2974
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
2975

M
Matthias Bolte 已提交
2976
    return count;
2977 2978 2979 2980 2981 2982 2983
}



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

2986
    if (esxVI_EnsureSession(priv->primary) < 0) {
2987 2988 2989
        return -1;
    }

2990
    return esxVI_LookupNumberOfDomainsByPowerState
2991
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, true);
2992 2993 2994 2995 2996
}



static int
2997
esxDomainCreateWithFlags(virDomainPtr domain, unsigned int flags)
2998
{
M
Matthias Bolte 已提交
2999
    int result = -1;
M
Matthias Bolte 已提交
3000
    esxPrivate *priv = domain->conn->privateData;
3001 3002 3003
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
3004
    int id = -1;
3005 3006
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3007
    char *taskInfoErrorMessage = NULL;
3008

3009 3010
    virCheckFlags(0, -1);

3011
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3012
        return -1;
3013 3014
    }

3015
    if (esxVI_String_AppendValueToList(&propertyNameList,
3016
                                       "runtime.powerState") < 0 ||
3017
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3018
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
3019
           priv->parsedUri->autoAnswer) < 0 ||
3020 3021
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0) {
M
Matthias Bolte 已提交
3022
        goto cleanup;
3023 3024 3025
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
3026 3027
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered off"));
M
Matthias Bolte 已提交
3028
        goto cleanup;
3029 3030
    }

3031
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
3032
                             &task) < 0 ||
3033
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3034
                                    esxVI_Occurrence_RequiredItem,
3035
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3036
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3037
        goto cleanup;
3038 3039 3040
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3041 3042
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not start domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3043
        goto cleanup;
3044 3045
    }

3046
    domain->id = id;
M
Matthias Bolte 已提交
3047 3048
    result = 0;

3049 3050 3051 3052
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
3053
    VIR_FREE(taskInfoErrorMessage);
3054 3055 3056 3057

    return result;
}

3058 3059


3060 3061 3062 3063 3064
static int
esxDomainCreate(virDomainPtr domain)
{
    return esxDomainCreateWithFlags(domain, 0);
}
3065

3066 3067


M
Matthias Bolte 已提交
3068
static virDomainPtr
3069
esxDomainDefineXML(virConnectPtr conn, const char *xml)
M
Matthias Bolte 已提交
3070
{
M
Matthias Bolte 已提交
3071
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
3072 3073
    virDomainDefPtr def = NULL;
    char *vmx = NULL;
3074 3075
    int i;
    virDomainDiskDefPtr disk = NULL;
M
Matthias Bolte 已提交
3076
    esxVI_ObjectContent *virtualMachine = NULL;
3077 3078
    int virtualHW_version;
    virVMXContext ctx;
3079
    esxVMX_Data data;
M
Matthias Bolte 已提交
3080 3081
    char *datastoreName = NULL;
    char *directoryName = NULL;
3082
    char *escapedName = NULL;
M
Matthias Bolte 已提交
3083 3084 3085 3086 3087 3088 3089 3090
    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;
3091
    char *taskInfoErrorMessage = NULL;
M
Matthias Bolte 已提交
3092 3093
    virDomainPtr domain = NULL;

3094
    memset(&data, 0, sizeof(data));
3095

3096
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3097
        return NULL;
M
Matthias Bolte 已提交
3098 3099 3100
    }

    /* Parse domain XML */
M
Matthias Bolte 已提交
3101
    def = virDomainDefParseString(priv->caps, xml, 1 << VIR_DOMAIN_VIRT_VMWARE,
M
Matthias Bolte 已提交
3102 3103 3104
                                  VIR_DOMAIN_XML_INACTIVE);

    if (def == NULL) {
M
Matthias Bolte 已提交
3105
        return NULL;
M
Matthias Bolte 已提交
3106 3107 3108
    }

    /* Check if an existing domain should be edited */
3109
    if (esxVI_LookupVirtualMachineByUuid(priv->primary, def->uuid, NULL,
M
Matthias Bolte 已提交
3110
                                         &virtualMachine,
M
Matthias Bolte 已提交
3111
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
3112
        goto cleanup;
M
Matthias Bolte 已提交
3113 3114
    }

3115 3116 3117 3118 3119 3120 3121
    if (virtualMachine == NULL &&
        esxVI_LookupVirtualMachineByName(priv->primary, def->name, NULL,
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
    }

M
Matthias Bolte 已提交
3122 3123
    if (virtualMachine != NULL) {
        /* FIXME */
3124 3125 3126
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Domain already exists, editing existing domains is not "
                         "supported yet"));
M
Matthias Bolte 已提交
3127
        goto cleanup;
M
Matthias Bolte 已提交
3128 3129 3130
    }

    /* Build VMX from domain XML */
3131 3132 3133 3134 3135 3136 3137
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        goto cleanup;
    }

3138
    data.ctx = priv->primary;
3139
    data.datastorePathWithoutFileName = NULL;
3140 3141 3142 3143 3144 3145

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

3146
    vmx = virVMXFormatConfig(&ctx, priv->caps, def, virtualHW_version);
M
Matthias Bolte 已提交
3147 3148

    if (vmx == NULL) {
M
Matthias Bolte 已提交
3149
        goto cleanup;
M
Matthias Bolte 已提交
3150 3151
    }

3152 3153 3154 3155 3156 3157 3158
    /*
     * 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 已提交
3159
    if (def->ndisks < 1) {
3160 3161 3162
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Domain XML doesn't contain any disks, cannot deduce "
                         "datastore and path for VMX file"));
M
Matthias Bolte 已提交
3163
        goto cleanup;
3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174
    }

    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) {
3175 3176 3177
        virReportError(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 已提交
3178
        goto cleanup;
M
Matthias Bolte 已提交
3179 3180
    }

3181
    if (disk->src == NULL) {
3182 3183 3184
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("First file-based harddisk has no source, cannot deduce "
                         "datastore and path for VMX file"));
M
Matthias Bolte 已提交
3185
        goto cleanup;
M
Matthias Bolte 已提交
3186 3187
    }

3188
    if (esxUtil_ParseDatastorePath(disk->src, &datastoreName, &directoryName,
3189
                                   NULL) < 0) {
M
Matthias Bolte 已提交
3190
        goto cleanup;
M
Matthias Bolte 已提交
3191 3192
    }

3193
    if (! virFileHasSuffix(disk->src, ".vmdk")) {
3194 3195 3196
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Expecting source '%s' of first file-based harddisk to "
                         "be a VMDK image"), disk->src);
M
Matthias Bolte 已提交
3197
        goto cleanup;
M
Matthias Bolte 已提交
3198 3199
    }

3200
    virBufferAsprintf(&buffer, "%s://%s:%d/folder/", priv->parsedUri->transport,
M
Matthias Bolte 已提交
3201 3202 3203 3204 3205 3206 3207
                      conn->uri->server, conn->uri->port);

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

3208 3209 3210 3211 3212 3213 3214
    escapedName = esxUtil_EscapeDatastoreItem(def->name);

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

    virBufferURIEncodeString(&buffer, escapedName);
M
Matthias Bolte 已提交
3215
    virBufferAddLit(&buffer, ".vmx?dcPath=");
3216
    virBufferURIEncodeString(&buffer, priv->primary->datacenterPath);
M
Matthias Bolte 已提交
3217 3218 3219 3220
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
3221
        virReportOOMError();
M
Matthias Bolte 已提交
3222
        goto cleanup;
M
Matthias Bolte 已提交
3223 3224 3225 3226
    }

    url = virBufferContentAndReset(&buffer);

3227 3228 3229 3230 3231 3232
    /* Check, if VMX file already exists */
    /* FIXME */

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

3233
    if (esxVI_CURL_Upload(priv->primary->curl, url, vmx) < 0) {
3234 3235 3236 3237
        goto cleanup;
    }

    /* Register the domain */
M
Matthias Bolte 已提交
3238 3239
    if (directoryName != NULL) {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s/%s.vmx", datastoreName,
3240
                        directoryName, escapedName) < 0) {
3241
            virReportOOMError();
M
Matthias Bolte 已提交
3242
            goto cleanup;
M
Matthias Bolte 已提交
3243 3244 3245
        }
    } else {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s.vmx", datastoreName,
3246
                        escapedName) < 0) {
3247
            virReportOOMError();
M
Matthias Bolte 已提交
3248
            goto cleanup;
M
Matthias Bolte 已提交
3249 3250 3251
        }
    }

3252
    if (esxVI_RegisterVM_Task(priv->primary, priv->primary->datacenter->vmFolder,
M
Matthias Bolte 已提交
3253
                              datastoreRelatedPath, NULL, esxVI_Boolean_False,
3254 3255 3256 3257
                              priv->primary->computeResource->resourcePool,
                              priv->primary->hostSystem->_reference,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, def->uuid,
3258
                                    esxVI_Occurrence_OptionalItem,
3259
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3260
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3261
        goto cleanup;
M
Matthias Bolte 已提交
3262 3263 3264
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3265 3266
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not define domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3267
        goto cleanup;
M
Matthias Bolte 已提交
3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278
    }

    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 已提交
3279 3280 3281 3282
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

M
Matthias Bolte 已提交
3283 3284 3285 3286
    virDomainDefFree(def);
    VIR_FREE(vmx);
    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
3287
    VIR_FREE(escapedName);
M
Matthias Bolte 已提交
3288 3289 3290 3291 3292 3293 3294
    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);
3295
    VIR_FREE(taskInfoErrorMessage);
M
Matthias Bolte 已提交
3296 3297 3298 3299 3300 3301

    return domain;
}



3302
static int
3303 3304
esxDomainUndefineFlags(virDomainPtr domain,
                       unsigned int flags)
3305
{
M
Matthias Bolte 已提交
3306
    int result = -1;
M
Matthias Bolte 已提交
3307
    esxPrivate *priv = domain->conn->privateData;
3308
    esxVI_Context *ctx = NULL;
3309 3310 3311 3312
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

3313 3314 3315 3316
    /* No managed save, so we explicitly reject
     * VIR_DOMAIN_UNDEFINE_MANAGED_SAVE.  No snapshot metadata for
     * ESX, so we can trivially ignore that flag.  */
    virCheckFlags(VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA, -1);
3317

3318 3319 3320 3321 3322 3323
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

3324
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
3325
        return -1;
3326 3327
    }

3328
    if (esxVI_String_AppendValueToList(&propertyNameList,
3329
                                       "runtime.powerState") < 0 ||
3330 3331
        esxVI_LookupVirtualMachineByUuid(ctx, domain->uuid, propertyNameList,
                                         &virtualMachine,
M
Matthias Bolte 已提交
3332
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3333
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
3334
        goto cleanup;
3335 3336 3337 3338
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended &&
        powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
3339 3340
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not suspended or powered off"));
M
Matthias Bolte 已提交
3341
        goto cleanup;
3342 3343
    }

3344
    if (esxVI_UnregisterVM(ctx, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
3345
        goto cleanup;
3346 3347
    }

M
Matthias Bolte 已提交
3348 3349
    result = 0;

3350 3351 3352 3353 3354 3355 3356 3357
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}


3358 3359 3360 3361 3362
static int
esxDomainUndefine(virDomainPtr domain)
{
    return esxDomainUndefineFlags(domain, 0);
}
3363

3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443
static int
esxDomainGetAutostart(virDomainPtr domain, int *autostart)
{
    int result = -1;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_AutoStartDefaults *defaults = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_AutoStartPowerInfo *powerInfo = NULL;
    esxVI_AutoStartPowerInfo *powerInfoList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;

    *autostart = 0;

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

    /* Check general autostart config */
    if (esxVI_LookupAutoStartDefaults(priv->primary, &defaults) < 0) {
        goto cleanup;
    }

    if (defaults->enabled != esxVI_Boolean_True) {
        /* Autostart is disabled in general, exit early here */
        result = 0;
        goto cleanup;
    }

    /* Check specific autostart config */
    if (esxVI_LookupAutoStartPowerInfoList(priv->primary, &powerInfoList) < 0) {
        goto cleanup;
    }

    if (powerInfoList == NULL) {
        /* powerInfo list is empty, exit early here */
        result = 0;
        goto cleanup;
    }

    if (esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
                                         NULL, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    for (powerInfo = powerInfoList; powerInfo != NULL;
         powerInfo = powerInfo->_next) {
        if (STREQ(powerInfo->key->value, virtualMachine->obj->value)) {
            if (STRCASEEQ(powerInfo->startAction, "powerOn")) {
                *autostart = 1;
            }

            break;
        }
    }

    result = 0;

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_AutoStartDefaults_Free(&defaults);
    esxVI_AutoStartPowerInfo_Free(&powerInfoList);
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
}



static int
esxDomainSetAutostart(virDomainPtr domain, int autostart)
{
    int result = -1;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_HostAutoStartManagerConfig *spec = NULL;
    esxVI_AutoStartDefaults *defaults = NULL;
    esxVI_AutoStartPowerInfo *powerInfoList = NULL;
    esxVI_AutoStartPowerInfo *powerInfo = NULL;
    esxVI_AutoStartPowerInfo *newPowerInfo = NULL;
3444
    bool newPowerInfo_isAppended = false;
3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482

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

    if (esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
                                         NULL, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_HostAutoStartManagerConfig_Alloc(&spec) < 0) {
        goto cleanup;
    }

    if (autostart) {
        /*
         * There is a general autostart option that affects the autostart
         * behavior of all domains. If it's disabled then no domain does
         * autostart. If it's enabled then the autostart behavior depends on
         * the per-domain autostart config.
         */
        if (esxVI_LookupAutoStartDefaults(priv->primary, &defaults) < 0) {
            goto cleanup;
        }

        if (defaults->enabled != esxVI_Boolean_True) {
            /*
             * Autostart is disabled in general. Check if no other domain is
             * in the list of autostarted domains, so it's safe to enable the
             * general autostart option without affecting the autostart
             * behavior of other domains.
             */
            if (esxVI_LookupAutoStartPowerInfoList(priv->primary,
                                                   &powerInfoList) < 0) {
                goto cleanup;
            }

            for (powerInfo = powerInfoList; powerInfo != NULL;
                 powerInfo = powerInfo->_next) {
                if (STRNEQ(powerInfo->key->value, virtualMachine->obj->value)) {
3483 3484 3485
                    virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                                   _("Cannot enable general autostart option "
                                     "without affecting other domains"));
3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501
                    goto cleanup;
                }
            }

            /* Enable autostart in general */
            if (esxVI_AutoStartDefaults_Alloc(&spec->defaults) < 0) {
                goto cleanup;
            }

            spec->defaults->enabled = esxVI_Boolean_True;
        }
    }

    if (esxVI_AutoStartPowerInfo_Alloc(&newPowerInfo) < 0 ||
        esxVI_Int_Alloc(&newPowerInfo->startOrder) < 0 ||
        esxVI_Int_Alloc(&newPowerInfo->startDelay) < 0 ||
3502
        esxVI_Int_Alloc(&newPowerInfo->stopDelay) < 0) {
3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513
        goto cleanup;
    }

    newPowerInfo->key = virtualMachine->obj;
    newPowerInfo->startOrder->value = -1; /* no specific start order */
    newPowerInfo->startDelay->value = -1; /* use system default */
    newPowerInfo->waitForHeartbeat = esxVI_AutoStartWaitHeartbeatSetting_SystemDefault;
    newPowerInfo->startAction = autostart ? (char *)"powerOn" : (char *)"none";
    newPowerInfo->stopDelay->value = -1; /* use system default */
    newPowerInfo->stopAction = (char *)"none";

3514 3515 3516 3517 3518 3519 3520
    if (esxVI_AutoStartPowerInfo_AppendToList(&spec->powerInfo,
                                              newPowerInfo) < 0) {
        goto cleanup;
    }

    newPowerInfo_isAppended = true;

3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541
    if (esxVI_ReconfigureAutostart
          (priv->primary,
           priv->primary->hostSystem->configManager->autoStartManager,
           spec) < 0) {
        goto cleanup;
    }

    result = 0;

  cleanup:
    if (newPowerInfo != NULL) {
        newPowerInfo->key = NULL;
        newPowerInfo->startAction = NULL;
        newPowerInfo->stopAction = NULL;
    }

    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_HostAutoStartManagerConfig_Free(&spec);
    esxVI_AutoStartDefaults_Free(&defaults);
    esxVI_AutoStartPowerInfo_Free(&powerInfoList);

3542 3543 3544 3545
    if (!newPowerInfo_isAppended) {
        esxVI_AutoStartPowerInfo_Free(&newPowerInfo);
    }

3546 3547 3548 3549 3550
    return result;
}



3551 3552 3553 3554 3555 3556 3557 3558 3559 3560
/*
 * 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:
 *
3561
 * - reservation (VIR_TYPED_PARAM_LLONG >= 0, in megaherz)
3562
 *
3563
 *   The amount of CPU resource that is guaranteed to be available to the domain.
3564 3565
 *
 *
3566
 * - limit (VIR_TYPED_PARAM_LLONG >= 0, or -1, in megaherz)
3567
 *
3568 3569
 *   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
3570 3571 3572 3573
 *   utilization of the domain is unlimited. If the limit is not set to -1, it
 *   must be greater than or equal to the reservation.
 *
 *
3574
 * - shares (VIR_TYPED_PARAM_INT >= 0, or in {-1, -2, -3}, no unit)
3575 3576 3577 3578 3579 3580
 *
 *   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'.
 */
3581
static char *
3582
esxDomainGetSchedulerType(virDomainPtr domain ATTRIBUTE_UNUSED, int *nparams)
3583 3584 3585 3586
{
    char *type = strdup("allocation");

    if (type == NULL) {
3587
        virReportOOMError();
3588
        return NULL;
3589 3590
    }

3591 3592 3593
    if (nparams != NULL) {
        *nparams = 3; /* reservation, limit, shares */
    }
3594 3595 3596 3597 3598 3599 3600

    return type;
}



static int
3601 3602 3603
esxDomainGetSchedulerParametersFlags(virDomainPtr domain,
                                     virTypedParameterPtr params, int *nparams,
                                     unsigned int flags)
3604
{
M
Matthias Bolte 已提交
3605
    int result = -1;
M
Matthias Bolte 已提交
3606
    esxPrivate *priv = domain->conn->privateData;
3607 3608 3609 3610 3611 3612 3613
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    unsigned int mask = 0;
    int i = 0;

3614 3615
    virCheckFlags(0, -1);

3616
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3617
        return -1;
3618 3619
    }

3620
    if (esxVI_String_AppendValueListToList(&propertyNameList,
3621 3622 3623
                                           "config.cpuAllocation.reservation\0"
                                           "config.cpuAllocation.limit\0"
                                           "config.cpuAllocation.shares\0") < 0 ||
3624
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
3625
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3626
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3627
        goto cleanup;
3628 3629 3630
    }

    for (dynamicProperty = virtualMachine->propSet;
3631
         dynamicProperty != NULL && mask != 7 && i < 3 && i < *nparams;
3632 3633
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.cpuAllocation.reservation") &&
M
Matthias Bolte 已提交
3634
            ! (mask & (1 << 0))) {
3635
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3636
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3637
                goto cleanup;
3638
            }
3639 3640 3641 3642 3643
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_SCHEDULER_RESERVATION,
                                        VIR_TYPED_PARAM_LLONG,
                                        dynamicProperty->val->int64) < 0)
                goto cleanup;
3644 3645 3646 3647
            mask |= 1 << 0;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.limit") &&
M
Matthias Bolte 已提交
3648
                   ! (mask & (1 << 1))) {
3649
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3650
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3651
                goto cleanup;
3652
            }
3653 3654 3655 3656 3657
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_SCHEDULER_LIMIT,
                                        VIR_TYPED_PARAM_LLONG,
                                        dynamicProperty->val->int64) < 0)
                goto cleanup;
3658 3659 3660 3661
            mask |= 1 << 1;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.shares") &&
M
Matthias Bolte 已提交
3662
                   ! (mask & (1 << 2))) {
3663 3664 3665 3666
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_SCHEDULER_SHARES,
                                        VIR_TYPED_PARAM_INT, 0) < 0)
                goto cleanup;
3667
            if (esxVI_SharesInfo_CastFromAnyType(dynamicProperty->val,
3668
                                                 &sharesInfo) < 0) {
M
Matthias Bolte 已提交
3669
                goto cleanup;
3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689
            }

            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:
3690 3691 3692
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Shares level has unknown value %d"),
                               (int)sharesInfo->level);
M
Matthias Bolte 已提交
3693
                goto cleanup;
3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705
            }

            esxVI_SharesInfo_Free(&sharesInfo);

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

    *nparams = i;
M
Matthias Bolte 已提交
3706
    result = 0;
3707 3708 3709 3710 3711 3712 3713 3714

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

    return result;
}

3715 3716 3717 3718 3719 3720
static int
esxDomainGetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int *nparams)
{
    return esxDomainGetSchedulerParametersFlags(domain, params, nparams, 0);
}
3721 3722 3723


static int
3724 3725 3726
esxDomainSetSchedulerParametersFlags(virDomainPtr domain,
                                     virTypedParameterPtr params, int nparams,
                                     unsigned int flags)
3727
{
M
Matthias Bolte 已提交
3728
    int result = -1;
M
Matthias Bolte 已提交
3729
    esxPrivate *priv = domain->conn->privateData;
3730 3731 3732 3733 3734
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3735
    char *taskInfoErrorMessage = NULL;
3736 3737
    int i;

3738
    virCheckFlags(0, -1);
3739 3740 3741 3742 3743 3744 3745 3746 3747
    if (virTypedParameterArrayValidate(params, nparams,
                                       VIR_DOMAIN_SCHEDULER_RESERVATION,
                                       VIR_TYPED_PARAM_LLONG,
                                       VIR_DOMAIN_SCHEDULER_LIMIT,
                                       VIR_TYPED_PARAM_LLONG,
                                       VIR_DOMAIN_SCHEDULER_SHARES,
                                       VIR_TYPED_PARAM_INT,
                                       NULL) < 0)
        return -1;
3748

3749
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3750
        return -1;
3751 3752
    }

3753
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3754
          (priv->primary, domain->uuid, NULL, &virtualMachine,
3755
           priv->parsedUri->autoAnswer) < 0 ||
3756 3757
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->cpuAllocation) < 0) {
M
Matthias Bolte 已提交
3758
        goto cleanup;
3759 3760 3761
    }

    for (i = 0; i < nparams; ++i) {
3762
        if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_RESERVATION)) {
3763
            if (esxVI_Long_Alloc(&spec->cpuAllocation->reservation) < 0) {
M
Matthias Bolte 已提交
3764
                goto cleanup;
3765 3766 3767
            }

            if (params[i].value.l < 0) {
3768 3769 3770
                virReportError(VIR_ERR_INVALID_ARG,
                               _("Could not set reservation to %lld MHz, expecting "
                                 "positive value"), params[i].value.l);
M
Matthias Bolte 已提交
3771
                goto cleanup;
3772 3773 3774
            }

            spec->cpuAllocation->reservation->value = params[i].value.l;
3775
        } else if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_LIMIT)) {
3776
            if (esxVI_Long_Alloc(&spec->cpuAllocation->limit) < 0) {
M
Matthias Bolte 已提交
3777
                goto cleanup;
3778 3779 3780
            }

            if (params[i].value.l < -1) {
3781 3782 3783 3784
                virReportError(VIR_ERR_INVALID_ARG,
                               _("Could not set limit to %lld MHz, expecting "
                                 "positive value or -1 (unlimited)"),
                               params[i].value.l);
M
Matthias Bolte 已提交
3785
                goto cleanup;
3786 3787 3788
            }

            spec->cpuAllocation->limit->value = params[i].value.l;
3789
        } else if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_SHARES)) {
3790 3791
            if (esxVI_SharesInfo_Alloc(&sharesInfo) < 0 ||
                esxVI_Int_Alloc(&sharesInfo->shares) < 0) {
M
Matthias Bolte 已提交
3792
                goto cleanup;
3793 3794 3795 3796
            }

            spec->cpuAllocation->shares = sharesInfo;

3797
            if (params[i].value.i >= 0) {
3798
                spec->cpuAllocation->shares->level = esxVI_SharesLevel_Custom;
3799
                spec->cpuAllocation->shares->shares->value = params[i].value.i;
3800
            } else {
3801
                switch (params[i].value.i) {
3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819
                  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:
3820 3821 3822 3823
                    virReportError(VIR_ERR_INVALID_ARG,
                                   _("Could not set shares to %d, expecting positive "
                                     "value or -1 (low), -2 (normal) or -3 (high)"),
                                   params[i].value.i);
M
Matthias Bolte 已提交
3824
                    goto cleanup;
3825 3826 3827 3828 3829
                }
            }
        }
    }

3830
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
3831
                              &task) < 0 ||
3832
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3833
                                    esxVI_Occurrence_RequiredItem,
3834
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3835
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3836
        goto cleanup;
3837 3838 3839
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3840 3841 3842
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not change scheduler parameters: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3843
        goto cleanup;
3844 3845
    }

M
Matthias Bolte 已提交
3846 3847
    result = 0;

3848 3849 3850 3851
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
3852
    VIR_FREE(taskInfoErrorMessage);
3853 3854 3855 3856

    return result;
}

3857 3858 3859 3860 3861 3862
static int
esxDomainSetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int nparams)
{
    return esxDomainSetSchedulerParametersFlags(domain, params, nparams, 0);
}
3863

E
Eric Blake 已提交
3864 3865 3866 3867 3868 3869
/* The subset of migration flags we are able to support.  */
#define ESX_MIGRATION_FLAGS                     \
    (VIR_MIGRATE_PERSIST_DEST |                 \
     VIR_MIGRATE_UNDEFINE_SOURCE |              \
     VIR_MIGRATE_LIVE |                         \
     VIR_MIGRATE_PAUSED)
3870 3871 3872 3873 3874

static int
esxDomainMigratePrepare(virConnectPtr dconn,
                        char **cookie ATTRIBUTE_UNUSED,
                        int *cookielen ATTRIBUTE_UNUSED,
3875 3876
                        const char *uri_in ATTRIBUTE_UNUSED,
                        char **uri_out,
E
Eric Blake 已提交
3877
                        unsigned long flags,
3878 3879 3880
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
3881
    esxPrivate *priv = dconn->privateData;
3882

E
Eric Blake 已提交
3883 3884
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

3885
    if (uri_in == NULL) {
3886 3887 3888 3889
        if (virAsprintf(uri_out, "vpxmigr://%s/%s/%s",
                        priv->vCenter->ipAddress,
                        priv->vCenter->computeResource->resourcePool->value,
                        priv->vCenter->hostSystem->_reference->value) < 0) {
3890
            virReportOOMError();
3891
            return -1;
3892 3893 3894
        }
    }

3895
    return 0;
3896 3897 3898 3899 3900 3901 3902 3903 3904
}



static int
esxDomainMigratePerform(virDomainPtr domain,
                        const char *cookie ATTRIBUTE_UNUSED,
                        int cookielen ATTRIBUTE_UNUSED,
                        const char *uri,
E
Eric Blake 已提交
3905
                        unsigned long flags,
3906 3907 3908
                        const char *dname,
                        unsigned long bandwidth ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
3909
    int result = -1;
M
Matthias Bolte 已提交
3910
    esxPrivate *priv = domain->conn->privateData;
M
Martin Kletzander 已提交
3911
    virURIPtr parsedUri = NULL;
3912 3913 3914
    char *saveptr;
    char *path_resourcePool;
    char *path_hostSystem;
3915
    esxVI_ObjectContent *virtualMachine = NULL;
3916 3917
    esxVI_ManagedObjectReference resourcePool;
    esxVI_ManagedObjectReference hostSystem;
3918 3919 3920
    esxVI_Event *eventList = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3921
    char *taskInfoErrorMessage = NULL;
3922

E
Eric Blake 已提交
3923 3924
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

M
Matthias Bolte 已提交
3925
    if (priv->vCenter == NULL) {
3926 3927
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration not possible without a vCenter"));
M
Matthias Bolte 已提交
3928
        return -1;
3929 3930 3931
    }

    if (dname != NULL) {
3932 3933
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Renaming domains on migration not supported"));
M
Matthias Bolte 已提交
3934
        return -1;
3935 3936
    }

3937
    if (esxVI_EnsureSession(priv->vCenter) < 0) {
M
Matthias Bolte 已提交
3938
        return -1;
3939 3940
    }

3941
    /* Parse migration URI */
3942
    if (!(parsedUri = virURIParse(uri)))
M
Matthias Bolte 已提交
3943
        return -1;
3944

3945
    if (parsedUri->scheme == NULL || STRCASENEQ(parsedUri->scheme, "vpxmigr")) {
3946 3947
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Only vpxmigr:// migration URIs are supported"));
M
Matthias Bolte 已提交
3948
        goto cleanup;
3949 3950
    }

3951
    if (STRCASENEQ(priv->vCenter->ipAddress, parsedUri->server)) {
3952 3953 3954
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration source and destination have to refer to "
                         "the same vCenter"));
3955 3956 3957 3958 3959 3960 3961
        goto cleanup;
    }

    path_resourcePool = strtok_r(parsedUri->path, "/", &saveptr);
    path_hostSystem = strtok_r(NULL, "", &saveptr);

    if (path_resourcePool == NULL || path_hostSystem == NULL) {
3962 3963
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration URI has to specify resource pool and host system"));
M
Matthias Bolte 已提交
3964
        goto cleanup;
3965 3966
    }

3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979
    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,
3980
           priv->parsedUri->autoAnswer) < 0) {
M
Matthias Bolte 已提交
3981
        goto cleanup;
3982 3983 3984
    }

    /* Validate the purposed migration */
3985
    if (esxVI_ValidateMigration(priv->vCenter, virtualMachine->obj,
3986 3987
                                esxVI_VirtualMachinePowerState_Undefined, NULL,
                                &resourcePool, &hostSystem, &eventList) < 0) {
M
Matthias Bolte 已提交
3988
        goto cleanup;
3989 3990 3991 3992 3993 3994 3995 3996
    }

    if (eventList != NULL) {
        /*
         * FIXME: Need to report the complete list of events. Limit reporting
         *        to the first event for now.
         */
        if (eventList->fullFormattedMessage != NULL) {
3997 3998 3999
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not migrate domain, validation reported a "
                             "problem: %s"), eventList->fullFormattedMessage);
4000
        } else {
4001 4002 4003
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Could not migrate domain, validation reported a "
                             "problem"));
4004 4005
        }

M
Matthias Bolte 已提交
4006
        goto cleanup;
4007 4008 4009
    }

    /* Perform the purposed migration */
4010 4011
    if (esxVI_MigrateVM_Task(priv->vCenter, virtualMachine->obj,
                             &resourcePool, &hostSystem,
4012 4013 4014
                             esxVI_VirtualMachineMovePriority_DefaultPriority,
                             esxVI_VirtualMachinePowerState_Undefined,
                             &task) < 0 ||
4015
        esxVI_WaitForTaskCompletion(priv->vCenter, task, domain->uuid,
4016
                                    esxVI_Occurrence_RequiredItem,
4017
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4018
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4019
        goto cleanup;
4020 4021 4022
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4023 4024 4025 4026
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not migrate domain, migration task finished with "
                         "an error: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4027
        goto cleanup;
4028 4029
    }

M
Matthias Bolte 已提交
4030 4031
    result = 0;

4032
  cleanup:
4033
    virURIFree(parsedUri);
4034 4035 4036
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Event_Free(&eventList);
    esxVI_ManagedObjectReference_Free(&task);
4037
    VIR_FREE(taskInfoErrorMessage);
4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048

    return result;
}



static virDomainPtr
esxDomainMigrateFinish(virConnectPtr dconn, const char *dname,
                       const char *cookie ATTRIBUTE_UNUSED,
                       int cookielen ATTRIBUTE_UNUSED,
                       const char *uri ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
4049
                       unsigned long flags)
4050
{
E
Eric Blake 已提交
4051 4052
    virCheckFlags(ESX_MIGRATION_FLAGS, NULL);

4053 4054 4055 4056 4057
    return esxDomainLookupByName(dconn, dname);
}



M
Matthias Bolte 已提交
4058 4059 4060 4061
static unsigned long long
esxNodeGetFreeMemory(virConnectPtr conn)
{
    unsigned long long result = 0;
M
Matthias Bolte 已提交
4062
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
4063 4064 4065 4066 4067
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *resourcePool = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ResourcePoolResourceUsage *resourcePoolResourceUsage = NULL;

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

    /* Get memory usage of resource pool */
4073
    if (esxVI_String_AppendValueToList(&propertyNameList,
M
Matthias Bolte 已提交
4074
                                       "runtime.memory") < 0 ||
4075 4076
        esxVI_LookupObjectContentByType(priv->primary,
                                        priv->primary->computeResource->resourcePool,
4077
                                        "ResourcePool", propertyNameList,
4078 4079
                                        &resourcePool,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4080
        goto cleanup;
M
Matthias Bolte 已提交
4081 4082 4083 4084 4085 4086
    }

    for (dynamicProperty = resourcePool->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.memory")) {
            if (esxVI_ResourcePoolResourceUsage_CastFromAnyType
4087
                  (dynamicProperty->val, &resourcePoolResourceUsage) < 0) {
M
Matthias Bolte 已提交
4088
                goto cleanup;
M
Matthias Bolte 已提交
4089 4090 4091 4092 4093 4094 4095 4096 4097
            }

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

    if (resourcePoolResourceUsage == NULL) {
4098 4099
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not retrieve memory usage of resource pool"));
M
Matthias Bolte 已提交
4100
        goto cleanup;
M
Matthias Bolte 已提交
4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114
    }

    result = resourcePoolResourceUsage->unreservedForVm->value;

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

    return result;
}



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

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



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

4134
    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
4135 4136 4137 4138 4139 4140 4141 4142
        return 1;
    } else {
        return 0;
    }
}



4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159
static int
esxIsAlive(virConnectPtr conn)
{
    esxPrivate *priv = conn->privateData;

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



4160 4161 4162
static int
esxDomainIsActive(virDomainPtr domain)
{
M
Matthias Bolte 已提交
4163
    int result = -1;
M
Matthias Bolte 已提交
4164
    esxPrivate *priv = domain->conn->privateData;
4165 4166 4167 4168
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

4169
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4170
        return -1;
4171 4172
    }

4173
    if (esxVI_String_AppendValueToList(&propertyNameList,
4174
                                       "runtime.powerState") < 0 ||
4175
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
4176
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
4177
                                         esxVI_Occurrence_RequiredItem) < 0 ||
4178
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
4179
        goto cleanup;
4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        result = 1;
    } else {
        result = 0;
    }

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

    return result;
}



static int
4198
esxDomainIsPersistent(virDomainPtr domain)
4199
{
4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219
    /* ESX has no concept of transient domains, so all of them are
     * persistent.  However, we do want to check for existence. */
    int result = -1;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_ObjectContent *virtualMachine = NULL;

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

    if (esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
                                         NULL, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0)
        goto cleanup;

    result = 1;

cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
4220 4221
}

M
Matthias Bolte 已提交
4222 4223


4224 4225 4226
static int
esxDomainIsUpdated(virDomainPtr domain ATTRIBUTE_UNUSED)
{
4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246
    /* ESX domains never have a persistent state that differs from
     * current state.  However, we do want to check for existence.  */
    int result = -1;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_ObjectContent *virtualMachine = NULL;

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

    if (esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
                                         NULL, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0)
        goto cleanup;

    result = 0;

cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
4247
}
4248

M
Matthias Bolte 已提交
4249 4250


4251 4252
static virDomainSnapshotPtr
esxDomainSnapshotCreateXML(virDomainPtr domain, const char *xmlDesc,
4253
                           unsigned int flags)
4254 4255 4256 4257 4258 4259 4260 4261
{
    esxPrivate *priv = domain->conn->privateData;
    virDomainSnapshotDefPtr def = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
4262
    char *taskInfoErrorMessage = NULL;
4263 4264
    virDomainSnapshotPtr snapshot = NULL;

4265 4266
    /* ESX has no snapshot metadata, so this flag is trivial.  */
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA, NULL);
4267

4268
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4269
        return NULL;
4270 4271
    }

4272
    def = virDomainSnapshotDefParseString(xmlDesc, NULL, 0, 0);
4273 4274

    if (def == NULL) {
M
Matthias Bolte 已提交
4275
        return NULL;
4276 4277
    }

4278
    if (def->ndisks) {
4279 4280
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("disk snapshots not supported yet"));
4281 4282 4283
        return NULL;
    }

4284
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
4285
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4286
           priv->parsedUri->autoAnswer) < 0 ||
4287
        esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4288 4289
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, def->name,
4290
                                    &snapshotTree, NULL,
4291
                                    esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4292
        goto cleanup;
4293 4294 4295
    }

    if (snapshotTree != NULL) {
4296 4297
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Snapshot '%s' already exists"), def->name);
M
Matthias Bolte 已提交
4298
        goto cleanup;
4299 4300
    }

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

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4313 4314
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not create snapshot: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4315
        goto cleanup;
4316 4317 4318 4319 4320 4321 4322 4323 4324
    }

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

  cleanup:
    virDomainSnapshotDefFree(def);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4325
    VIR_FREE(taskInfoErrorMessage);
4326 4327 4328 4329 4330 4331 4332

    return snapshot;
}



static char *
4333 4334
esxDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                            unsigned int flags)
4335 4336 4337 4338 4339 4340 4341 4342 4343
{
    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;

4344 4345
    virCheckFlags(0, NULL);

4346
    memset(&def, 0, sizeof(def));
4347

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

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

    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 已提交
4366
        goto cleanup;
4367 4368 4369 4370 4371 4372 4373
    }

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

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

4374
    xml = virDomainSnapshotDefFormat(uuid_string, &def, flags, 0);
4375 4376 4377 4378 4379 4380 4381 4382 4383 4384

  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return xml;
}



static int
4385
esxDomainSnapshotNum(virDomainPtr domain, unsigned int flags)
4386
{
M
Matthias Bolte 已提交
4387
    int count;
4388 4389
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
4390
    bool recurse;
4391
    bool leaves;
4392

4393
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
4394 4395
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4396 4397

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) == 0;
4398
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4399

4400
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4401
        return -1;
4402 4403
    }

4404 4405 4406 4407
    /* ESX snapshots do not require libvirt to maintain any metadata.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA)
        return 0;

4408
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4409
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4410
        return -1;
4411 4412
    }

4413 4414
    count = esxVI_GetNumberOfSnapshotTrees(rootSnapshotTreeList, recurse,
                                           leaves);
4415 4416 4417

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

M
Matthias Bolte 已提交
4418
    return count;
4419 4420 4421 4422 4423 4424
}



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

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
4434 4435
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4436

4437
    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) == 0;
4438
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4439

4440
    if (names == NULL || nameslen < 0) {
4441
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
4442 4443 4444
        return -1;
    }

4445
    if (nameslen == 0 || (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA)) {
4446 4447 4448
        return 0;
    }

4449
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4450
        return -1;
4451 4452
    }

4453
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4454
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4455
        return -1;
4456 4457
    }

4458
    result = esxVI_GetSnapshotTreeNames(rootSnapshotTreeList, names, nameslen,
4459
                                        recurse, leaves);
4460 4461 4462 4463 4464 4465 4466 4467

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



4468 4469 4470 4471 4472 4473 4474 4475
static int
esxDomainSnapshotNumChildren(virDomainSnapshotPtr snapshot, unsigned int flags)
{
    int count = -1;
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    bool recurse;
4476
    bool leaves;
4477 4478

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
4479 4480
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4481 4482

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) != 0;
4483
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503

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

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

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

    count = esxVI_GetNumberOfSnapshotTrees(snapshotTree->childSnapshotList,
4504
                                           recurse, leaves);
4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523

cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return count;
}



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

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
4527 4528
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4529 4530

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) != 0;
4531
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4532 4533

    if (names == NULL || nameslen < 0) {
4534
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560
        return -1;
    }

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

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

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

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

    result = esxVI_GetSnapshotTreeNames(snapshotTree->childSnapshotList,
4561
                                        names, nameslen, recurse, leaves);
4562 4563 4564 4565 4566 4567 4568 4569 4570

cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



4571 4572
static virDomainSnapshotPtr
esxDomainSnapshotLookupByName(virDomainPtr domain, const char *name,
4573
                              unsigned int flags)
4574 4575 4576 4577 4578 4579
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    virDomainSnapshotPtr snapshot = NULL;

4580 4581
    virCheckFlags(0, NULL);

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

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

4610
    virCheckFlags(0, -1);
4611

4612
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4613
        return -1;
4614 4615
    }

4616
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4617 4618
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4619
        return -1;
4620 4621 4622
    }

    if (currentSnapshotTree != NULL) {
M
Matthias Bolte 已提交
4623 4624
        esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);
        return 1;
4625 4626
    }

M
Matthias Bolte 已提交
4627
    return 0;
4628 4629 4630 4631
}



E
Eric Blake 已提交
4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655
static virDomainSnapshotPtr
esxDomainSnapshotGetParent(virDomainSnapshotPtr snapshot, unsigned int flags)
{
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    virDomainSnapshotPtr parent = NULL;

    virCheckFlags(0, NULL);

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

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

    if (!snapshotTreeParent) {
4656 4657 4658
        virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                       _("snapshot '%s' does not have a parent"),
                       snapshotTree->name);
E
Eric Blake 已提交
4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671
        goto cleanup;
    }

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

cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return parent;
}



4672 4673 4674 4675 4676
static virDomainSnapshotPtr
esxDomainSnapshotCurrent(virDomainPtr domain, unsigned int flags)
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *currentSnapshotTree = NULL;
M
Matthias Bolte 已提交
4677
    virDomainSnapshotPtr snapshot = NULL;
4678

4679
    virCheckFlags(0, NULL);
4680

4681
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4682
        return NULL;
4683 4684
    }

4685
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4686 4687
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4688
        return NULL;
4689 4690 4691 4692 4693 4694 4695 4696 4697 4698
    }

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

    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return snapshot;
}


4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767
static int
esxDomainSnapshotIsCurrent(virDomainSnapshotPtr snapshot, unsigned int flags)
{
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *currentSnapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

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

    /* Check that snapshot exists.  */
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, NULL,
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    if (esxVI_LookupCurrentSnapshotTree(priv->primary, snapshot->domain->uuid,
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    ret = STREQ(snapshot->name, currentSnapshotTree->name);

cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    return ret;
}


static int
esxDomainSnapshotHasMetadata(virDomainSnapshotPtr snapshot, unsigned int flags)
{
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

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

    /* Check that snapshot exists.  If so, there is no metadata.  */
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, NULL,
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    ret = 0;

cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    return ret;
}

4768 4769 4770 4771

static int
esxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4772
    int result = -1;
4773 4774 4775 4776 4777
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
4778
    char *taskInfoErrorMessage = NULL;
4779

4780
    virCheckFlags(0, -1);
4781

4782
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4783
        return -1;
4784 4785
    }

4786
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4787 4788
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
4789
                                    &snapshotTree, NULL,
4790
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4791
        goto cleanup;
4792 4793
    }

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

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4804 4805 4806
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not revert to snapshot '%s': %s"), snapshot->name,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4807
        goto cleanup;
4808 4809
    }

M
Matthias Bolte 已提交
4810 4811
    result = 0;

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

    return result;
}



static int
esxDomainSnapshotDelete(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4825
    int result = -1;
4826 4827 4828 4829 4830 4831
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_Boolean removeChildren = esxVI_Boolean_False;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
4832
    char *taskInfoErrorMessage = NULL;
4833

4834 4835
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
                  VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY, -1);
4836

4837
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4838
        return -1;
4839 4840 4841 4842 4843 4844
    }

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

4845
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4846 4847
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
4848
                                    &snapshotTree, NULL,
4849
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4850
        goto cleanup;
4851 4852
    }

4853 4854 4855 4856 4857 4858 4859
    /* ESX snapshots do not require any libvirt metadata, making this
     * flag trivial once we know we have a valid snapshot.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY) {
        result = 0;
        goto cleanup;
    }

4860
    if (esxVI_RemoveSnapshot_Task(priv->primary, snapshotTree->snapshot,
4861
                                  removeChildren, &task) < 0 ||
4862
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4863
                                    esxVI_Occurrence_RequiredItem,
4864
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4865
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4866
        goto cleanup;
4867 4868 4869
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4870 4871 4872
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not delete snapshot '%s': %s"), snapshot->name,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4873
        goto cleanup;
4874 4875
    }

M
Matthias Bolte 已提交
4876 4877
    result = 0;

4878 4879 4880
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4881
    VIR_FREE(taskInfoErrorMessage);
4882 4883 4884 4885 4886 4887

    return result;
}



4888
static int
4889
esxDomainSetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
4890 4891 4892 4893 4894 4895 4896 4897
                             int nparams, unsigned int flags)
{
    int result = -1;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
4898
    char *taskInfoErrorMessage = NULL;
4899 4900 4901
    int i;

    virCheckFlags(0, -1);
4902 4903 4904 4905 4906
    if (virTypedParameterArrayValidate(params, nparams,
                                       VIR_DOMAIN_MEMORY_MIN_GUARANTEE,
                                       VIR_TYPED_PARAM_ULLONG,
                                       NULL) < 0)
        return -1;
4907 4908 4909 4910 4911 4912 4913

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

    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4914
           priv->parsedUri->autoAnswer) < 0 ||
4915 4916 4917 4918 4919 4920
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0) {
        goto cleanup;
    }

    for (i = 0; i < nparams; ++i) {
4921
        if (STREQ(params[i].field, VIR_DOMAIN_MEMORY_MIN_GUARANTEE)) {
4922 4923 4924 4925 4926
            if (esxVI_Long_Alloc(&spec->memoryAllocation->reservation) < 0) {
                goto cleanup;
            }

            spec->memoryAllocation->reservation->value =
4927
              VIR_DIV_UP(params[i].value.ul, 1024); /* Scale from kilobytes to megabytes */
4928 4929 4930 4931 4932 4933 4934
        }
    }

    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
4935
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4936
                                    &taskInfoErrorMessage) < 0) {
4937 4938 4939 4940
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4941 4942 4943
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not change memory parameters: %s"),
                       taskInfoErrorMessage);
4944 4945 4946 4947 4948 4949 4950 4951 4952
        goto cleanup;
    }

    result = 0;

  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
4953
    VIR_FREE(taskInfoErrorMessage);
4954 4955 4956 4957 4958 4959 4960

    return result;
}



static int
4961
esxDomainGetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990
                             int *nparams, unsigned int flags)
{
    int result = -1;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_Long *reservation = NULL;

    virCheckFlags(0, -1);

    if (*nparams == 0) {
        *nparams = 1; /* min_guarantee */
        return 0;
    }

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

    if (esxVI_String_AppendValueToList
          (&propertyNameList, "config.memoryAllocation.reservation") < 0 ||
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
                                         propertyNameList, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_GetLong(virtualMachine, "config.memoryAllocation.reservation",
                      &reservation, esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

4991 4992 4993 4994
    /* Scale from megabytes to kilobytes */
    if (virTypedParameterAssign(params, VIR_DOMAIN_MEMORY_MIN_GUARANTEE,
                                VIR_TYPED_PARAM_ULLONG,
                                reservation->value * 1024) < 0)
4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007
        goto cleanup;

    *nparams = 1;
    result = 0;

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

    return result;
}

5008 5009 5010 5011 5012 5013 5014 5015
#define MATCH(FLAG) (flags & (FLAG))
static int
esxListAllDomains(virConnectPtr conn,
                  virDomainPtr **domains,
                  unsigned int flags)
{
    int ret = -1;
    esxPrivate *priv = conn->privateData;
5016 5017
    bool needIdentity;
    bool needPowerState;
5018 5019 5020
    virDomainPtr dom;
    virDomainPtr *doms = NULL;
    size_t ndoms = 0;
5021
    esxVI_String *propertyNameList = NULL;
5022 5023
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
5024
    esxVI_AutoStartDefaults *autoStartDefaults = NULL;
5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041
    esxVI_VirtualMachinePowerState powerState;
    esxVI_AutoStartPowerInfo *powerInfoList = NULL;
    esxVI_AutoStartPowerInfo *powerInfo = NULL;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    char *name = NULL;
    int id;
    unsigned char uuid[VIR_UUID_BUFLEN];
    int count = 0;
    bool autostart;
    int state;

    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);

    /* check for flags that would produce empty output lists:
     * - persistence: all esx machines are persistent
     * - managed save: esx doesn't support managed save
     */
5042
    if ((MATCH(VIR_CONNECT_LIST_DOMAINS_TRANSIENT) &&
5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053
         !MATCH(VIR_CONNECT_LIST_DOMAINS_PERSISTENT)) ||
        (MATCH(VIR_CONNECT_LIST_DOMAINS_MANAGEDSAVE) &&
         !MATCH(VIR_CONNECT_LIST_DOMAINS_NO_MANAGEDSAVE))) {
        if (domains &&
            VIR_ALLOC_N(*domains, 1) < 0)
            goto no_memory;

        ret = 0;
        goto cleanup;
    }

5054
    if (esxVI_EnsureSession(priv->primary) < 0)
5055 5056 5057 5058 5059
        return -1;

    /* check system default autostart value */
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_AUTOSTART)) {
        if (esxVI_LookupAutoStartDefaults(priv->primary,
5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080
                                          &autoStartDefaults) < 0) {
            goto cleanup;
        }

        if (autoStartDefaults->enabled == esxVI_Boolean_True) {
            if (esxVI_LookupAutoStartPowerInfoList(priv->primary,
                                                   &powerInfoList) < 0) {
                goto cleanup;
            }
        }
    }

    needIdentity = MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_SNAPSHOT) ||
                   domains != NULL;

    if (needIdentity) {
        /* Request required data for esxVI_GetVirtualMachineIdentity */
        if (esxVI_String_AppendValueListToList(&propertyNameList,
                                               "configStatus\0"
                                               "name\0"
                                               "config.uuid\0") < 0) {
5081
            goto cleanup;
5082 5083 5084 5085 5086 5087
        }
    }

    needPowerState = MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_ACTIVE) ||
                     MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_STATE) ||
                     domains != NULL;
5088

5089 5090 5091
    if (needPowerState) {
        if (esxVI_String_AppendValueToList(&propertyNameList,
                                           "runtime.powerState") < 0) {
5092
            goto cleanup;
5093
        }
5094 5095
    }

5096
    if (esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107
                                       &virtualMachineList) < 0)
        goto cleanup;

    if (domains) {
        if (VIR_ALLOC_N(doms, 1) < 0)
            goto no_memory;
        ndoms = 1;
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
5108 5109
        if (needIdentity) {
            VIR_FREE(name);
5110

5111 5112 5113 5114 5115
            if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id,
                                                &name, uuid) < 0) {
                goto cleanup;
            }
        }
5116

5117 5118 5119 5120 5121 5122
        if (needPowerState) {
            if (esxVI_GetVirtualMachinePowerState(virtualMachine,
                                                  &powerState) < 0) {
                goto cleanup;
            }
        }
5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133

        /* filter by active state */
        if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_ACTIVE) &&
            !((MATCH(VIR_CONNECT_LIST_DOMAINS_ACTIVE) &&
               powerState != esxVI_VirtualMachinePowerState_PoweredOff) ||
              (MATCH(VIR_CONNECT_LIST_DOMAINS_INACTIVE) &&
               powerState == esxVI_VirtualMachinePowerState_PoweredOff)))
            continue;

        /* filter by snapshot existence */
        if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_SNAPSHOT)) {
5134 5135
            esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

5136 5137 5138 5139 5140 5141
            if (esxVI_LookupRootSnapshotTreeList(priv->primary, uuid,
                                                 &rootSnapshotTreeList) < 0) {
                goto cleanup;
            }

            if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT) &&
5142
                   rootSnapshotTreeList != NULL) ||
5143
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT) &&
5144
                   rootSnapshotTreeList == NULL)))
5145 5146 5147 5148 5149 5150 5151
                continue;
        }

        /* filter by autostart */
        if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_AUTOSTART)) {
            autostart = false;

5152 5153 5154 5155 5156 5157
            if (autoStartDefaults->enabled == esxVI_Boolean_True) {
                for (powerInfo = powerInfoList; powerInfo != NULL;
                     powerInfo = powerInfo->_next) {
                    if (STREQ(powerInfo->key->value, virtualMachine->obj->value)) {
                        if (STRCASEEQ(powerInfo->startAction, "powerOn"))
                            autostart = true;
5158

5159 5160
                        break;
                    }
5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173
                }
            }

            if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_AUTOSTART) &&
                   autostart) ||
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_AUTOSTART) &&
                   !autostart)))
                continue;
        }

        /* filter by domain state */
        if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_STATE)) {
            state = esxVI_VirtualMachinePowerState_ConvertToLibvirt(powerState);
5174

5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193
            if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_RUNNING) &&
                   state == VIR_DOMAIN_RUNNING) ||
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_PAUSED) &&
                   state == VIR_DOMAIN_PAUSED) ||
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_SHUTOFF) &&
                   state == VIR_DOMAIN_SHUTOFF) ||
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_OTHER) &&
                   (state != VIR_DOMAIN_RUNNING &&
                    state != VIR_DOMAIN_PAUSED &&
                    state != VIR_DOMAIN_SHUTOFF))))
                continue;
        }

        /* just count the machines */
        if (!doms) {
            count++;
            continue;
        }

5194
        if (VIR_RESIZE_N(doms, ndoms, count, 2) < 0)
5195 5196
            goto no_memory;

5197 5198 5199
        if (!(dom = virGetDomain(conn, name, uuid)))
            goto cleanup;

5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216
        /* Only running/suspended virtual machines have an ID != -1 */
        if (powerState != esxVI_VirtualMachinePowerState_PoweredOff)
            dom->id = id;
        else
            dom->id = -1;

        doms[count++] = dom;
    }

    if (doms)
        *domains = doms;
    doms = NULL;
    ret = count;

cleanup:
    if (doms) {
        for (id = 0; id < count; id++) {
5217
            virDomainFree(doms[id]);
5218
        }
5219 5220

        VIR_FREE(doms);
5221
    }
5222

5223
    VIR_FREE(name);
5224 5225
    esxVI_AutoStartDefaults_Free(&autoStartDefaults);
    esxVI_AutoStartPowerInfo_Free(&powerInfoList);
5226 5227
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
5228 5229
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

5230 5231 5232 5233 5234 5235 5236
    return ret;

no_memory:
    virReportOOMError();
    goto cleanup;
}
#undef MATCH
5237 5238


5239
static virDriver esxDriver = {
5240 5241
    .no = VIR_DRV_ESX,
    .name = "ESX",
5242 5243 5244 5245 5246 5247 5248 5249 5250 5251
    .open = esxOpen, /* 0.7.0 */
    .close = esxClose, /* 0.7.0 */
    .supports_feature = esxSupportsFeature, /* 0.7.0 */
    .type = esxGetType, /* 0.7.0 */
    .version = esxGetVersion, /* 0.7.0 */
    .getHostname = esxGetHostname, /* 0.7.0 */
    .nodeGetInfo = esxNodeGetInfo, /* 0.7.0 */
    .getCapabilities = esxGetCapabilities, /* 0.7.1 */
    .listDomains = esxListDomains, /* 0.7.0 */
    .numOfDomains = esxNumberOfDomains, /* 0.7.0 */
5252
    .listAllDomains = esxListAllDomains, /* 0.10.2 */
5253 5254 5255 5256 5257 5258
    .domainLookupByID = esxDomainLookupByID, /* 0.7.0 */
    .domainLookupByUUID = esxDomainLookupByUUID, /* 0.7.0 */
    .domainLookupByName = esxDomainLookupByName, /* 0.7.0 */
    .domainSuspend = esxDomainSuspend, /* 0.7.0 */
    .domainResume = esxDomainResume, /* 0.7.0 */
    .domainShutdown = esxDomainShutdown, /* 0.7.0 */
5259
    .domainShutdownFlags = esxDomainShutdownFlags, /* 0.9.10 */
5260 5261
    .domainReboot = esxDomainReboot, /* 0.7.0 */
    .domainDestroy = esxDomainDestroy, /* 0.7.0 */
5262
    .domainDestroyFlags = esxDomainDestroyFlags, /* 0.9.4 */
5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283
    .domainGetOSType = esxDomainGetOSType, /* 0.7.0 */
    .domainGetMaxMemory = esxDomainGetMaxMemory, /* 0.7.0 */
    .domainSetMaxMemory = esxDomainSetMaxMemory, /* 0.7.0 */
    .domainSetMemory = esxDomainSetMemory, /* 0.7.0 */
    .domainSetMemoryParameters = esxDomainSetMemoryParameters, /* 0.8.6 */
    .domainGetMemoryParameters = esxDomainGetMemoryParameters, /* 0.8.6 */
    .domainGetInfo = esxDomainGetInfo, /* 0.7.0 */
    .domainGetState = esxDomainGetState, /* 0.9.2 */
    .domainSetVcpus = esxDomainSetVcpus, /* 0.7.0 */
    .domainSetVcpusFlags = esxDomainSetVcpusFlags, /* 0.8.5 */
    .domainGetVcpusFlags = esxDomainGetVcpusFlags, /* 0.8.5 */
    .domainGetMaxVcpus = esxDomainGetMaxVcpus, /* 0.7.0 */
    .domainGetXMLDesc = esxDomainGetXMLDesc, /* 0.7.0 */
    .domainXMLFromNative = esxDomainXMLFromNative, /* 0.7.0 */
    .domainXMLToNative = esxDomainXMLToNative, /* 0.7.2 */
    .listDefinedDomains = esxListDefinedDomains, /* 0.7.0 */
    .numOfDefinedDomains = esxNumberOfDefinedDomains, /* 0.7.0 */
    .domainCreate = esxDomainCreate, /* 0.7.0 */
    .domainCreateWithFlags = esxDomainCreateWithFlags, /* 0.8.2 */
    .domainDefineXML = esxDomainDefineXML, /* 0.7.2 */
    .domainUndefine = esxDomainUndefine, /* 0.7.1 */
5284
    .domainUndefineFlags = esxDomainUndefineFlags, /* 0.9.4 */
5285 5286 5287 5288
    .domainGetAutostart = esxDomainGetAutostart, /* 0.9.0 */
    .domainSetAutostart = esxDomainSetAutostart, /* 0.9.0 */
    .domainGetSchedulerType = esxDomainGetSchedulerType, /* 0.7.0 */
    .domainGetSchedulerParameters = esxDomainGetSchedulerParameters, /* 0.7.0 */
5289
    .domainGetSchedulerParametersFlags = esxDomainGetSchedulerParametersFlags, /* 0.9.2 */
5290
    .domainSetSchedulerParameters = esxDomainSetSchedulerParameters, /* 0.7.0 */
5291
    .domainSetSchedulerParametersFlags = esxDomainSetSchedulerParametersFlags, /* 0.9.2 */
5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304
    .domainMigratePrepare = esxDomainMigratePrepare, /* 0.7.0 */
    .domainMigratePerform = esxDomainMigratePerform, /* 0.7.0 */
    .domainMigrateFinish = esxDomainMigrateFinish, /* 0.7.0 */
    .nodeGetFreeMemory = esxNodeGetFreeMemory, /* 0.7.2 */
    .isEncrypted = esxIsEncrypted, /* 0.7.3 */
    .isSecure = esxIsSecure, /* 0.7.3 */
    .domainIsActive = esxDomainIsActive, /* 0.7.3 */
    .domainIsPersistent = esxDomainIsPersistent, /* 0.7.3 */
    .domainIsUpdated = esxDomainIsUpdated, /* 0.8.6 */
    .domainSnapshotCreateXML = esxDomainSnapshotCreateXML, /* 0.8.0 */
    .domainSnapshotGetXMLDesc = esxDomainSnapshotGetXMLDesc, /* 0.8.0 */
    .domainSnapshotNum = esxDomainSnapshotNum, /* 0.8.0 */
    .domainSnapshotListNames = esxDomainSnapshotListNames, /* 0.8.0 */
5305 5306
    .domainSnapshotNumChildren = esxDomainSnapshotNumChildren, /* 0.9.7 */
    .domainSnapshotListChildrenNames = esxDomainSnapshotListChildrenNames, /* 0.9.7 */
5307 5308
    .domainSnapshotLookupByName = esxDomainSnapshotLookupByName, /* 0.8.0 */
    .domainHasCurrentSnapshot = esxDomainHasCurrentSnapshot, /* 0.8.0 */
E
Eric Blake 已提交
5309
    .domainSnapshotGetParent = esxDomainSnapshotGetParent, /* 0.9.7 */
5310 5311
    .domainSnapshotCurrent = esxDomainSnapshotCurrent, /* 0.8.0 */
    .domainRevertToSnapshot = esxDomainRevertToSnapshot, /* 0.8.0 */
5312 5313
    .domainSnapshotIsCurrent = esxDomainSnapshotIsCurrent, /* 0.9.13 */
    .domainSnapshotHasMetadata = esxDomainSnapshotHasMetadata, /* 0.9.13 */
5314
    .domainSnapshotDelete = esxDomainSnapshotDelete, /* 0.8.0 */
5315
    .isAlive = esxIsAlive, /* 0.9.8 */
5316 5317 5318 5319 5320 5321 5322
};



int
esxRegister(void)
{
5323 5324 5325 5326 5327
    if (virRegisterDriver(&esxDriver) < 0 ||
        esxInterfaceRegister() < 0 ||
        esxNetworkRegister() < 0 ||
        esxStorageRegister() < 0 ||
        esxDeviceRegister() < 0 ||
M
Matthias Bolte 已提交
5328 5329
        esxSecretRegister() < 0 ||
        esxNWFilterRegister() < 0) {
5330 5331
        return -1;
    }
5332 5333 5334

    return 0;
}