esx_driver.c 170.1 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-2013 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
#include "virutil.h"
32
#include "viralloc.h"
33
#include "virlog.h"
34
#include "viruuid.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
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);
73
    virObjectUnref((*priv)->caps);
74
    virObjectUnref((*priv)->xmlopt);
75 76 77 78 79
    VIR_FREE(*priv);
}



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

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

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

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

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

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

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

189
            tmp = strippedFileName;
190

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

197 198
                ++tmp;
            }
199

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

206 207
            break;
        }
208

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

215 216 217 218
            /* Expected format: '/vmfs/volumes/<datastore>/<path>' */
            if ((tmp = STRSKIP(copyOfFileName, "/vmfs/volumes/")) == NULL ||
                (datastoreName = strtok_r(tmp, "/", &saveptr)) == NULL ||
                (directoryAndFileName = strtok_r(NULL, "", &saveptr)) == NULL) {
219 220 221
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("File name '%s' doesn't have expected format "
                                 "'/vmfs/volumes/<datastore>/<path>'"), fileName);
222 223
                goto cleanup;
            }
224

225
            esxVI_ObjectContent_Free(&datastoreList);
226

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

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

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

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

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

269
    return result;
270 271 272 273
}



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

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

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

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

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

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

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

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

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

340 341
                ++tmp;
            }
342
        }
343

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

347 348 349 350 351 352 353 354 355 356 357 358
        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 {
359 360
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not handle file name '%s'"), fileName);
361 362 363 364 365 366 367 368 369
        goto cleanup;
    }

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

    success = true;

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

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

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



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

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

411
    vmDiskFileInfo = esxVI_VmDiskFileInfo_DynamicCast(fileInfo);
412 413

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

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

    result = 0;

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

    return result;
}

446 447


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

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

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

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

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

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

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

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

                    break;
                }
            }

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

  cleanup:
M
Matthias Bolte 已提交
516 517 518 519
    /*
     * If we goto cleanup in case of an error then priv->supportsLongMode
     * is still esxVI_Boolean_Undefined, therefore we don't need to set it.
     */
520 521 522 523 524 525 526 527 528
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_HostCpuIdInfo_Free(&hostCpuIdInfoList);

    return priv->supportsLongMode;
}



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

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

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

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

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

    result = 0;

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

    return result;
}


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

578

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

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

    if (supportsLongMode == esxVI_Boolean_True) {
591
        caps = virCapabilitiesNew(VIR_ARCH_X86_64, 1, 1);
592
    } else {
593
        caps = virCapabilitiesNew(VIR_ARCH_I686, 1, 1);
594
    }
595 596

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

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

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

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

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

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

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

626 627
    /* x86_64 */
    if (supportsLongMode == esxVI_Boolean_True) {
628 629 630
        guest = virCapabilitiesAddGuest(caps, "hvm",
                                        VIR_ARCH_X86_64,
                                        NULL, NULL,
631 632 633 634 635 636 637 638 639 640 641 642
                                        0, NULL);

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

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

643 644 645
    return caps;

  failure:
646
    virObjectUnref(caps);
647 648 649 650 651 652

    return NULL;
}



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

    if (vCenterIpAddress == NULL || *vCenterIpAddress != NULL) {
673
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
674 675 676
        return -1;
    }

677
    if (esxUtil_ResolveHostname(conn->uri->server, ipAddress, NI_MAXHOST) < 0) {
678 679 680
        return -1;
    }

681 682
    if (conn->uri->user != NULL) {
        username = strdup(conn->uri->user);
683 684 685 686 687 688

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

        if (username == NULL) {
692
            virReportError(VIR_ERR_AUTH_FAILED, "%s", _("Username request failed"));
693 694 695 696
            goto cleanup;
        }
    }

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

M
Matthias Bolte 已提交
699
    if (unescapedPassword == NULL) {
700
        virReportError(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
701 702 703
        goto cleanup;
    }

M
Matthias Bolte 已提交
704 705 706 707 708 709
    password = esxUtil_EscapeForXml(unescapedPassword);

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

710
    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->parsedUri->transport,
711
                    conn->uri->server, conn->uri->port) < 0) {
712 713 714 715 716 717
        virReportOOMError();
        goto cleanup;
    }

    if (esxVI_Context_Alloc(&priv->host) < 0 ||
        esxVI_Context_Connect(priv->host, url, ipAddress, username, password,
718
                              priv->parsedUri) < 0 ||
719
        esxVI_Context_LookupManagedObjects(priv->host) < 0) {
720 721 722 723 724
        goto cleanup;
    }

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

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

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

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

    result = 0;

  cleanup:
    VIR_FREE(username);
M
Matthias Bolte 已提交
777 778
    VIR_FREE(unescapedPassword);
    VIR_FREE(password);
779 780 781 782 783 784 785 786 787 788
    VIR_FREE(url);
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



static int
789 790
esxConnectToVCenter(esxPrivate *priv,
                    virConnectPtr conn,
791 792
                    virConnectAuthPtr auth,
                    const char *hostname,
793
                    const char *hostSystemIpAddress)
794 795 796 797
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
M
Matthias Bolte 已提交
798
    char *unescapedPassword = NULL;
799 800 801
    char *password = NULL;
    char *url = NULL;

802
    if (hostSystemIpAddress == NULL &&
803
        (priv->parsedUri->path == NULL || STREQ(priv->parsedUri->path, "/"))) {
804 805
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Path has to specify the datacenter and compute resource"));
806 807 808
        return -1;
    }

809 810 811 812
    if (esxUtil_ResolveHostname(hostname, ipAddress, NI_MAXHOST) < 0) {
        return -1;
    }

813 814
    if (conn->uri->user != NULL) {
        username = strdup(conn->uri->user);
815 816 817 818 819 820

        if (username == NULL) {
            virReportOOMError();
            goto cleanup;
        }
    } else {
821
        username = virAuthGetUsername(conn, auth, "esx", "administrator", hostname);
822 823

        if (username == NULL) {
824
            virReportError(VIR_ERR_AUTH_FAILED, "%s", _("Username request failed"));
825 826 827 828
            goto cleanup;
        }
    }

829
    unescapedPassword = virAuthGetPassword(conn, auth, "esx", username, hostname);
830

M
Matthias Bolte 已提交
831
    if (unescapedPassword == NULL) {
832
        virReportError(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
833 834 835
        goto cleanup;
    }

M
Matthias Bolte 已提交
836 837 838 839 840 841
    password = esxUtil_EscapeForXml(unescapedPassword);

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

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

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

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

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

879 880 881 882
    result = 0;

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

    return result;
}



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

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

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

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

971 972 973
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Transport '%s' in URI scheme is not supported, try again "
                         "without the transport part"), plus + 1);
974 975 976
        return VIR_DRV_OPEN_ERROR;
    }

977 978 979 980 981 982
    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);
    }

983 984
    /* Require server part */
    if (conn->uri->server == NULL) {
985 986
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("URI is missing the server part"));
987 988 989 990 991
        return VIR_DRV_OPEN_ERROR;
    }

    /* Require auth */
    if (auth == NULL || auth->cb == NULL) {
992 993
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Missing or invalid auth pointer"));
994
        return VIR_DRV_OPEN_ERROR;
995 996 997 998
    }

    /* Allocate per-connection private data */
    if (VIR_ALLOC(priv) < 0) {
999
        virReportOOMError();
M
Matthias Bolte 已提交
1000
        goto cleanup;
1001 1002
    }

1003
    if (esxUtil_ParseUri(&priv->parsedUri, conn->uri) < 0) {
1004 1005 1006
        goto cleanup;
    }

M
Matthias Bolte 已提交
1007 1008
    priv->maxVcpus = -1;
    priv->supportsVMotion = esxVI_Boolean_Undefined;
1009
    priv->supportsLongMode = esxVI_Boolean_Undefined;
1010 1011
    priv->usedCpuTimeCounterId = -1;

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

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

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

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

1065 1066
                if (potentialVCenterIpAddress != NULL &&
                    STRNEQ(vCenterIpAddress, potentialVCenterIpAddress)) {
1067 1068 1069 1070 1071 1072
                    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 已提交
1073
                    goto cleanup;
1074 1075
                }
            }
1076

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

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

1093
        priv->primary = priv->vCenter;
1094 1095
    }

M
Matthias Bolte 已提交
1096
    /* Setup capabilities */
1097
    priv->caps = esxCapsInit(priv);
1098

M
Matthias Bolte 已提交
1099
    if (priv->caps == NULL) {
M
Matthias Bolte 已提交
1100
        goto cleanup;
1101 1102
    }

1103
    if (!(priv->xmlopt = virDomainXMLOptionNew(NULL, NULL, NULL)))
1104 1105
        goto cleanup;

1106 1107
    conn->privateData = priv;
    priv = NULL;
M
Matthias Bolte 已提交
1108
    result = VIR_DRV_OPEN_SUCCESS;
1109

M
Matthias Bolte 已提交
1110
  cleanup:
1111
    esxFreePrivate(&priv);
1112
    VIR_FREE(potentialVCenterIpAddress);
1113

M
Matthias Bolte 已提交
1114
    return result;
1115 1116 1117 1118 1119 1120 1121
}



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

1125 1126 1127 1128 1129 1130
    if (priv->host != NULL) {
        if (esxVI_EnsureSession(priv->host) < 0 ||
            esxVI_Logout(priv->host) < 0) {
            result = -1;
        }
    }
1131

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

1139
    esxFreePrivate(&priv);
1140 1141 1142

    conn->privateData = NULL;

E
Eric Blake 已提交
1143
    return result;
1144 1145 1146 1147 1148
}



static esxVI_Boolean
1149
esxSupportsVMotion(esxPrivate *priv)
1150 1151 1152 1153
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;

M
Matthias Bolte 已提交
1154 1155
    if (priv->supportsVMotion != esxVI_Boolean_Undefined) {
        return priv->supportsVMotion;
1156 1157
    }

1158
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1159
        return esxVI_Boolean_Undefined;
1160 1161
    }

1162
    if (esxVI_String_AppendValueToList(&propertyNameList,
1163
                                       "capability.vmotionSupported") < 0 ||
1164
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
1165 1166
                                         &hostSystem) < 0 ||
        esxVI_GetBoolean(hostSystem, "capability.vmotionSupported",
1167 1168 1169
                         &priv->supportsVMotion,
                         esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
1170 1171 1172
    }

  cleanup:
M
Matthias Bolte 已提交
1173 1174 1175 1176
    /*
     * 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.
     */
1177 1178 1179
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
1180
    return priv->supportsVMotion;
1181 1182 1183 1184 1185 1186 1187
}



static int
esxSupportsFeature(virConnectPtr conn, int feature)
{
M
Matthias Bolte 已提交
1188
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1189
    esxVI_Boolean supportsVMotion = esxVI_Boolean_Undefined;
1190 1191 1192

    switch (feature) {
      case VIR_DRV_FEATURE_MIGRATION_V1:
1193
        supportsVMotion = esxSupportsVMotion(priv);
1194

M
Matthias Bolte 已提交
1195
        if (supportsVMotion == esxVI_Boolean_Undefined) {
1196 1197 1198
            return -1;
        }

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

      default:
        return 0;
    }
}



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



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

1223
    if (virParseVersionString(priv->primary->service->about->version,
1224
                              version, false) < 0) {
1225 1226 1227
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not parse version number from '%s'"),
                       priv->primary->service->about->version);
1228

1229
        return -1;
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
    }

    return 0;
}



static char *
esxGetHostname(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1240
    esxPrivate *priv = conn->privateData;
1241 1242 1243 1244 1245 1246 1247
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    const char *hostName = NULL;
    const char *domainName = NULL;
    char *complete = NULL;

1248
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1249
        return NULL;
1250 1251 1252
    }

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

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

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

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

M
Matthias Bolte 已提交
1284
    if (hostName == NULL || strlen(hostName) < 1) {
1285 1286
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing or empty 'hostName' property"));
M
Matthias Bolte 已提交
1287
        goto cleanup;
1288 1289
    }

M
Matthias Bolte 已提交
1290
    if (domainName == NULL || strlen(domainName) < 1) {
1291
        complete = strdup(hostName);
1292

1293
        if (complete == NULL) {
1294
            virReportOOMError();
M
Matthias Bolte 已提交
1295
            goto cleanup;
1296 1297 1298
        }
    } else {
        if (virAsprintf(&complete, "%s.%s", hostName, domainName) < 0) {
1299
            virReportOOMError();
M
Matthias Bolte 已提交
1300
            goto cleanup;
1301
        }
1302 1303 1304
    }

  cleanup:
M
Matthias Bolte 已提交
1305 1306 1307 1308 1309
    /*
     * 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
     */
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return complete;
}



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

1334
    memset(nodeinfo, 0, sizeof(*nodeinfo));
1335

1336
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1337
        return -1;
1338 1339
    }

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

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

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

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

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

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

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

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

            ptr = dynamicProperty->val->string;

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

                ++ptr;
            }

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

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

1453 1454 1455 1456 1457 1458 1459 1460 1461
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



1462 1463 1464
static char *
esxGetCapabilities(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1465
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1466
    char *xml = virCapabilitiesFormatXML(priv->caps);
1467 1468

    if (xml == NULL) {
1469
        virReportOOMError();
1470 1471 1472 1473 1474 1475 1476 1477
        return NULL;
    }

    return xml;
}



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

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

1493
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1494
        return -1;
1495 1496
    }

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

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

        if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

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

        count++;

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

M
Matthias Bolte 已提交
1531 1532
    success = true;

1533 1534 1535 1536
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
1537
    return success ? count : -1;
1538 1539 1540 1541 1542 1543 1544
}



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

1547
    if (esxVI_EnsureSession(priv->primary) < 0) {
1548 1549 1550
        return -1;
    }

1551
    return esxVI_LookupNumberOfDomainsByPowerState
1552
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, false);
1553 1554 1555 1556 1557 1558 1559
}



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

1570
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1571
        return NULL;
1572 1573
    }

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

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

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

M
Matthias Bolte 已提交
1596
        VIR_FREE(name_candidate);
1597

1598
        if (esxVI_GetVirtualMachineIdentity(virtualMachine,
M
Matthias Bolte 已提交
1599 1600
                                            &id_candidate, &name_candidate,
                                            uuid_candidate) < 0) {
M
Matthias Bolte 已提交
1601
            goto cleanup;
1602 1603
        }

M
Matthias Bolte 已提交
1604
        if (id != id_candidate) {
1605 1606 1607
            continue;
        }

M
Matthias Bolte 已提交
1608
        domain = virGetDomain(conn, name_candidate, uuid_candidate);
1609 1610

        if (domain == NULL) {
M
Matthias Bolte 已提交
1611
            goto cleanup;
1612 1613 1614 1615 1616 1617 1618 1619
        }

        domain->id = id;

        break;
    }

    if (domain == NULL) {
1620
        virReportError(VIR_ERR_NO_DOMAIN, _("No domain with ID %d"), id);
1621 1622 1623 1624 1625
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
M
Matthias Bolte 已提交
1626
    VIR_FREE(name_candidate);
1627 1628 1629 1630 1631 1632 1633 1634 1635

    return domain;
}



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

1644
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1645
        return NULL;
1646 1647
    }

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

1659
    domain = virGetDomain(conn, name, uuid);
1660 1661

    if (domain == NULL) {
M
Matthias Bolte 已提交
1662
        goto cleanup;
1663
    }
1664

1665 1666 1667 1668 1669
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1670 1671 1672 1673
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1674 1675
    esxVI_ObjectContent_Free(&virtualMachine);
    VIR_FREE(name);
1676 1677 1678 1679 1680 1681 1682 1683 1684

    return domain;
}



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

1693
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1694
        return NULL;
1695 1696
    }

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

1707
    if (virtualMachine == NULL) {
1708
        virReportError(VIR_ERR_NO_DOMAIN, _("No domain with name '%s'"), name);
M
Matthias Bolte 已提交
1709
        goto cleanup;
1710
    }
1711

M
Matthias Bolte 已提交
1712 1713 1714
    if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, uuid) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
1715
    }
1716

1717
    domain = virGetDomain(conn, name, uuid);
1718

1719
    if (domain == NULL) {
M
Matthias Bolte 已提交
1720
        goto cleanup;
1721 1722
    }

1723 1724 1725 1726 1727
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1728 1729 1730 1731
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1732
    esxVI_ObjectContent_Free(&virtualMachine);
1733 1734 1735 1736 1737 1738 1739 1740 1741

    return domain;
}



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

1751
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1752
        return -1;
1753 1754
    }

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

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1765 1766
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1767
        goto cleanup;
1768 1769
    }

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

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1779 1780
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not suspend domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
1781
        goto cleanup;
1782 1783
    }

M
Matthias Bolte 已提交
1784 1785
    result = 0;

1786 1787 1788 1789
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1790
    VIR_FREE(taskInfoErrorMessage);
1791 1792 1793 1794 1795 1796 1797 1798 1799

    return result;
}



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

1809
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1810
        return -1;
1811 1812
    }

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

    if (powerState != esxVI_VirtualMachinePowerState_Suspended) {
1823
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not suspended"));
M
Matthias Bolte 已提交
1824
        goto cleanup;
1825 1826
    }

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

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1837 1838
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not resume domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
1839
        goto cleanup;
1840 1841
    }

M
Matthias Bolte 已提交
1842 1843
    result = 0;

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

    return result;
}



static int
1856
esxDomainShutdownFlags(virDomainPtr domain, unsigned int flags)
1857
{
M
Matthias Bolte 已提交
1858
    int result = -1;
M
Matthias Bolte 已提交
1859
    esxPrivate *priv = domain->conn->privateData;
1860 1861 1862 1863
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1864 1865
    virCheckFlags(0, -1);

1866
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1867
        return -1;
1868 1869
    }

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

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1880 1881
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1882
        goto cleanup;
1883 1884
    }

1885
    if (esxVI_ShutdownGuest(priv->primary, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1886
        goto cleanup;
1887 1888
    }

M
Matthias Bolte 已提交
1889 1890
    result = 0;

1891 1892 1893 1894 1895 1896 1897 1898
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}


1899 1900 1901 1902 1903 1904
static int
esxDomainShutdown(virDomainPtr domain)
{
    return esxDomainShutdownFlags(domain, 0);
}

1905 1906

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

E
Eric Blake 已提交
1915 1916
    virCheckFlags(0, -1);

1917
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1918
        return -1;
1919 1920
    }

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

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1931 1932
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1933
        goto cleanup;
1934 1935
    }

1936
    if (esxVI_RebootGuest(priv->primary, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1937
        goto cleanup;
1938 1939
    }

M
Matthias Bolte 已提交
1940 1941
    result = 0;

1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



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

1965 1966
    virCheckFlags(0, -1);

1967 1968 1969 1970 1971 1972
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

1973
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
1974
        return -1;
1975 1976
    }

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

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1987 1988
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1989
        goto cleanup;
1990 1991
    }

1992
    if (esxVI_PowerOffVM_Task(ctx, virtualMachine->obj, &task) < 0 ||
1993 1994
        esxVI_WaitForTaskCompletion(ctx, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
1995
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1996
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1997
        goto cleanup;
1998 1999 2000
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2001 2002
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not destroy domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2003
        goto cleanup;
2004 2005
    }

2006
    domain->id = -1;
M
Matthias Bolte 已提交
2007 2008
    result = 0;

2009 2010 2011 2012
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
2013
    VIR_FREE(taskInfoErrorMessage);
2014 2015 2016 2017 2018

    return result;
}


2019 2020 2021 2022 2023 2024
static int
esxDomainDestroy(virDomainPtr dom)
{
    return esxDomainDestroyFlags(dom, 0);
}

2025 2026

static char *
2027
esxDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED)
2028
{
2029 2030 2031
    char *osType = strdup("hvm");

    if (osType == NULL) {
2032
        virReportOOMError();
2033 2034 2035 2036
        return NULL;
    }

    return osType;
2037 2038 2039 2040
}



2041
static unsigned long long
2042 2043
esxDomainGetMaxMemory(virDomainPtr domain)
{
M
Matthias Bolte 已提交
2044
    esxPrivate *priv = domain->conn->privateData;
2045 2046 2047 2048 2049
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    unsigned long memoryMB = 0;

2050
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2051
        return 0;
2052 2053
    }

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

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2065
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2066
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2067
                goto cleanup;
2068 2069 2070
            }

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

2106
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2107
        return -1;
2108 2109
    }

2110 2111 2112 2113
    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "runtime.powerState") < 0 ||
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
2114
           priv->parsedUri->autoAnswer) < 0 ||
2115 2116 2117 2118 2119
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2120 2121
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered off"));
2122 2123 2124 2125
        goto cleanup;
    }

    if (esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
2126
        esxVI_Long_Alloc(&spec->memoryMB) < 0) {
M
Matthias Bolte 已提交
2127
        goto cleanup;
2128 2129
    }

2130
    /* max-memory must be a multiple of 4096 kilobyte */
2131
    spec->memoryMB->value =
2132
      VIR_DIV_UP(memory, 4096) * 4; /* Scale from kilobytes to megabytes */
2133

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

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2144 2145 2146
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set max-memory to %lu kilobytes: %s"), memory,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2147
        goto cleanup;
2148 2149
    }

M
Matthias Bolte 已提交
2150 2151
    result = 0;

2152
  cleanup:
2153
    esxVI_String_Free(&propertyNameList);
2154 2155 2156
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2157
    VIR_FREE(taskInfoErrorMessage);
2158 2159 2160 2161 2162 2163 2164 2165 2166

    return result;
}



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

2175
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2176
        return -1;
2177 2178
    }

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

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

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

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2201 2202 2203
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set memory to %lu kilobytes: %s"), memory,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2204
        goto cleanup;
2205 2206
    }

M
Matthias Bolte 已提交
2207 2208
    result = 0;

2209 2210 2211 2212
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2213
    VIR_FREE(taskInfoErrorMessage);
2214 2215 2216 2217 2218 2219

    return result;
}



2220 2221 2222 2223 2224 2225 2226 2227 2228
/*
 * 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

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

2254
    memset(info, 0, sizeof(*info));
M
Matthias Bolte 已提交
2255

2256
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2257
        return -1;
2258 2259
    }

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

    info->state = VIR_DOMAIN_NOSTATE;

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

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

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

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

            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;

2317
#if ESX_QUERY_FOR_USED_CPU_TIME
2318
    /* Verify the cached 'used CPU time' performance counter ID */
2319 2320 2321 2322 2323 2324
    /* 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;
            }
2325

2326
            counterId->value = priv->usedCpuTimeCounterId;
2327

2328 2329 2330
            if (esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                goto cleanup;
            }
2331

2332 2333 2334 2335
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfo) < 0) {
                goto cleanup;
            }
2336

2337 2338 2339 2340 2341
            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);
2342

2343 2344 2345 2346 2347
                priv->usedCpuTimeCounterId = -1;
            }

            esxVI_Int_Free(&counterIdList);
            esxVI_PerfCounterInfo_Free(&perfCounterInfo);
2348 2349
        }

2350 2351 2352 2353 2354 2355 2356 2357 2358 2359
        /*
         * 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;
            }
2360

2361 2362 2363 2364
            for (perfMetricId = perfMetricIdList; perfMetricId != NULL;
                 perfMetricId = perfMetricId->_next) {
                VIR_DEBUG("perfMetricId counterId %d, instance '%s'",
                          perfMetricId->counterId->value, perfMetricId->instance);
2365

2366
                counterId = NULL;
2367

2368 2369 2370 2371 2372
                if (esxVI_Int_DeepCopy(&counterId, perfMetricId->counterId) < 0 ||
                    esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                    goto cleanup;
                }
            }
2373

2374 2375
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfoList) < 0) {
M
Matthias Bolte 已提交
2376
                goto cleanup;
2377 2378
            }

2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395
            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;
                }
2396 2397
            }

2398
            if (priv->usedCpuTimeCounterId < 0) {
2399
                VIR_WARN("Could not find 'used CPU time' performance counter");
2400
            }
2401 2402
        }

2403 2404 2405 2406 2407 2408
        /*
         * 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);
2409

2410 2411 2412 2413 2414 2415
            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;
            }
2416

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

2428 2429 2430
            for (perfEntityMetricBase = perfEntityMetricBaseList;
                 perfEntityMetricBase != NULL;
                 perfEntityMetricBase = perfEntityMetricBase->_next) {
2431
                VIR_DEBUG("perfEntityMetric ...");
2432

2433 2434
                perfEntityMetric =
                  esxVI_PerfEntityMetric_DynamicCast(perfEntityMetricBase);
2435

2436
                if (perfEntityMetric == NULL) {
2437 2438 2439
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("QueryPerf returned object with unexpected type '%s'"),
                                   esxVI_Type_ToString(perfEntityMetricBase->_type));
2440
                    goto cleanup;
2441
                }
2442

2443 2444
                perfMetricIntSeries =
                  esxVI_PerfMetricIntSeries_DynamicCast(perfEntityMetric->value);
2445

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

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

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

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

2467
            /*
E
Eric Blake 已提交
2468
             * FIXME: Cannot map between relative used-cpu-time and absolute
2469 2470 2471
             *        info->cpuTime
             */
        }
2472
    }
2473
#endif
2474

M
Matthias Bolte 已提交
2475 2476
    result = 0;

2477
  cleanup:
2478
#if ESX_QUERY_FOR_USED_CPU_TIME
2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490
    /*
     * 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;
        }
    }
2491
#endif
2492

2493 2494
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2495
#if ESX_QUERY_FOR_USED_CPU_TIME
2496 2497 2498 2499
    esxVI_PerfMetricId_Free(&perfMetricIdList);
    esxVI_Int_Free(&counterIdList);
    esxVI_PerfCounterInfo_Free(&perfCounterInfoList);
    esxVI_PerfQuerySpec_Free(&querySpec);
2500
    esxVI_PerfEntityMetricBase_Free(&perfEntityMetricBaseList);
2501
#endif
2502 2503 2504 2505 2506 2507

    return result;
}



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 2546 2547 2548 2549 2550
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;
}



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

2564
    if (flags != VIR_DOMAIN_AFFECT_LIVE) {
2565
        virReportError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
2566 2567 2568
        return -1;
    }

2569
    if (nvcpus < 1) {
2570 2571
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Requested number of virtual CPUs must at least be 1"));
M
Matthias Bolte 已提交
2572
        return -1;
2573 2574
    }

2575
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2576
        return -1;
2577 2578
    }

M
Matthias Bolte 已提交
2579
    maxVcpus = esxDomainGetMaxVcpus(domain);
2580

M
Matthias Bolte 已提交
2581
    if (maxVcpus < 0) {
M
Matthias Bolte 已提交
2582
        return -1;
2583 2584
    }

M
Matthias Bolte 已提交
2585
    if (nvcpus > maxVcpus) {
2586 2587 2588 2589
        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 已提交
2590
        return -1;
2591 2592
    }

2593
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2594
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2595
           priv->parsedUri->autoAnswer) < 0 ||
2596 2597
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Int_Alloc(&spec->numCPUs) < 0) {
M
Matthias Bolte 已提交
2598
        goto cleanup;
2599 2600 2601 2602
    }

    spec->numCPUs->value = nvcpus;

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

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2613 2614 2615
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set number of virtual CPUs to %d: %s"), nvcpus,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2616
        goto cleanup;
2617 2618
    }

M
Matthias Bolte 已提交
2619 2620
    result = 0;

2621 2622 2623 2624
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2625
    VIR_FREE(taskInfoErrorMessage);
2626 2627 2628 2629 2630

    return result;
}


M
Matthias Bolte 已提交
2631

2632 2633 2634
static int
esxDomainSetVcpus(virDomainPtr domain, unsigned int nvcpus)
{
2635
    return esxDomainSetVcpusFlags(domain, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
2636 2637
}

2638

M
Matthias Bolte 已提交
2639

2640
static int
2641
esxDomainGetVcpusFlags(virDomainPtr domain, unsigned int flags)
2642
{
M
Matthias Bolte 已提交
2643
    esxPrivate *priv = domain->conn->privateData;
2644 2645 2646 2647
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

2648
    if (flags != (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_VCPU_MAXIMUM)) {
2649
        virReportError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
2650 2651 2652
        return -1;
    }

M
Matthias Bolte 已提交
2653 2654
    if (priv->maxVcpus > 0) {
        return priv->maxVcpus;
2655 2656
    }

M
Matthias Bolte 已提交
2657 2658
    priv->maxVcpus = -1;

2659
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2660
        return -1;
2661 2662
    }

2663
    if (esxVI_String_AppendValueToList(&propertyNameList,
2664
                                       "capability.maxSupportedVcpus") < 0 ||
2665 2666
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
2667
        goto cleanup;
2668 2669 2670 2671 2672
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "capability.maxSupportedVcpus")) {
2673
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2674
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2675
                goto cleanup;
2676 2677
            }

M
Matthias Bolte 已提交
2678
            priv->maxVcpus = dynamicProperty->val->int32;
2679 2680 2681 2682 2683 2684 2685 2686 2687 2688
            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

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

M
Matthias Bolte 已提交
2689
    return priv->maxVcpus;
2690 2691
}

M
Matthias Bolte 已提交
2692 2693


2694 2695 2696
static int
esxDomainGetMaxVcpus(virDomainPtr domain)
{
2697
    return esxDomainGetVcpusFlags(domain, (VIR_DOMAIN_AFFECT_LIVE |
2698 2699
                                           VIR_DOMAIN_VCPU_MAXIMUM));
}
2700

M
Matthias Bolte 已提交
2701 2702


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

E
Eric Blake 已提交
2723 2724
    /* Flags checked by virDomainDefFormat */

2725
    memset(&data, 0, sizeof(data));
2726

2727
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2728
        return NULL;
2729 2730
    }

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

2744
    if (esxUtil_ParseDatastorePath(vmPathName, &datastoreName, &directoryName,
2745
                                   &directoryAndFileName) < 0) {
M
Matthias Bolte 已提交
2746
        goto cleanup;
2747 2748
    }

2749
    virBufferAsprintf(&buffer, "%s://%s:%d/folder/", priv->parsedUri->transport,
2750
                      domain->conn->uri->server, domain->conn->uri->port);
2751
    virBufferURIEncodeString(&buffer, directoryAndFileName);
2752
    virBufferAddLit(&buffer, "?dcPath=");
2753
    virBufferURIEncodeString(&buffer, priv->primary->datacenterPath);
2754 2755 2756 2757
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
2758
        virReportOOMError();
M
Matthias Bolte 已提交
2759
        goto cleanup;
2760 2761
    }

2762 2763
    url = virBufferContentAndReset(&buffer);

2764
    if (esxVI_CURL_Download(priv->primary->curl, url, &vmx, 0, NULL) < 0) {
M
Matthias Bolte 已提交
2765
        goto cleanup;
2766 2767
    }

2768
    data.ctx = priv->primary;
2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782

    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;
        }
    }
2783 2784 2785 2786 2787 2788

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

2789
    def = virVMXParseConfig(&ctx, priv->caps, vmx);
2790 2791

    if (def != NULL) {
2792 2793 2794 2795
        if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
            def->id = id;
        }

2796
        xml = virDomainDefFormat(def, flags);
2797 2798 2799
    }

  cleanup:
M
Matthias Bolte 已提交
2800 2801 2802 2803
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

2804 2805
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2806
    VIR_FREE(datastoreName);
M
Matthias Bolte 已提交
2807
    VIR_FREE(directoryName);
2808
    VIR_FREE(directoryAndFileName);
2809
    VIR_FREE(url);
2810
    VIR_FREE(data.datastorePathWithoutFileName);
2811
    VIR_FREE(vmx);
2812
    virDomainDefFree(def);
2813 2814 2815 2816 2817 2818 2819 2820 2821

    return xml;
}



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

E
Eric Blake 已提交
2830 2831
    virCheckFlags(0, NULL);

2832
    memset(&data, 0, sizeof(data));
2833

2834
    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2835 2836
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Unsupported config format '%s'"), nativeFormat);
2837
        return NULL;
2838 2839
    }

2840
    data.ctx = priv->primary;
2841
    data.datastorePathWithoutFileName = (char *)"[?] ?";
2842 2843 2844 2845 2846 2847

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

2848
    def = virVMXParseConfig(&ctx, priv->caps, nativeConfig);
2849 2850

    if (def != NULL) {
2851
        xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
2852 2853 2854 2855 2856 2857 2858 2859 2860
    }

    virDomainDefFree(def);

    return xml;
}



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

E
Eric Blake 已提交
2873 2874
    virCheckFlags(0, NULL);

2875
    memset(&data, 0, sizeof(data));
2876

M
Matthias Bolte 已提交
2877
    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2878 2879
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Unsupported config format '%s'"), nativeFormat);
M
Matthias Bolte 已提交
2880 2881 2882
        return NULL;
    }

2883 2884 2885 2886 2887 2888 2889
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        return NULL;
    }

2890 2891
    def = virDomainDefParseString(domainXml, priv->caps, priv->xmlopt,
                                  1 << VIR_DOMAIN_VIRT_VMWARE, 0);
M
Matthias Bolte 已提交
2892 2893 2894 2895 2896

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

2897
    data.ctx = priv->primary;
2898
    data.datastorePathWithoutFileName = NULL;
2899 2900 2901 2902 2903 2904

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

2905
    vmx = virVMXFormatConfig(&ctx, priv->caps, def, virtualHW_version);
M
Matthias Bolte 已提交
2906 2907 2908 2909 2910 2911 2912 2913

    virDomainDefFree(def);

    return vmx;
}



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

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

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

2934
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2935 2936
                                           "name\0"
                                           "runtime.powerState\0") < 0 ||
2937 2938
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2939
        goto cleanup;
2940 2941 2942 2943
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
2944
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
2945
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
2946
            goto cleanup;
2947 2948 2949 2950 2951 2952
        }

        if (powerState == esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

2953
        names[count] = NULL;
2954

2955 2956 2957
        if (esxVI_GetVirtualMachineIdentity(virtualMachine, NULL, &names[count],
                                            NULL) < 0) {
            goto cleanup;
2958 2959
        }

2960 2961
        ++count;

2962 2963 2964 2965 2966
        if (count >= maxnames) {
            break;
        }
    }

M
Matthias Bolte 已提交
2967
    success = true;
2968

M
Matthias Bolte 已提交
2969 2970 2971 2972 2973
  cleanup:
    if (! success) {
        for (i = 0; i < count; ++i) {
            VIR_FREE(names[i]);
        }
2974

M
Matthias Bolte 已提交
2975
        count = -1;
2976 2977
    }

M
Matthias Bolte 已提交
2978 2979
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
2980

M
Matthias Bolte 已提交
2981
    return count;
2982 2983 2984 2985 2986 2987 2988
}



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

2991
    if (esxVI_EnsureSession(priv->primary) < 0) {
2992 2993 2994
        return -1;
    }

2995
    return esxVI_LookupNumberOfDomainsByPowerState
2996
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, true);
2997 2998 2999 3000 3001
}



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

3014 3015
    virCheckFlags(0, -1);

3016
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3017
        return -1;
3018 3019
    }

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

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
3031 3032
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered off"));
M
Matthias Bolte 已提交
3033
        goto cleanup;
3034 3035
    }

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

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3046 3047
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not start domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3048
        goto cleanup;
3049 3050
    }

3051
    domain->id = id;
M
Matthias Bolte 已提交
3052 3053
    result = 0;

3054 3055 3056 3057
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
3058
    VIR_FREE(taskInfoErrorMessage);
3059 3060 3061 3062

    return result;
}

3063 3064


3065 3066 3067 3068 3069
static int
esxDomainCreate(virDomainPtr domain)
{
    return esxDomainCreateWithFlags(domain, 0);
}
3070

3071 3072


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

3099
    memset(&data, 0, sizeof(data));
3100

3101
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3102
        return NULL;
M
Matthias Bolte 已提交
3103 3104 3105
    }

    /* Parse domain XML */
3106 3107
    def = virDomainDefParseString(xml, priv->caps, priv->xmlopt,
                                  1 << VIR_DOMAIN_VIRT_VMWARE,
M
Matthias Bolte 已提交
3108 3109 3110
                                  VIR_DOMAIN_XML_INACTIVE);

    if (def == NULL) {
M
Matthias Bolte 已提交
3111
        return NULL;
M
Matthias Bolte 已提交
3112 3113 3114
    }

    /* Check if an existing domain should be edited */
3115
    if (esxVI_LookupVirtualMachineByUuid(priv->primary, def->uuid, NULL,
M
Matthias Bolte 已提交
3116
                                         &virtualMachine,
M
Matthias Bolte 已提交
3117
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
3118
        goto cleanup;
M
Matthias Bolte 已提交
3119 3120
    }

3121 3122 3123 3124 3125 3126 3127
    if (virtualMachine == NULL &&
        esxVI_LookupVirtualMachineByName(priv->primary, def->name, NULL,
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
    }

M
Matthias Bolte 已提交
3128 3129
    if (virtualMachine != NULL) {
        /* FIXME */
3130 3131 3132
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Domain already exists, editing existing domains is not "
                         "supported yet"));
M
Matthias Bolte 已提交
3133
        goto cleanup;
M
Matthias Bolte 已提交
3134 3135 3136
    }

    /* Build VMX from domain XML */
3137 3138 3139 3140 3141 3142 3143
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        goto cleanup;
    }

3144
    data.ctx = priv->primary;
3145
    data.datastorePathWithoutFileName = NULL;
3146 3147 3148 3149 3150 3151

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

3152
    vmx = virVMXFormatConfig(&ctx, priv->caps, def, virtualHW_version);
M
Matthias Bolte 已提交
3153 3154

    if (vmx == NULL) {
M
Matthias Bolte 已提交
3155
        goto cleanup;
M
Matthias Bolte 已提交
3156 3157
    }

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

    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) {
3181 3182 3183
        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 已提交
3184
        goto cleanup;
M
Matthias Bolte 已提交
3185 3186
    }

3187
    if (disk->src == NULL) {
3188 3189 3190
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("First file-based harddisk has no source, cannot deduce "
                         "datastore and path for VMX file"));
M
Matthias Bolte 已提交
3191
        goto cleanup;
M
Matthias Bolte 已提交
3192 3193
    }

3194
    if (esxUtil_ParseDatastorePath(disk->src, &datastoreName, &directoryName,
3195
                                   NULL) < 0) {
M
Matthias Bolte 已提交
3196
        goto cleanup;
M
Matthias Bolte 已提交
3197 3198
    }

3199
    if (! virFileHasSuffix(disk->src, ".vmdk")) {
3200 3201 3202
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Expecting source '%s' of first file-based harddisk to "
                         "be a VMDK image"), disk->src);
M
Matthias Bolte 已提交
3203
        goto cleanup;
M
Matthias Bolte 已提交
3204 3205
    }

3206
    virBufferAsprintf(&buffer, "%s://%s:%d/folder/", priv->parsedUri->transport,
M
Matthias Bolte 已提交
3207 3208 3209 3210 3211 3212 3213
                      conn->uri->server, conn->uri->port);

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

3214 3215 3216 3217 3218 3219 3220
    escapedName = esxUtil_EscapeDatastoreItem(def->name);

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

    virBufferURIEncodeString(&buffer, escapedName);
M
Matthias Bolte 已提交
3221
    virBufferAddLit(&buffer, ".vmx?dcPath=");
3222
    virBufferURIEncodeString(&buffer, priv->primary->datacenterPath);
M
Matthias Bolte 已提交
3223 3224 3225 3226
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
3227
        virReportOOMError();
M
Matthias Bolte 已提交
3228
        goto cleanup;
M
Matthias Bolte 已提交
3229 3230 3231 3232
    }

    url = virBufferContentAndReset(&buffer);

3233 3234 3235 3236 3237 3238
    /* Check, if VMX file already exists */
    /* FIXME */

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

3239
    if (esxVI_CURL_Upload(priv->primary->curl, url, vmx) < 0) {
3240 3241 3242 3243
        goto cleanup;
    }

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

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

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3271 3272
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not define domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3273
        goto cleanup;
M
Matthias Bolte 已提交
3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284
    }

    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 已提交
3285 3286 3287 3288
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

M
Matthias Bolte 已提交
3289 3290 3291 3292
    virDomainDefFree(def);
    VIR_FREE(vmx);
    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
3293
    VIR_FREE(escapedName);
M
Matthias Bolte 已提交
3294 3295 3296 3297 3298 3299 3300
    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);
3301
    VIR_FREE(taskInfoErrorMessage);
M
Matthias Bolte 已提交
3302 3303 3304 3305 3306 3307

    return domain;
}



3308
static int
3309 3310
esxDomainUndefineFlags(virDomainPtr domain,
                       unsigned int flags)
3311
{
M
Matthias Bolte 已提交
3312
    int result = -1;
M
Matthias Bolte 已提交
3313
    esxPrivate *priv = domain->conn->privateData;
3314
    esxVI_Context *ctx = NULL;
3315 3316 3317 3318
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

3319 3320 3321 3322
    /* 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);
3323

3324 3325 3326 3327 3328 3329
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

3330
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
3331
        return -1;
3332 3333
    }

3334
    if (esxVI_String_AppendValueToList(&propertyNameList,
3335
                                       "runtime.powerState") < 0 ||
3336 3337
        esxVI_LookupVirtualMachineByUuid(ctx, domain->uuid, propertyNameList,
                                         &virtualMachine,
M
Matthias Bolte 已提交
3338
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3339
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
3340
        goto cleanup;
3341 3342 3343 3344
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended &&
        powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
3345 3346
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not suspended or powered off"));
M
Matthias Bolte 已提交
3347
        goto cleanup;
3348 3349
    }

3350
    if (esxVI_UnregisterVM(ctx, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
3351
        goto cleanup;
3352 3353
    }

M
Matthias Bolte 已提交
3354 3355
    result = 0;

3356 3357 3358 3359 3360 3361 3362 3363
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}


3364 3365 3366 3367 3368
static int
esxDomainUndefine(virDomainPtr domain)
{
    return esxDomainUndefineFlags(domain, 0);
}
3369

3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449
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;
3450
    bool newPowerInfo_isAppended = false;
3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488

    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)) {
3489 3490 3491
                    virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                                   _("Cannot enable general autostart option "
                                     "without affecting other domains"));
3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507
                    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 ||
3508
        esxVI_Int_Alloc(&newPowerInfo->stopDelay) < 0) {
3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519
        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";

3520 3521 3522 3523 3524 3525 3526
    if (esxVI_AutoStartPowerInfo_AppendToList(&spec->powerInfo,
                                              newPowerInfo) < 0) {
        goto cleanup;
    }

    newPowerInfo_isAppended = true;

3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547
    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);

3548 3549 3550 3551
    if (!newPowerInfo_isAppended) {
        esxVI_AutoStartPowerInfo_Free(&newPowerInfo);
    }

3552 3553 3554 3555 3556
    return result;
}



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

    if (type == NULL) {
3593
        virReportOOMError();
3594
        return NULL;
3595 3596
    }

3597 3598 3599
    if (nparams != NULL) {
        *nparams = 3; /* reservation, limit, shares */
    }
3600 3601 3602 3603 3604 3605 3606

    return type;
}



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

3620 3621
    virCheckFlags(0, -1);

3622
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3623
        return -1;
3624 3625
    }

3626
    if (esxVI_String_AppendValueListToList(&propertyNameList,
3627 3628 3629
                                           "config.cpuAllocation.reservation\0"
                                           "config.cpuAllocation.limit\0"
                                           "config.cpuAllocation.shares\0") < 0 ||
3630
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
3631
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3632
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3633
        goto cleanup;
3634 3635 3636
    }

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

            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:
3696 3697 3698
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Shares level has unknown value %d"),
                               (int)sharesInfo->level);
M
Matthias Bolte 已提交
3699
                goto cleanup;
3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711
            }

            esxVI_SharesInfo_Free(&sharesInfo);

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

    *nparams = i;
M
Matthias Bolte 已提交
3712
    result = 0;
3713 3714 3715 3716 3717 3718 3719 3720

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

    return result;
}

3721 3722 3723 3724 3725 3726
static int
esxDomainGetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int *nparams)
{
    return esxDomainGetSchedulerParametersFlags(domain, params, nparams, 0);
}
3727 3728 3729


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

3744
    virCheckFlags(0, -1);
3745 3746 3747 3748 3749 3750 3751 3752 3753
    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;
3754

3755
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3756
        return -1;
3757 3758
    }

3759
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3760
          (priv->primary, domain->uuid, NULL, &virtualMachine,
3761
           priv->parsedUri->autoAnswer) < 0 ||
3762 3763
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->cpuAllocation) < 0) {
M
Matthias Bolte 已提交
3764
        goto cleanup;
3765 3766 3767
    }

    for (i = 0; i < nparams; ++i) {
3768
        if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_RESERVATION)) {
3769
            if (esxVI_Long_Alloc(&spec->cpuAllocation->reservation) < 0) {
M
Matthias Bolte 已提交
3770
                goto cleanup;
3771 3772 3773
            }

            if (params[i].value.l < 0) {
3774 3775 3776
                virReportError(VIR_ERR_INVALID_ARG,
                               _("Could not set reservation to %lld MHz, expecting "
                                 "positive value"), params[i].value.l);
M
Matthias Bolte 已提交
3777
                goto cleanup;
3778 3779 3780
            }

            spec->cpuAllocation->reservation->value = params[i].value.l;
3781
        } else if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_LIMIT)) {
3782
            if (esxVI_Long_Alloc(&spec->cpuAllocation->limit) < 0) {
M
Matthias Bolte 已提交
3783
                goto cleanup;
3784 3785 3786
            }

            if (params[i].value.l < -1) {
3787 3788 3789 3790
                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 已提交
3791
                goto cleanup;
3792 3793 3794
            }

            spec->cpuAllocation->limit->value = params[i].value.l;
3795
        } else if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_SHARES)) {
3796 3797
            if (esxVI_SharesInfo_Alloc(&sharesInfo) < 0 ||
                esxVI_Int_Alloc(&sharesInfo->shares) < 0) {
M
Matthias Bolte 已提交
3798
                goto cleanup;
3799 3800 3801 3802
            }

            spec->cpuAllocation->shares = sharesInfo;

3803
            if (params[i].value.i >= 0) {
3804
                spec->cpuAllocation->shares->level = esxVI_SharesLevel_Custom;
3805
                spec->cpuAllocation->shares->shares->value = params[i].value.i;
3806
            } else {
3807
                switch (params[i].value.i) {
3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825
                  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:
3826 3827 3828 3829
                    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 已提交
3830
                    goto cleanup;
3831 3832 3833 3834 3835
                }
            }
        }
    }

3836
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
3837
                              &task) < 0 ||
3838
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3839
                                    esxVI_Occurrence_RequiredItem,
3840
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3841
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3842
        goto cleanup;
3843 3844 3845
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3846 3847 3848
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not change scheduler parameters: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3849
        goto cleanup;
3850 3851
    }

M
Matthias Bolte 已提交
3852 3853
    result = 0;

3854 3855 3856 3857
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
3858
    VIR_FREE(taskInfoErrorMessage);
3859 3860 3861 3862

    return result;
}

3863 3864 3865 3866 3867 3868
static int
esxDomainSetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int nparams)
{
    return esxDomainSetSchedulerParametersFlags(domain, params, nparams, 0);
}
3869

E
Eric Blake 已提交
3870 3871 3872 3873 3874 3875
/* 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)
3876 3877 3878 3879 3880

static int
esxDomainMigratePrepare(virConnectPtr dconn,
                        char **cookie ATTRIBUTE_UNUSED,
                        int *cookielen ATTRIBUTE_UNUSED,
3881 3882
                        const char *uri_in ATTRIBUTE_UNUSED,
                        char **uri_out,
E
Eric Blake 已提交
3883
                        unsigned long flags,
3884 3885 3886
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
3887
    esxPrivate *priv = dconn->privateData;
3888

E
Eric Blake 已提交
3889 3890
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

3891
    if (uri_in == NULL) {
3892 3893 3894 3895
        if (virAsprintf(uri_out, "vpxmigr://%s/%s/%s",
                        priv->vCenter->ipAddress,
                        priv->vCenter->computeResource->resourcePool->value,
                        priv->vCenter->hostSystem->_reference->value) < 0) {
3896
            virReportOOMError();
3897
            return -1;
3898 3899 3900
        }
    }

3901
    return 0;
3902 3903 3904 3905 3906 3907 3908 3909 3910
}



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

E
Eric Blake 已提交
3929 3930
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

M
Matthias Bolte 已提交
3931
    if (priv->vCenter == NULL) {
3932 3933
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration not possible without a vCenter"));
M
Matthias Bolte 已提交
3934
        return -1;
3935 3936 3937
    }

    if (dname != NULL) {
3938 3939
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Renaming domains on migration not supported"));
M
Matthias Bolte 已提交
3940
        return -1;
3941 3942
    }

3943
    if (esxVI_EnsureSession(priv->vCenter) < 0) {
M
Matthias Bolte 已提交
3944
        return -1;
3945 3946
    }

3947
    /* Parse migration URI */
3948
    if (!(parsedUri = virURIParse(uri)))
M
Matthias Bolte 已提交
3949
        return -1;
3950

3951
    if (parsedUri->scheme == NULL || STRCASENEQ(parsedUri->scheme, "vpxmigr")) {
3952 3953
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Only vpxmigr:// migration URIs are supported"));
M
Matthias Bolte 已提交
3954
        goto cleanup;
3955 3956
    }

3957
    if (STRCASENEQ(priv->vCenter->ipAddress, parsedUri->server)) {
3958 3959 3960
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration source and destination have to refer to "
                         "the same vCenter"));
3961 3962 3963 3964 3965 3966 3967
        goto cleanup;
    }

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

    if (path_resourcePool == NULL || path_hostSystem == NULL) {
3968 3969
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration URI has to specify resource pool and host system"));
M
Matthias Bolte 已提交
3970
        goto cleanup;
3971 3972
    }

3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985
    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,
3986
           priv->parsedUri->autoAnswer) < 0) {
M
Matthias Bolte 已提交
3987
        goto cleanup;
3988 3989 3990
    }

    /* Validate the purposed migration */
3991
    if (esxVI_ValidateMigration(priv->vCenter, virtualMachine->obj,
3992 3993
                                esxVI_VirtualMachinePowerState_Undefined, NULL,
                                &resourcePool, &hostSystem, &eventList) < 0) {
M
Matthias Bolte 已提交
3994
        goto cleanup;
3995 3996 3997 3998 3999 4000 4001 4002
    }

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

M
Matthias Bolte 已提交
4012
        goto cleanup;
4013 4014 4015
    }

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

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4029 4030 4031 4032
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not migrate domain, migration task finished with "
                         "an error: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4033
        goto cleanup;
4034 4035
    }

M
Matthias Bolte 已提交
4036 4037
    result = 0;

4038
  cleanup:
4039
    virURIFree(parsedUri);
4040 4041 4042
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Event_Free(&eventList);
    esxVI_ManagedObjectReference_Free(&task);
4043
    VIR_FREE(taskInfoErrorMessage);
4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054

    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 已提交
4055
                       unsigned long flags)
4056
{
E
Eric Blake 已提交
4057 4058
    virCheckFlags(ESX_MIGRATION_FLAGS, NULL);

4059 4060 4061 4062 4063
    return esxDomainLookupByName(dconn, dname);
}



M
Matthias Bolte 已提交
4064 4065 4066 4067
static unsigned long long
esxNodeGetFreeMemory(virConnectPtr conn)
{
    unsigned long long result = 0;
M
Matthias Bolte 已提交
4068
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
4069 4070 4071 4072 4073
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *resourcePool = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ResourcePoolResourceUsage *resourcePoolResourceUsage = NULL;

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

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

    for (dynamicProperty = resourcePool->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.memory")) {
            if (esxVI_ResourcePoolResourceUsage_CastFromAnyType
4093
                  (dynamicProperty->val, &resourcePoolResourceUsage) < 0) {
M
Matthias Bolte 已提交
4094
                goto cleanup;
M
Matthias Bolte 已提交
4095 4096 4097 4098 4099 4100 4101 4102 4103
            }

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

    if (resourcePoolResourceUsage == NULL) {
4104 4105
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not retrieve memory usage of resource pool"));
M
Matthias Bolte 已提交
4106
        goto cleanup;
M
Matthias Bolte 已提交
4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120
    }

    result = resourcePoolResourceUsage->unreservedForVm->value;

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

    return result;
}



4121 4122 4123
static int
esxIsEncrypted(virConnectPtr conn)
{
M
Matthias Bolte 已提交
4124
    esxPrivate *priv = conn->privateData;
4125

4126
    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137
        return 1;
    } else {
        return 0;
    }
}



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

4140
    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
4141 4142 4143 4144 4145 4146 4147 4148
        return 1;
    } else {
        return 0;
    }
}



4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165
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;
}



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

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

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

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

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

    return result;
}



static int
4204
esxDomainIsPersistent(virDomainPtr domain)
4205
{
4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225
    /* 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;
4226 4227
}

M
Matthias Bolte 已提交
4228 4229


4230 4231 4232
static int
esxDomainIsUpdated(virDomainPtr domain ATTRIBUTE_UNUSED)
{
4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252
    /* 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;
4253
}
4254

M
Matthias Bolte 已提交
4255 4256


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

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

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

4278
    def = virDomainSnapshotDefParseString(xmlDesc, priv->caps,
4279
                                          priv->xmlopt, 0, 0);
4280 4281

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

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

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

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

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

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

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

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

    return snapshot;
}



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

4351 4352
    virCheckFlags(0, NULL);

4353
    memset(&def, 0, sizeof(def));
4354

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

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

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

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

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

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

  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return xml;
}



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

4400
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
4401 4402
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4403 4404

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) == 0;
4405
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4406

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

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

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

4420 4421
    count = esxVI_GetNumberOfSnapshotTrees(rootSnapshotTreeList, recurse,
                                           leaves);
4422 4423 4424

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

M
Matthias Bolte 已提交
4425
    return count;
4426 4427 4428 4429 4430 4431
}



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

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
4441 4442
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4443

4444
    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) == 0;
4445
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4446

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

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

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

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

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

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



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

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
4486 4487
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4488 4489

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

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

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;
4531
    bool leaves;
4532 4533

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
4534 4535
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4536 4537

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) != 0;
4538
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4539 4540

    if (names == NULL || nameslen < 0) {
4541
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567
        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,
4568
                                        names, nameslen, recurse, leaves);
4569 4570 4571 4572 4573 4574 4575 4576 4577

cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



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

4587 4588
    virCheckFlags(0, NULL);

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

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

4617
    virCheckFlags(0, -1);
4618

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

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

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

M
Matthias Bolte 已提交
4634
    return 0;
4635 4636 4637 4638
}



E
Eric Blake 已提交
4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662
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) {
4663 4664 4665
        virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                       _("snapshot '%s' does not have a parent"),
                       snapshotTree->name);
E
Eric Blake 已提交
4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678
        goto cleanup;
    }

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

cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return parent;
}



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

4686
    virCheckFlags(0, NULL);
4687

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

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

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

    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return snapshot;
}


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 4768 4769 4770 4771 4772 4773 4774
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;
}

4775 4776 4777 4778

static int
esxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4779
    int result = -1;
4780 4781 4782 4783 4784
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
4785
    char *taskInfoErrorMessage = NULL;
4786

4787
    virCheckFlags(0, -1);
4788

4789
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4790
        return -1;
4791 4792
    }

4793
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4794 4795
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
4796
                                    &snapshotTree, NULL,
4797
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4798
        goto cleanup;
4799 4800
    }

4801
    if (esxVI_RevertToSnapshot_Task(priv->primary, snapshotTree->snapshot, NULL,
4802
                                    esxVI_Boolean_Undefined, &task) < 0 ||
4803
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4804
                                    esxVI_Occurrence_RequiredItem,
4805
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4806
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4807
        goto cleanup;
4808 4809 4810
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4811 4812 4813
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not revert to snapshot '%s': %s"), snapshot->name,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4814
        goto cleanup;
4815 4816
    }

M
Matthias Bolte 已提交
4817 4818
    result = 0;

4819 4820 4821
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4822
    VIR_FREE(taskInfoErrorMessage);
4823 4824 4825 4826 4827 4828 4829 4830 4831

    return result;
}



static int
esxDomainSnapshotDelete(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4832
    int result = -1;
4833 4834 4835 4836 4837 4838
    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;
4839
    char *taskInfoErrorMessage = NULL;
4840

4841 4842
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
                  VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY, -1);
4843

4844
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4845
        return -1;
4846 4847 4848 4849 4850 4851
    }

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

4852
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4853 4854
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
4855
                                    &snapshotTree, NULL,
4856
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4857
        goto cleanup;
4858 4859
    }

4860 4861 4862 4863 4864 4865 4866
    /* 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;
    }

4867
    if (esxVI_RemoveSnapshot_Task(priv->primary, snapshotTree->snapshot,
4868
                                  removeChildren, &task) < 0 ||
4869
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4870
                                    esxVI_Occurrence_RequiredItem,
4871
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4872
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4873
        goto cleanup;
4874 4875 4876
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4877 4878 4879
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not delete snapshot '%s': %s"), snapshot->name,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4880
        goto cleanup;
4881 4882
    }

M
Matthias Bolte 已提交
4883 4884
    result = 0;

4885 4886 4887
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4888
    VIR_FREE(taskInfoErrorMessage);
4889 4890 4891 4892 4893 4894

    return result;
}



4895
static int
4896
esxDomainSetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
4897 4898 4899 4900 4901 4902 4903 4904
                             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;
4905
    char *taskInfoErrorMessage = NULL;
4906 4907 4908
    int i;

    virCheckFlags(0, -1);
4909 4910 4911 4912 4913
    if (virTypedParameterArrayValidate(params, nparams,
                                       VIR_DOMAIN_MEMORY_MIN_GUARANTEE,
                                       VIR_TYPED_PARAM_ULLONG,
                                       NULL) < 0)
        return -1;
4914 4915 4916 4917 4918 4919 4920

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

    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4921
           priv->parsedUri->autoAnswer) < 0 ||
4922 4923 4924 4925 4926 4927
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0) {
        goto cleanup;
    }

    for (i = 0; i < nparams; ++i) {
4928
        if (STREQ(params[i].field, VIR_DOMAIN_MEMORY_MIN_GUARANTEE)) {
4929 4930 4931 4932 4933
            if (esxVI_Long_Alloc(&spec->memoryAllocation->reservation) < 0) {
                goto cleanup;
            }

            spec->memoryAllocation->reservation->value =
4934
              VIR_DIV_UP(params[i].value.ul, 1024); /* Scale from kilobytes to megabytes */
4935 4936 4937 4938 4939 4940 4941
        }
    }

    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
4942
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4943
                                    &taskInfoErrorMessage) < 0) {
4944 4945 4946 4947
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4948 4949 4950
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not change memory parameters: %s"),
                       taskInfoErrorMessage);
4951 4952 4953 4954 4955 4956 4957 4958 4959
        goto cleanup;
    }

    result = 0;

  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
4960
    VIR_FREE(taskInfoErrorMessage);
4961 4962 4963 4964 4965 4966 4967

    return result;
}



static int
4968
esxDomainGetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997
                             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;
    }

4998 4999 5000 5001
    /* Scale from megabytes to kilobytes */
    if (virTypedParameterAssign(params, VIR_DOMAIN_MEMORY_MIN_GUARANTEE,
                                VIR_TYPED_PARAM_ULLONG,
                                reservation->value * 1024) < 0)
5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014
        goto cleanup;

    *nparams = 1;
    result = 0;

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

    return result;
}

5015 5016 5017 5018 5019 5020 5021 5022
#define MATCH(FLAG) (flags & (FLAG))
static int
esxListAllDomains(virConnectPtr conn,
                  virDomainPtr **domains,
                  unsigned int flags)
{
    int ret = -1;
    esxPrivate *priv = conn->privateData;
5023 5024
    bool needIdentity;
    bool needPowerState;
5025 5026 5027
    virDomainPtr dom;
    virDomainPtr *doms = NULL;
    size_t ndoms = 0;
5028
    esxVI_String *propertyNameList = NULL;
5029 5030
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
5031
    esxVI_AutoStartDefaults *autoStartDefaults = NULL;
5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048
    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
     */
5049
    if ((MATCH(VIR_CONNECT_LIST_DOMAINS_TRANSIENT) &&
5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060
         !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;
    }

5061
    if (esxVI_EnsureSession(priv->primary) < 0)
5062 5063 5064 5065 5066
        return -1;

    /* check system default autostart value */
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_AUTOSTART)) {
        if (esxVI_LookupAutoStartDefaults(priv->primary,
5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087
                                          &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) {
5088
            goto cleanup;
5089 5090 5091 5092 5093 5094
        }
    }

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

5096 5097 5098
    if (needPowerState) {
        if (esxVI_String_AppendValueToList(&propertyNameList,
                                           "runtime.powerState") < 0) {
5099
            goto cleanup;
5100
        }
5101 5102
    }

5103
    if (esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114
                                       &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) {
5115 5116
        if (needIdentity) {
            VIR_FREE(name);
5117

5118 5119 5120 5121 5122
            if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id,
                                                &name, uuid) < 0) {
                goto cleanup;
            }
        }
5123

5124 5125 5126 5127 5128 5129
        if (needPowerState) {
            if (esxVI_GetVirtualMachinePowerState(virtualMachine,
                                                  &powerState) < 0) {
                goto cleanup;
            }
        }
5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140

        /* 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)) {
5141 5142
            esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

5143 5144 5145 5146 5147 5148
            if (esxVI_LookupRootSnapshotTreeList(priv->primary, uuid,
                                                 &rootSnapshotTreeList) < 0) {
                goto cleanup;
            }

            if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT) &&
5149
                   rootSnapshotTreeList != NULL) ||
5150
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT) &&
5151
                   rootSnapshotTreeList == NULL)))
5152 5153 5154 5155 5156 5157 5158
                continue;
        }

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

5159 5160 5161 5162 5163 5164
            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;
5165

5166 5167
                        break;
                    }
5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180
                }
            }

            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);
5181

5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200
            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;
        }

5201
        if (VIR_RESIZE_N(doms, ndoms, count, 2) < 0)
5202 5203
            goto no_memory;

5204 5205 5206
        if (!(dom = virGetDomain(conn, name, uuid)))
            goto cleanup;

5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223
        /* 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++) {
5224
            virDomainFree(doms[id]);
5225
        }
5226 5227

        VIR_FREE(doms);
5228
    }
5229

5230
    VIR_FREE(name);
5231 5232
    esxVI_AutoStartDefaults_Free(&autoStartDefaults);
    esxVI_AutoStartPowerInfo_Free(&powerInfoList);
5233 5234
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
5235 5236
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

5237 5238 5239 5240 5241 5242 5243
    return ret;

no_memory:
    virReportOOMError();
    goto cleanup;
}
#undef MATCH
5244 5245


5246
static virDriver esxDriver = {
5247 5248
    .no = VIR_DRV_ESX,
    .name = "ESX",
5249 5250 5251 5252 5253 5254 5255 5256 5257 5258
    .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 */
5259
    .listAllDomains = esxListAllDomains, /* 0.10.2 */
5260 5261 5262 5263 5264 5265
    .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 */
5266
    .domainShutdownFlags = esxDomainShutdownFlags, /* 0.9.10 */
5267 5268
    .domainReboot = esxDomainReboot, /* 0.7.0 */
    .domainDestroy = esxDomainDestroy, /* 0.7.0 */
5269
    .domainDestroyFlags = esxDomainDestroyFlags, /* 0.9.4 */
5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290
    .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 */
5291
    .domainUndefineFlags = esxDomainUndefineFlags, /* 0.9.4 */
5292 5293 5294 5295
    .domainGetAutostart = esxDomainGetAutostart, /* 0.9.0 */
    .domainSetAutostart = esxDomainSetAutostart, /* 0.9.0 */
    .domainGetSchedulerType = esxDomainGetSchedulerType, /* 0.7.0 */
    .domainGetSchedulerParameters = esxDomainGetSchedulerParameters, /* 0.7.0 */
5296
    .domainGetSchedulerParametersFlags = esxDomainGetSchedulerParametersFlags, /* 0.9.2 */
5297
    .domainSetSchedulerParameters = esxDomainSetSchedulerParameters, /* 0.7.0 */
5298
    .domainSetSchedulerParametersFlags = esxDomainSetSchedulerParametersFlags, /* 0.9.2 */
5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311
    .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 */
5312 5313
    .domainSnapshotNumChildren = esxDomainSnapshotNumChildren, /* 0.9.7 */
    .domainSnapshotListChildrenNames = esxDomainSnapshotListChildrenNames, /* 0.9.7 */
5314 5315
    .domainSnapshotLookupByName = esxDomainSnapshotLookupByName, /* 0.8.0 */
    .domainHasCurrentSnapshot = esxDomainHasCurrentSnapshot, /* 0.8.0 */
E
Eric Blake 已提交
5316
    .domainSnapshotGetParent = esxDomainSnapshotGetParent, /* 0.9.7 */
5317 5318
    .domainSnapshotCurrent = esxDomainSnapshotCurrent, /* 0.8.0 */
    .domainRevertToSnapshot = esxDomainRevertToSnapshot, /* 0.8.0 */
5319 5320
    .domainSnapshotIsCurrent = esxDomainSnapshotIsCurrent, /* 0.9.13 */
    .domainSnapshotHasMetadata = esxDomainSnapshotHasMetadata, /* 0.9.13 */
5321
    .domainSnapshotDelete = esxDomainSnapshotDelete, /* 0.8.0 */
5322
    .isAlive = esxIsAlive, /* 0.9.8 */
5323 5324 5325 5326 5327 5328 5329
};



int
esxRegister(void)
{
5330 5331 5332 5333 5334
    if (virRegisterDriver(&esxDriver) < 0 ||
        esxInterfaceRegister() < 0 ||
        esxNetworkRegister() < 0 ||
        esxStorageRegister() < 0 ||
        esxDeviceRegister() < 0 ||
M
Matthias Bolte 已提交
5335 5336
        esxSecretRegister() < 0 ||
        esxNWFilterRegister() < 0) {
5337 5338
        return -1;
    }
5339 5340 5341

    return 0;
}