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

#include <config.h>

#include "internal.h"
#include "domain_conf.h"
28
#include "snapshot_conf.h"
29
#include "virauth.h"
30
#include "viralloc.h"
31
#include "virfile.h"
32
#include "virlog.h"
33
#include "viruuid.h"
34
#include "vmx.h"
35
#include "virtypedparam.h"
36
#include "esx_driver.h"
37 38 39 40
#include "esx_interface_driver.h"
#include "esx_network_driver.h"
#include "esx_storage_driver.h"
#include "esx_private.h"
41 42 43
#include "esx_vi.h"
#include "esx_vi_methods.h"
#include "esx_util.h"
44
#include "esx_stream.h"
45
#include "virstring.h"
46
#include "viruri.h"
47 48 49

#define VIR_FROM_THIS VIR_FROM_ESX

50 51
VIR_LOG_INIT("esx.esx_driver");

52 53
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
static void
esxFreePrivate(esxPrivate **priv)
{
66
    if (!priv || !(*priv))
67 68 69 70 71
        return;

    esxVI_Context_Free(&(*priv)->host);
    esxVI_Context_Free(&(*priv)->vCenter);
    esxUtil_FreeParsedUri(&(*priv)->parsedUri);
72
    virObjectUnref((*priv)->caps);
73
    virObjectUnref((*priv)->xmlopt);
74 75 76 77 78
    VIR_FREE(*priv);
}



79
/*
80 81
 * Parse a file name from a .vmx file and convert it to datastore path format
 * if possbile. A .vmx file can contain file names in various formats:
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
 *
 * - A single name referencing a file in the same directory as the .vmx file:
 *
 *     test1.vmdk
 *
 * - An absolute file name referencing a file in a datastore that is mounted at
 *   /vmfs/volumes/<datastore>:
 *
 *     /vmfs/volumes/b24b7a78-9d82b4f5/test1/test1.vmdk
 *     /vmfs/volumes/datastore1/test1/test1.vmdk
 *
 *   The actual mount directory is /vmfs/volumes/b24b7a78-9d82b4f5, the second
 *   form is a symlink to it using the datastore name. This is the typical
 *   setup on an ESX(i) server.
 *
 * - With GSX installed on Windows there are also Windows style file names
 *   including UNC file names:
 *
 *     C:\Virtual Machines\test1\test1.vmdk
 *     \\nas1\storage1\test1\test1.vmdk
 *
103 104 105 106 107 108 109 110
 * - There might also be absolute file names referencing files outside of a
 *   datastore:
 *
 *     /usr/lib/vmware/isoimages/linux.iso
 *
 *   Such file names are left as is and are not converted to datastore path
 *   format because this is not possible.
 *
111 112 113 114 115 116 117
 * The datastore path format typically looks like this:
 *
 *  [datastore1] test1/test1.vmdk
 *
 * Firstly this functions checks if the given file name contains a separator.
 * If it doesn't then the referenced file is in the same directory as the .vmx
 * file. The datastore name and directory of the .vmx file are passed to this
118
 * function via the opaque parameter by the caller of virVMXParseConfig.
119 120 121 122 123 124 125 126 127
 *
 * Otherwise query for all known datastores and their mount directories. Then
 * try to find a datastore with a mount directory that is a prefix to the given
 * file name. This mechanism covers the Windows style file names too.
 *
 * The symlinks using the datastore name (/vmfs/volumes/datastore1) are an
 * exception and need special handling. Parse the datastore name and use it
 * to lookup the datastore by name to verify that it exists.
 */
128
static char *
129
esxParseVMXFileName(const char *fileName, void *opaque)
130
{
131
    char *result = NULL;
132
    esxVMX_Data *data = opaque;
133
    esxVI_String *propertyNameList = NULL;
134
    esxVI_ObjectContent *datastoreList = NULL;
135
    esxVI_ObjectContent *datastore = NULL;
136 137 138 139 140 141 142 143
    esxVI_DatastoreHostMount *hostMount = NULL;
    char *datastoreName;
    char *tmp;
    char *saveptr;
    char *strippedFileName = NULL;
    char *copyOfFileName = NULL;
    char *directoryAndFileName;

144
    if (!strchr(fileName, '/') && !strchr(fileName, '\\')) {
145
        /* Plain file name, use same directory as for the .vmx file */
146
        if (virAsprintf(&result, "%s/%s",
147
                        data->datastorePathWithoutFileName, fileName) < 0)
148 149 150 151 152 153 154 155
            goto cleanup;
    } else {
        if (esxVI_String_AppendValueToList(&propertyNameList,
                                           "summary.name") < 0 ||
            esxVI_LookupDatastoreList(data->ctx, propertyNameList,
                                      &datastoreList) < 0) {
            return NULL;
        }
156

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

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

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

173
            if (!tmp)
174
                continue;
175

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

180
            if (VIR_STRDUP(strippedFileName, tmp) < 0)
181
                goto cleanup;
182

183
            tmp = strippedFileName;
184

185 186
            /* Convert \ to / */
            while (*tmp != '\0') {
187
                if (*tmp == '\\')
188
                    *tmp = '/';
189

190 191
                ++tmp;
            }
192

193
            if (virAsprintf(&result, "[%s] %s", datastoreName,
194
                            strippedFileName) < 0)
195
                goto cleanup;
196

197 198
            break;
        }
199

200
        /* Fallback to direct datastore name match */
201
        if (!result && STRPREFIX(fileName, "/vmfs/volumes/")) {
202
            if (VIR_STRDUP(copyOfFileName, fileName) < 0)
203
                goto cleanup;
204

205
            /* Expected format: '/vmfs/volumes/<datastore>/<path>' */
206 207 208
            if (!(tmp = STRSKIP(copyOfFileName, "/vmfs/volumes/")) ||
                !(datastoreName = strtok_r(tmp, "/", &saveptr))    ||
                !(directoryAndFileName = strtok_r(NULL, "", &saveptr))) {
209 210 211
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("File name '%s' doesn't have expected format "
                                 "'/vmfs/volumes/<datastore>/<path>'"), fileName);
212 213
                goto cleanup;
            }
214

215
            esxVI_ObjectContent_Free(&datastoreList);
216

217 218 219 220 221
            if (esxVI_LookupDatastoreByName(data->ctx, datastoreName,
                                            NULL, &datastoreList,
                                            esxVI_Occurrence_OptionalItem) < 0) {
                goto cleanup;
            }
222

223
            if (!datastoreList) {
224 225 226
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("File name '%s' refers to non-existing datastore '%s'"),
                               fileName, datastoreName);
227 228
                goto cleanup;
            }
229

230
            if (virAsprintf(&result, "[%s] %s", datastoreName,
231
                            directoryAndFileName) < 0)
232
                goto cleanup;
233 234
        }

235
        /* If it's an absolute path outside of a datastore just use it as is */
236
        if (!result && *fileName == '/') {
237
            /* FIXME: need to deal with Windows paths here too */
238
            if (VIR_STRDUP(result, fileName) < 0)
239 240 241
                goto cleanup;
        }

242
        if (!result) {
243 244
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not handle file name '%s'"), fileName);
245
            goto cleanup;
246
        }
247
    }
248

249
 cleanup:
250 251 252 253 254
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&datastoreList);
    esxVI_DatastoreHostMount_Free(&hostMount);
    VIR_FREE(strippedFileName);
    VIR_FREE(copyOfFileName);
255

256
    return result;
257 258 259 260
}



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

289 290 291 292 293 294
    if (*fileName == '[') {
        /* Parse datastore path and lookup datastore */
        if (esxUtil_ParseDatastorePath(fileName, &datastoreName, NULL,
                                       &directoryAndFileName) < 0) {
            goto cleanup;
        }
295

296 297 298
        if (esxVI_LookupDatastoreByName(data->ctx, datastoreName, NULL, &datastore,
                                        esxVI_Occurrence_RequiredItem) < 0 ||
            esxVI_LookupDatastoreHostMount(data->ctx, datastore->obj,
299 300
                                           &hostMount,
                                           esxVI_Occurrence_RequiredItem) < 0) {
301 302
            goto cleanup;
        }
303

304
        /* Detect separator type */
305
        if (strchr(hostMount->mountInfo->path, '\\'))
306
            separator = '\\';
307

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

311
        while (length > 0 && hostMount->mountInfo->path[length - 1] == separator)
312
            --length;
313

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

317 318
        if (separator != '/') {
            tmp = directoryAndFileName;
319

320
            while (*tmp != '\0') {
321
                if (*tmp == '/')
322
                    *tmp = separator;
323

324 325
                ++tmp;
            }
326
        }
327

328 329
        virBufferAddChar(&buffer, separator);
        virBufferAdd(&buffer, directoryAndFileName, -1);
330

331
        if (virBufferCheckError(&buffer) < 0)
332 333 334 335 336
            goto cleanup;

        result = virBufferContentAndReset(&buffer);
    } else if (*fileName == '/') {
        /* FIXME: need to deal with Windows paths here too */
337
        if (VIR_STRDUP(result, fileName) < 0)
338 339
            goto cleanup;
    } else {
340 341
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not handle file name '%s'"), fileName);
342 343 344 345 346 347 348
        goto cleanup;
    }

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

    success = true;

349
 cleanup:
350
    if (! success) {
351
        virBufferFreeAndReset(&buffer);
352
        VIR_FREE(result);
353 354 355
    }

    VIR_FREE(datastoreName);
356
    VIR_FREE(directoryAndFileName);
357 358
    esxVI_ObjectContent_Free(&datastore);
    esxVI_DatastoreHostMount_Free(&hostMount);
359

360
    return result;
361 362 363 364 365 366 367 368 369 370
}



static int
esxAutodetectSCSIControllerModel(virDomainDiskDefPtr def, int *model,
                                 void *opaque)
{
    int result = -1;
    esxVMX_Data *data = opaque;
371
    esxVI_FileInfo *fileInfo = NULL;
372
    esxVI_VmDiskFileInfo *vmDiskFileInfo = NULL;
373
    const char *src = virDomainDiskGetSource(def);
374 375 376

    if (def->device != VIR_DOMAIN_DISK_DEVICE_DISK ||
        def->bus != VIR_DOMAIN_DISK_BUS_SCSI ||
E
Eric Blake 已提交
377
        virDomainDiskGetType(def) != VIR_STORAGE_TYPE_FILE ||
378
        !src || !STRPREFIX(src, "[")) {
379 380 381 382 383 384 385
        /*
         * This isn't a file-based SCSI disk device with a datastore related
         * source path => do nothing.
         */
        return 0;
    }

386
    if (esxVI_LookupFileInfoByDatastorePath(data->ctx, src,
387
                                            false, &fileInfo,
388
                                            esxVI_Occurrence_RequiredItem) < 0) {
389 390 391
        goto cleanup;
    }

392
    vmDiskFileInfo = esxVI_VmDiskFileInfo_DynamicCast(fileInfo);
393

394
    if (!vmDiskFileInfo || !vmDiskFileInfo->controllerType) {
395
        virReportError(VIR_ERR_INTERNAL_ERROR,
396
                       _("Could not lookup controller model for '%s'"), src);
397 398 399 400 401
        goto cleanup;
    }

    if (STRCASEEQ(vmDiskFileInfo->controllerType,
                  "VirtualBusLogicController")) {
402
        *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_BUSLOGIC;
403 404
    } else if (STRCASEEQ(vmDiskFileInfo->controllerType,
                         "VirtualLsiLogicController")) {
405
        *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC;
406 407
    } else if (STRCASEEQ(vmDiskFileInfo->controllerType,
                         "VirtualLsiLogicSASController")) {
408
        *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSISAS1068;
409 410
    } else if (STRCASEEQ(vmDiskFileInfo->controllerType,
                         "ParaVirtualSCSIController")) {
411
        *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VMPVSCSI;
412
    } else {
413 414
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Found unexpected controller model '%s' for disk '%s'"),
415
                       vmDiskFileInfo->controllerType, src);
416 417 418 419 420
        goto cleanup;
    }

    result = 0;

421
 cleanup:
422
    esxVI_FileInfo_Free(&fileInfo);
423 424 425 426

    return result;
}

427 428


429
static esxVI_Boolean
430
esxSupportsLongMode(esxPrivate *priv)
431 432 433 434 435 436
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_HostCpuIdInfo *hostCpuIdInfoList = NULL;
    esxVI_HostCpuIdInfo *hostCpuIdInfo = NULL;
437
    esxVI_ParsedHostCpuIdInfo parsedHostCpuIdInfo;
438 439
    char edxLongModeBit = '?';

440
    if (priv->supportsLongMode != esxVI_Boolean_Undefined)
441 442
        return priv->supportsLongMode;

443
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
444
        return esxVI_Boolean_Undefined;
445

446
    if (esxVI_String_AppendValueToList(&propertyNameList,
447
                                       "hardware.cpuFeature") < 0 ||
448 449
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
450
        goto cleanup;
451 452
    }

453
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
454 455 456
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuFeature")) {
            if (esxVI_HostCpuIdInfo_CastListFromAnyType
457
                  (dynamicProperty->val, &hostCpuIdInfoList) < 0) {
M
Matthias Bolte 已提交
458
                goto cleanup;
459 460
            }

461
            for (hostCpuIdInfo = hostCpuIdInfoList; hostCpuIdInfo;
462 463
                 hostCpuIdInfo = hostCpuIdInfo->_next) {
                if (hostCpuIdInfo->level->value == -2147483647) { /* 0x80000001 */
464 465
                    if (esxVI_ParseHostCpuIdInfo(&parsedHostCpuIdInfo,
                                                 hostCpuIdInfo) < 0) {
M
Matthias Bolte 已提交
466
                        goto cleanup;
467 468
                    }

469
                    edxLongModeBit = parsedHostCpuIdInfo.edx[29];
470 471 472 473 474 475

                    if (edxLongModeBit == '1') {
                        priv->supportsLongMode = esxVI_Boolean_True;
                    } else if (edxLongModeBit == '0') {
                        priv->supportsLongMode = esxVI_Boolean_False;
                    } else {
476 477 478 479 480
                        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 已提交
481
                        goto cleanup;
482 483 484 485 486 487 488 489 490 491 492 493
                    }

                    break;
                }
            }

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

494
 cleanup:
M
Matthias Bolte 已提交
495 496 497 498
    /*
     * 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.
     */
499 500 501 502 503 504 505 506 507
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_HostCpuIdInfo_Free(&hostCpuIdInfoList);

    return priv->supportsLongMode;
}



508 509 510 511 512 513
static int
esxLookupHostSystemBiosUuid(esxPrivate *priv, unsigned char *uuid)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
514
    char *uuid_string = NULL;
515

516
    if (esxVI_EnsureSession(priv->primary) < 0)
517 518 519 520
        return -1;

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "hardware.systemInfo.uuid") < 0 ||
521
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
522 523 524
                                         &hostSystem) < 0 ||
        esxVI_GetStringValue(hostSystem, "hardware.systemInfo.uuid",
                             &uuid_string, esxVI_Occurrence_RequiredItem) < 0) {
525 526 527
        goto cleanup;
    }

528 529 530
    if (strlen(uuid_string) > 0) {
        if (virUUIDParse(uuid_string, uuid) < 0) {
            VIR_WARN("Could not parse host UUID from string '%s'", uuid_string);
531

532 533
            /* HostSystem has an invalid UUID, ignore it */
            memset(uuid, 0, VIR_UUID_BUFLEN);
534
        }
535 536 537
    } else {
        /* HostSystem has an empty UUID */
        memset(uuid, 0, VIR_UUID_BUFLEN);
538 539 540 541
    }

    result = 0;

542
 cleanup:
543 544 545 546 547 548 549
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}


550
static virCapsPtr
551
esxCapsInit(esxPrivate *priv)
552
{
553
    esxVI_Boolean supportsLongMode = esxSupportsLongMode(priv);
554 555 556
    virCapsPtr caps = NULL;
    virCapsGuestPtr guest = NULL;

557
    if (supportsLongMode == esxVI_Boolean_Undefined)
558 559 560
        return NULL;

    if (supportsLongMode == esxVI_Boolean_True) {
561
        caps = virCapabilitiesNew(VIR_ARCH_X86_64, true, true);
562
    } else {
563
        caps = virCapabilitiesNew(VIR_ARCH_I686, true, true);
564
    }
565

566
    if (!caps)
567 568
        return NULL;

569
    virCapabilitiesAddHostMigrateTransport(caps, "vpxmigr");
570

571

572
    if (esxLookupHostSystemBiosUuid(priv, caps->host.host_uuid) < 0)
573 574
        goto failure;

575
    /* i686 */
576
    guest = virCapabilitiesAddGuest(caps, VIR_DOMAIN_OSTYPE_HVM,
577 578
                                    VIR_ARCH_I686,
                                    NULL, NULL, 0,
579
                                    NULL);
580

581
    if (!guest)
582 583
        goto failure;

584
    if (!virCapabilitiesAddGuestDomain(guest, VIR_DOMAIN_VIRT_VMWARE, NULL, NULL, 0, NULL))
585 586
        goto failure;

587 588
    /* x86_64 */
    if (supportsLongMode == esxVI_Boolean_True) {
589
        guest = virCapabilitiesAddGuest(caps, VIR_DOMAIN_OSTYPE_HVM,
590 591
                                        VIR_ARCH_X86_64,
                                        NULL, NULL,
592 593
                                        0, NULL);

594
        if (!guest)
595 596
            goto failure;

597
        if (!virCapabilitiesAddGuestDomain(guest, VIR_DOMAIN_VIRT_VMWARE, NULL, NULL, 0, NULL))
598 599 600
            goto failure;
    }

601 602
    return caps;

603
 failure:
604
    virObjectUnref(caps);
605 606 607 608 609 610

    return NULL;
}



611
static int
612 613
esxConnectToHost(esxPrivate *priv,
                 virConnectPtr conn,
614
                 virConnectAuthPtr auth,
615 616 617 618 619
                 char **vCenterIpAddress)
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
M
Matthias Bolte 已提交
620
    char *unescapedPassword = NULL;
621 622 623 624 625
    char *password = NULL;
    char *url = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_Boolean inMaintenanceMode = esxVI_Boolean_Undefined;
626 627 628
    esxVI_ProductLine expectedProductLine = STRCASEEQ(conn->uri->scheme, "esx")
        ? esxVI_ProductLine_ESX
        : esxVI_ProductLine_GSX;
629

630
    if (!vCenterIpAddress || *vCenterIpAddress) {
631
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
632 633 634
        return -1;
    }

635
    if (esxUtil_ResolveHostname(conn->uri->server, ipAddress, NI_MAXHOST) < 0)
636 637
        return -1;

638
    if (conn->uri->user) {
639
        if (VIR_STRDUP(username, conn->uri->user) < 0)
640 641
            goto cleanup;
    } else {
642
        username = virAuthGetUsername(conn, auth, "esx", "root", conn->uri->server);
643

644
        if (!username) {
645
            virReportError(VIR_ERR_AUTH_FAILED, "%s", _("Username request failed"));
646 647 648 649
            goto cleanup;
        }
    }

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

652
    if (!unescapedPassword) {
653
        virReportError(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
654 655 656
        goto cleanup;
    }

M
Matthias Bolte 已提交
657 658
    password = esxUtil_EscapeForXml(unescapedPassword);

659
    if (!password)
M
Matthias Bolte 已提交
660 661
        goto cleanup;

662
    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->parsedUri->transport,
663
                    conn->uri->server, conn->uri->port) < 0)
664 665 666 667
        goto cleanup;

    if (esxVI_Context_Alloc(&priv->host) < 0 ||
        esxVI_Context_Connect(priv->host, url, ipAddress, username, password,
668
                              priv->parsedUri) < 0 ||
669
        esxVI_Context_LookupManagedObjects(priv->host) < 0) {
670 671 672
        goto cleanup;
    }

673 674 675 676 677 678 679
    if (priv->host->productLine != expectedProductLine) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Expecting '%s' to be a %s host but found a %s host"),
                       conn->uri->server,
                       esxVI_ProductLineToDisplayName(expectedProductLine),
                       esxVI_ProductLineToDisplayName(priv->host->productLine));
        goto cleanup;
680 681 682 683 684 685
    }

    /* Query the host for maintenance mode and vCenter IP address */
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "runtime.inMaintenanceMode\0"
                                           "summary.managementServerIp\0") < 0 ||
686 687
        esxVI_LookupHostSystemProperties(priv->host, propertyNameList,
                                         &hostSystem) < 0 ||
688 689 690 691 692 693 694 695 696 697
        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 */
698
    if (inMaintenanceMode == esxVI_Boolean_True)
699
        VIR_WARN("The server is in maintenance mode");
700

701 702
    if (VIR_STRDUP(*vCenterIpAddress, *vCenterIpAddress) < 0)
        goto cleanup;
703 704 705

    result = 0;

706
 cleanup:
707
    VIR_FREE(username);
M
Matthias Bolte 已提交
708 709
    VIR_FREE(unescapedPassword);
    VIR_FREE(password);
710 711 712 713 714 715 716 717 718 719
    VIR_FREE(url);
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



static int
720 721
esxConnectToVCenter(esxPrivate *priv,
                    virConnectPtr conn,
722 723
                    virConnectAuthPtr auth,
                    const char *hostname,
724
                    const char *hostSystemIpAddress)
725 726 727 728
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
M
Matthias Bolte 已提交
729
    char *unescapedPassword = NULL;
730 731 732
    char *password = NULL;
    char *url = NULL;

733 734
    if (!hostSystemIpAddress &&
        (!priv->parsedUri->path || STREQ(priv->parsedUri->path, "/"))) {
735 736
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Path has to specify the datacenter and compute resource"));
737 738 739
        return -1;
    }

740
    if (esxUtil_ResolveHostname(hostname, ipAddress, NI_MAXHOST) < 0)
741 742
        return -1;

743
    if (conn->uri->user) {
744
        if (VIR_STRDUP(username, conn->uri->user) < 0)
745 746
            goto cleanup;
    } else {
747
        username = virAuthGetUsername(conn, auth, "esx", "administrator", hostname);
748

749
        if (!username) {
750
            virReportError(VIR_ERR_AUTH_FAILED, "%s", _("Username request failed"));
751 752 753 754
            goto cleanup;
        }
    }

755
    unescapedPassword = virAuthGetPassword(conn, auth, "esx", username, hostname);
756

757
    if (!unescapedPassword) {
758
        virReportError(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
759 760 761
        goto cleanup;
    }

M
Matthias Bolte 已提交
762 763
    password = esxUtil_EscapeForXml(unescapedPassword);

764
    if (!password)
M
Matthias Bolte 已提交
765 766
        goto cleanup;

767
    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->parsedUri->transport,
768
                    hostname, conn->uri->port) < 0)
769 770 771 772
        goto cleanup;

    if (esxVI_Context_Alloc(&priv->vCenter) < 0 ||
        esxVI_Context_Connect(priv->vCenter, url, ipAddress, username,
773
                              password, priv->parsedUri) < 0) {
774 775 776
        goto cleanup;
    }

777
    if (priv->vCenter->productLine != esxVI_ProductLine_VPX) {
778
        virReportError(VIR_ERR_INTERNAL_ERROR,
779 780 781 782
                       _("Expecting '%s' to be a %s host but found a %s host"),
                       hostname,
                       esxVI_ProductLineToDisplayName(esxVI_ProductLine_VPX),
                       esxVI_ProductLineToDisplayName(priv->vCenter->productLine));
783 784 785
        goto cleanup;
    }

786
    if (hostSystemIpAddress) {
787 788
        if (esxVI_Context_LookupManagedObjectsByHostSystemIp
              (priv->vCenter, hostSystemIpAddress) < 0) {
789 790 791
            goto cleanup;
        }
    } else {
792 793
        if (esxVI_Context_LookupManagedObjectsByPath(priv->vCenter,
                                                     priv->parsedUri->path) < 0) {
794 795 796 797
            goto cleanup;
        }
    }

798 799
    result = 0;

800
 cleanup:
801
    VIR_FREE(username);
M
Matthias Bolte 已提交
802 803
    VIR_FREE(unescapedPassword);
    VIR_FREE(password);
804 805 806 807 808 809 810
    VIR_FREE(url);

    return result;
}



811
/*
812 813
 * URI format: {vpx|esx|gsx}://[<username>@]<hostname>[:<port>]/[<path>][?<query parameter>...]
 *             <path> = [<folder>/...]<datacenter>/[<folder>/...]<computeresource>[/<hostsystem>]
814
 *
815 816
 * If no port is specified the default port is set dependent on the scheme and
 * transport parameter:
817 818
 * - vpx+http  80
 * - vpx+https 443
819
 * - esx+http  80
820
 * - esx+https 443
821 822 823
 * - gsx+http  8222
 * - gsx+https 8333
 *
824 825 826
 * 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
827 828
 * can be omitted. As datacenters and computeresources can be organized in
 * folders those have to be included in <path>.
829
 *
830 831
 * Optional query parameters:
 * - transport={http|https}
832
 * - vcenter={<vcenter>|*}             only useful for an esx:// connection
833 834
 * - no_verify={0|1}
 * - auto_answer={0|1}
M
Matthias Bolte 已提交
835
 * - proxy=[{http|socks|socks4|socks4a|socks5}://]<hostname>[:<port>]
836
 *
837 838 839
 * If no transport parameter is specified https is used.
 *
 * The vcenter parameter is only necessary for migration, because the vCenter
840
 * server is in charge to initiate a migration between two ESX hosts. The
841
 * vcenter parameter can be set to an explicitly hostname or to *. If set to *,
842 843
 * 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.
844 845
 *
 * If the no_verify parameter is set to 1, this disables libcurl client checks
846
 * of the server's certificate. The default value is 0.
847 848 849
 *
 * 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
850
 * questions will be reported as errors. The default value is 0.
M
Matthias Bolte 已提交
851 852 853 854
 *
 * 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.
855 856
 */
static virDrvOpenStatus
857 858
esxConnectOpen(virConnectPtr conn, virConnectAuthPtr auth,
               unsigned int flags)
859
{
M
Matthias Bolte 已提交
860
    virDrvOpenStatus result = VIR_DRV_OPEN_ERROR;
861
    char *plus;
862
    esxPrivate *priv = NULL;
863
    char *potentialVCenterIpAddress = NULL;
M
Matthias Bolte 已提交
864
    char vCenterIpAddress[NI_MAXHOST] = "";
865

E
Eric Blake 已提交
866 867
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

868
    /* Decline if the URI is NULL or the scheme is NULL */
869
    if (!conn->uri || !conn->uri->scheme)
870 871
        return VIR_DRV_OPEN_DECLINED;

872 873 874
    /* Decline if the scheme is not one of {vpx|esx|gsx} */
    plus = strchr(conn->uri->scheme, '+');

875
    if (!plus) {
876 877 878 879 880 881 882 883 884 885 886 887 888
        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;
        }

889 890 891
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Transport '%s' in URI scheme is not supported, try again "
                         "without the transport part"), plus + 1);
892 893 894
        return VIR_DRV_OPEN_ERROR;
    }

895
    if (STRCASENEQ(conn->uri->scheme, "vpx") &&
896
        conn->uri->path && STRNEQ(conn->uri->path, "/")) {
897 898 899 900
        VIR_WARN("Ignoring unexpected path '%s' for non-vpx scheme '%s'",
                 conn->uri->path, conn->uri->scheme);
    }

901
    /* Require server part */
902
    if (!conn->uri->server) {
903 904
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("URI is missing the server part"));
905 906 907 908
        return VIR_DRV_OPEN_ERROR;
    }

    /* Require auth */
909
    if (!auth || !auth->cb) {
910 911
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Missing or invalid auth pointer"));
912
        return VIR_DRV_OPEN_ERROR;
913 914 915
    }

    /* Allocate per-connection private data */
916
    if (VIR_ALLOC(priv) < 0)
M
Matthias Bolte 已提交
917
        goto cleanup;
918

919
    if (esxUtil_ParseUri(&priv->parsedUri, conn->uri) < 0)
920 921
        goto cleanup;

M
Matthias Bolte 已提交
922 923
    priv->maxVcpus = -1;
    priv->supportsVMotion = esxVI_Boolean_Undefined;
924
    priv->supportsLongMode = esxVI_Boolean_Undefined;
925
    priv->supportsScreenshot = esxVI_Boolean_Undefined;
926 927
    priv->usedCpuTimeCounterId = -1;

M
Matthias Bolte 已提交
928 929 930 931 932 933 934
    /*
     * 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) {
935 936
        if (STRCASEEQ(conn->uri->scheme, "vpx") ||
            STRCASEEQ(conn->uri->scheme, "esx")) {
937
            if (STRCASEEQ(priv->parsedUri->transport, "https")) {
M
Matthias Bolte 已提交
938 939 940 941 942
                conn->uri->port = 443;
            } else {
                conn->uri->port = 80;
            }
        } else { /* GSX */
943
            if (STRCASEEQ(priv->parsedUri->transport, "https")) {
M
Matthias Bolte 已提交
944 945 946 947
                conn->uri->port = 8333;
            } else {
                conn->uri->port = 8222;
            }
948
        }
M
Matthias Bolte 已提交
949
    }
950

951 952 953
    if (STRCASEEQ(conn->uri->scheme, "esx") ||
        STRCASEEQ(conn->uri->scheme, "gsx")) {
        /* Connect to host */
954
        if (esxConnectToHost(priv, conn, auth,
955
                             &potentialVCenterIpAddress) < 0) {
M
Matthias Bolte 已提交
956
            goto cleanup;
957
        }
958

959
        /* Connect to vCenter */
960
        if (priv->parsedUri->vCenter) {
961
            if (STREQ(priv->parsedUri->vCenter, "*")) {
962
                if (!potentialVCenterIpAddress) {
963 964
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("This host is not managed by a vCenter"));
M
Matthias Bolte 已提交
965
                    goto cleanup;
966 967
                }

968 969
                if (!virStrcpyStatic(vCenterIpAddress,
                                     potentialVCenterIpAddress)) {
970 971 972
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("vCenter IP address %s too big for destination"),
                                   potentialVCenterIpAddress);
973 974 975
                    goto cleanup;
                }
            } else {
976
                if (esxUtil_ResolveHostname(priv->parsedUri->vCenter,
977 978 979
                                            vCenterIpAddress, NI_MAXHOST) < 0) {
                    goto cleanup;
                }
980

981
                if (potentialVCenterIpAddress &&
982
                    STRNEQ(vCenterIpAddress, potentialVCenterIpAddress)) {
983 984 985 986 987 988
                    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 已提交
989
                    goto cleanup;
990 991
                }
            }
992

993
            if (esxConnectToVCenter(priv, conn, auth,
994
                                    vCenterIpAddress,
995
                                    priv->host->ipAddress) < 0) {
996 997
                goto cleanup;
            }
998 999
        }

1000 1001 1002
        priv->primary = priv->host;
    } else { /* VPX */
        /* Connect to vCenter */
1003
        if (esxConnectToVCenter(priv, conn, auth,
1004 1005
                                conn->uri->server,
                                NULL) < 0) {
M
Matthias Bolte 已提交
1006
            goto cleanup;
1007 1008
        }

1009
        priv->primary = priv->vCenter;
1010 1011
    }

M
Matthias Bolte 已提交
1012
    /* Setup capabilities */
1013
    priv->caps = esxCapsInit(priv);
1014

1015
    if (!priv->caps)
M
Matthias Bolte 已提交
1016
        goto cleanup;
1017

1018
    if (!(priv->xmlopt = virVMXDomainXMLConfInit()))
1019 1020
        goto cleanup;

1021 1022
    conn->privateData = priv;
    priv = NULL;
M
Matthias Bolte 已提交
1023
    result = VIR_DRV_OPEN_SUCCESS;
1024

1025
 cleanup:
1026
    esxFreePrivate(&priv);
1027
    VIR_FREE(potentialVCenterIpAddress);
1028

M
Matthias Bolte 已提交
1029
    return result;
1030 1031 1032 1033 1034
}



static int
1035
esxConnectClose(virConnectPtr conn)
1036
{
M
Matthias Bolte 已提交
1037
    esxPrivate *priv = conn->privateData;
E
Eric Blake 已提交
1038
    int result = 0;
1039

1040
    if (priv->host) {
1041 1042 1043 1044 1045
        if (esxVI_EnsureSession(priv->host) < 0 ||
            esxVI_Logout(priv->host) < 0) {
            result = -1;
        }
    }
1046

1047
    if (priv->vCenter) {
E
Eric Blake 已提交
1048 1049 1050 1051
        if (esxVI_EnsureSession(priv->vCenter) < 0 ||
            esxVI_Logout(priv->vCenter) < 0) {
            result = -1;
        }
1052 1053
    }

1054
    esxFreePrivate(&priv);
1055 1056 1057

    conn->privateData = NULL;

E
Eric Blake 已提交
1058
    return result;
1059 1060 1061 1062 1063
}



static esxVI_Boolean
1064
esxSupportsVMotion(esxPrivate *priv)
1065 1066 1067 1068
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;

1069
    if (priv->supportsVMotion != esxVI_Boolean_Undefined)
M
Matthias Bolte 已提交
1070
        return priv->supportsVMotion;
1071

1072
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1073
        return esxVI_Boolean_Undefined;
1074

1075
    if (esxVI_String_AppendValueToList(&propertyNameList,
1076
                                       "capability.vmotionSupported") < 0 ||
1077
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
1078 1079
                                         &hostSystem) < 0 ||
        esxVI_GetBoolean(hostSystem, "capability.vmotionSupported",
1080 1081 1082
                         &priv->supportsVMotion,
                         esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
1083 1084
    }

1085
 cleanup:
M
Matthias Bolte 已提交
1086 1087 1088 1089
    /*
     * 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.
     */
1090 1091 1092
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
1093
    return priv->supportsVMotion;
1094 1095 1096 1097
}



1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
static esxVI_Boolean
esxSupportsScreenshot(esxPrivate *priv)
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;

    if (priv->supportsScreenshot != esxVI_Boolean_Undefined)
        return priv->supportsScreenshot;

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

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "capability.screenshotSupported") < 0 ||
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0 ||
        esxVI_GetBoolean(hostSystem, "capability.screenshotSupported",
                         &priv->supportsScreenshot,
                         esxVI_Occurrence_RequiredItem) < 0)
        goto cleanup;

 cleanup:
    /*
     * If we goto cleanup in case of an error then priv->supportsScreenshot is
     * still esxVI_Boolean_Undefined, therefore we don't need to set it.
     */
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return priv->supportsScreenshot;
}



1132
static int
1133
esxConnectSupportsFeature(virConnectPtr conn, int feature)
1134
{
M
Matthias Bolte 已提交
1135
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1136
    esxVI_Boolean supportsVMotion = esxVI_Boolean_Undefined;
1137 1138 1139

    switch (feature) {
      case VIR_DRV_FEATURE_MIGRATION_V1:
1140
        supportsVMotion = esxSupportsVMotion(priv);
1141

1142
        if (supportsVMotion == esxVI_Boolean_Undefined)
1143 1144
            return -1;

M
Matthias Bolte 已提交
1145
        /* Migration is only possible via a vCenter and if VMotion is enabled */
1146
        return priv->vCenter &&
M
Matthias Bolte 已提交
1147
               supportsVMotion == esxVI_Boolean_True ? 1 : 0;
1148 1149 1150 1151 1152 1153 1154 1155 1156

      default:
        return 0;
    }
}



static const char *
1157
esxConnectGetType(virConnectPtr conn ATTRIBUTE_UNUSED)
1158 1159 1160 1161 1162 1163 1164
{
    return "ESX";
}



static int
1165
esxConnectGetVersion(virConnectPtr conn, unsigned long *version)
1166
{
M
Matthias Bolte 已提交
1167
    esxPrivate *priv = conn->privateData;
1168

1169
    *version = priv->primary->productVersion;
1170 1171 1172 1173 1174 1175 1176

    return 0;
}



static char *
1177
esxConnectGetHostname(virConnectPtr conn)
1178
{
M
Matthias Bolte 已提交
1179
    esxPrivate *priv = conn->privateData;
1180 1181 1182 1183 1184 1185 1186
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    const char *hostName = NULL;
    const char *domainName = NULL;
    char *complete = NULL;

1187
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1188
        return NULL;
1189 1190

    if (esxVI_String_AppendValueListToList
1191
          (&propertyNameList,
1192 1193
           "config.network.dnsConfig.hostName\0"
           "config.network.dnsConfig.domainName\0") < 0 ||
1194 1195
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1196
        goto cleanup;
1197 1198
    }

1199
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
1200 1201 1202
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name,
                  "config.network.dnsConfig.hostName")) {
1203
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1204
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1205
                goto cleanup;
1206 1207 1208 1209 1210
            }

            hostName = dynamicProperty->val->string;
        } else if (STREQ(dynamicProperty->name,
                         "config.network.dnsConfig.domainName")) {
1211
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1212
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1213
                goto cleanup;
1214 1215 1216 1217 1218 1219 1220 1221
            }

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

1222
    if (!hostName || strlen(hostName) < 1) {
1223 1224
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing or empty 'hostName' property"));
M
Matthias Bolte 已提交
1225
        goto cleanup;
1226 1227
    }

1228
    if (!domainName || strlen(domainName) < 1) {
1229
        if (VIR_STRDUP(complete, hostName) < 0)
M
Matthias Bolte 已提交
1230
            goto cleanup;
1231
    } else {
1232
        if (virAsprintf(&complete, "%s.%s", hostName, domainName) < 0)
M
Matthias Bolte 已提交
1233
            goto cleanup;
1234 1235
    }

1236
 cleanup:
M
Matthias Bolte 已提交
1237 1238
    /*
     * If we goto cleanup in case of an error then complete is still NULL,
1239
     * either VIR_STRDUP returned -1 or virAsprintf failed. When virAsprintf
M
Matthias Bolte 已提交
1240 1241
     * fails it guarantees setting complete to NULL
     */
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return complete;
}



static int
esxNodeGetInfo(virConnectPtr conn, virNodeInfoPtr nodeinfo)
{
M
Matthias Bolte 已提交
1253
    int result = -1;
M
Matthias Bolte 已提交
1254
    esxPrivate *priv = conn->privateData;
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
    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;

1266
    memset(nodeinfo, 0, sizeof(*nodeinfo));
1267

1268
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1269
        return -1;
1270

1271
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1272 1273 1274 1275 1276 1277 1278
                                           "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 ||
1279 1280
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1281
        goto cleanup;
1282 1283
    }

1284
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
1285 1286
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuInfo.hz")) {
1287
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1288
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1289
                goto cleanup;
1290 1291 1292 1293 1294
            }

            cpuInfo_hz = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuCores")) {
1295
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1296
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1297
                goto cleanup;
1298 1299 1300 1301 1302
            }

            cpuInfo_numCpuCores = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuPackages")) {
1303
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1304
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1305
                goto cleanup;
1306 1307 1308 1309 1310
            }

            cpuInfo_numCpuPackages = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuThreads")) {
1311
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1312
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1313
                goto cleanup;
1314 1315 1316 1317
            }

            cpuInfo_numCpuThreads = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name, "hardware.memorySize")) {
1318
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1319
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1320
                goto cleanup;
1321 1322 1323 1324 1325
            }

            memorySize = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.numaInfo.numNodes")) {
1326
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1327
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1328
                goto cleanup;
1329 1330 1331 1332 1333
            }

            numaInfo_numNodes = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "summary.hardware.cpuModel")) {
1334
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1335
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1336
                goto cleanup;
1337 1338 1339 1340 1341 1342
            }

            ptr = dynamicProperty->val->string;

            /* Strip the string to fit more relevant information in 32 chars */
            while (*ptr != '\0') {
M
Matthias Bolte 已提交
1343 1344
                if (STRPREFIX(ptr, "  ")) {
                    memmove(ptr, ptr + 1, strlen(ptr + 1) + 1);
1345
                    continue;
1346
                } else if (STRPREFIX(ptr, "(R)") || STRPREFIX(ptr, "(C)")) {
M
Matthias Bolte 已提交
1347
                    memmove(ptr, ptr + 3, strlen(ptr + 3) + 1);
1348
                    continue;
1349 1350 1351
                } else if (STRPREFIX(ptr, "(TM)")) {
                    memmove(ptr, ptr + 4, strlen(ptr + 4) + 1);
                    continue;
1352 1353 1354 1355 1356
                }

                ++ptr;
            }

1357 1358 1359
            if (!virStrncpy(nodeinfo->model, dynamicProperty->val->string,
                            sizeof(nodeinfo->model) - 1,
                            sizeof(nodeinfo->model))) {
1360 1361 1362
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("CPU Model %s too long for destination"),
                               dynamicProperty->val->string);
M
Matthias Bolte 已提交
1363
                goto cleanup;
C
Chris Lalancette 已提交
1364
            }
1365 1366 1367 1368 1369 1370 1371
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    nodeinfo->memory = memorySize / 1024; /* Scale from bytes to kilobytes */
    nodeinfo->cpus = cpuInfo_numCpuCores;
1372
    nodeinfo->mhz = cpuInfo_hz / (1000 * 1000); /* Scale from hz to mhz */
1373 1374 1375 1376 1377 1378 1379 1380 1381
    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 已提交
1382 1383
    result = 0;

1384
 cleanup:
1385 1386 1387 1388 1389 1390 1391 1392
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



1393
static char *
1394
esxConnectGetCapabilities(virConnectPtr conn)
1395
{
M
Matthias Bolte 已提交
1396
    esxPrivate *priv = conn->privateData;
1397

1398
    return virCapabilitiesFormatXML(priv->caps);
1399 1400 1401 1402
}



1403
static int
1404
esxConnectListDomains(virConnectPtr conn, int *ids, int maxids)
1405
{
M
Matthias Bolte 已提交
1406
    bool success = false;
M
Matthias Bolte 已提交
1407
    esxPrivate *priv = conn->privateData;
1408 1409 1410 1411 1412 1413
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;

1414
    if (maxids == 0)
1415 1416
        return 0;

1417
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1418
        return -1;
1419

1420
    if (esxVI_String_AppendValueToList(&propertyNameList,
1421
                                       "runtime.powerState") < 0 ||
1422 1423
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1424
        goto cleanup;
1425 1426
    }

1427
    for (virtualMachine = virtualMachineList; virtualMachine;
1428
         virtualMachine = virtualMachine->_next) {
1429
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1430
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1431
            goto cleanup;
1432 1433
        }

1434
        if (powerState != esxVI_VirtualMachinePowerState_PoweredOn)
1435 1436 1437 1438 1439
            continue;

        if (esxUtil_ParseVirtualMachineIDString(virtualMachine->obj->value,
                                                &ids[count]) < 0 ||
            ids[count] <= 0) {
1440 1441 1442
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to parse positive integer from '%s'"),
                           virtualMachine->obj->value);
M
Matthias Bolte 已提交
1443
            goto cleanup;
1444 1445 1446 1447
        }

        count++;

1448
        if (count >= maxids)
1449 1450 1451
            break;
    }

M
Matthias Bolte 已提交
1452 1453
    success = true;

1454
 cleanup:
1455 1456 1457
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
1458
    return success ? count : -1;
1459 1460 1461 1462 1463
}



static int
1464
esxConnectNumOfDomains(virConnectPtr conn)
1465
{
M
Matthias Bolte 已提交
1466
    esxPrivate *priv = conn->privateData;
1467

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

1471
    return esxVI_LookupNumberOfDomainsByPowerState
1472
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, false);
1473 1474 1475 1476 1477 1478 1479
}



static virDomainPtr
esxDomainLookupByID(virConnectPtr conn, int id)
{
M
Matthias Bolte 已提交
1480
    esxPrivate *priv = conn->privateData;
1481 1482 1483 1484
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
M
Matthias Bolte 已提交
1485 1486 1487
    int id_candidate = -1;
    char *name_candidate = NULL;
    unsigned char uuid_candidate[VIR_UUID_BUFLEN];
1488 1489
    virDomainPtr domain = NULL;

1490
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1491
        return NULL;
1492

1493
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1494
                                           "configStatus\0"
1495 1496
                                           "name\0"
                                           "runtime.powerState\0"
1497
                                           "config.uuid\0") < 0 ||
1498 1499
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1500
        goto cleanup;
1501 1502
    }

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

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

M
Matthias Bolte 已提交
1514
        VIR_FREE(name_candidate);
1515

1516
        if (esxVI_GetVirtualMachineIdentity(virtualMachine,
M
Matthias Bolte 已提交
1517 1518
                                            &id_candidate, &name_candidate,
                                            uuid_candidate) < 0) {
M
Matthias Bolte 已提交
1519
            goto cleanup;
1520 1521
        }

1522
        if (id != id_candidate)
1523 1524
            continue;

M
Matthias Bolte 已提交
1525
        domain = virGetDomain(conn, name_candidate, uuid_candidate);
1526

1527
        if (!domain)
M
Matthias Bolte 已提交
1528
            goto cleanup;
1529 1530 1531 1532 1533 1534

        domain->id = id;

        break;
    }

1535
    if (!domain)
1536
        virReportError(VIR_ERR_NO_DOMAIN, _("No domain with ID %d"), id);
1537

1538
 cleanup:
1539 1540
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
M
Matthias Bolte 已提交
1541
    VIR_FREE(name_candidate);
1542 1543 1544 1545 1546 1547 1548 1549 1550

    return domain;
}



static virDomainPtr
esxDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
M
Matthias Bolte 已提交
1551
    esxPrivate *priv = conn->privateData;
1552 1553 1554
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1555 1556
    int id = -1;
    char *name = NULL;
1557 1558
    virDomainPtr domain = NULL;

1559
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1560
        return NULL;
1561

1562
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1563
                                           "name\0"
1564
                                           "runtime.powerState\0") < 0 ||
1565
        esxVI_LookupVirtualMachineByUuid(priv->primary, uuid, propertyNameList,
1566
                                         &virtualMachine,
M
Matthias Bolte 已提交
1567
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1568 1569
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, &name, NULL) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1570
        goto cleanup;
1571 1572
    }

1573
    domain = virGetDomain(conn, name, uuid);
1574

1575
    if (!domain)
M
Matthias Bolte 已提交
1576
        goto cleanup;
1577

1578 1579 1580 1581 1582
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1583 1584
    }

1585
 cleanup:
1586
    esxVI_String_Free(&propertyNameList);
1587 1588
    esxVI_ObjectContent_Free(&virtualMachine);
    VIR_FREE(name);
1589 1590 1591 1592 1593 1594 1595 1596 1597

    return domain;
}



static virDomainPtr
esxDomainLookupByName(virConnectPtr conn, const char *name)
{
M
Matthias Bolte 已提交
1598
    esxPrivate *priv = conn->privateData;
1599 1600 1601
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1602 1603
    int id = -1;
    unsigned char uuid[VIR_UUID_BUFLEN];
1604 1605
    virDomainPtr domain = NULL;

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

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

1619
    if (!virtualMachine) {
1620
        virReportError(VIR_ERR_NO_DOMAIN, _("No domain with name '%s'"), name);
M
Matthias Bolte 已提交
1621
        goto cleanup;
1622
    }
1623

M
Matthias Bolte 已提交
1624 1625 1626
    if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, uuid) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
1627
    }
1628

1629
    domain = virGetDomain(conn, name, uuid);
1630

1631
    if (!domain)
M
Matthias Bolte 已提交
1632
        goto cleanup;
1633

1634 1635 1636 1637 1638
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1639 1640
    }

1641
 cleanup:
1642
    esxVI_String_Free(&propertyNameList);
1643
    esxVI_ObjectContent_Free(&virtualMachine);
1644 1645 1646 1647 1648 1649 1650 1651 1652

    return domain;
}



static int
esxDomainSuspend(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1653
    int result = -1;
M
Matthias Bolte 已提交
1654
    esxPrivate *priv = domain->conn->privateData;
1655 1656 1657 1658 1659
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1660
    char *taskInfoErrorMessage = NULL;
1661

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

1665
    if (esxVI_String_AppendValueToList(&propertyNameList,
1666
                                       "runtime.powerState") < 0 ||
1667
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1668
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1669
           priv->parsedUri->autoAnswer) < 0 ||
1670
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1671
        goto cleanup;
1672 1673 1674
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1675 1676
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1677
        goto cleanup;
1678 1679
    }

1680 1681
    if (esxVI_SuspendVM_Task(priv->primary, virtualMachine->obj, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1682
                                    esxVI_Occurrence_RequiredItem,
1683
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1684
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1685
        goto cleanup;
1686 1687 1688
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1689 1690
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not suspend domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
1691
        goto cleanup;
1692 1693
    }

M
Matthias Bolte 已提交
1694 1695
    result = 0;

1696
 cleanup:
1697 1698 1699
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1700
    VIR_FREE(taskInfoErrorMessage);
1701 1702 1703 1704 1705 1706 1707 1708 1709

    return result;
}



static int
esxDomainResume(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1710
    int result = -1;
M
Matthias Bolte 已提交
1711
    esxPrivate *priv = domain->conn->privateData;
1712 1713 1714 1715 1716
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1717
    char *taskInfoErrorMessage = NULL;
1718

1719
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1720
        return -1;
1721

1722
    if (esxVI_String_AppendValueToList(&propertyNameList,
1723
                                       "runtime.powerState") < 0 ||
1724
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1725
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1726
           priv->parsedUri->autoAnswer) < 0 ||
1727
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1728
        goto cleanup;
1729 1730 1731
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended) {
1732
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not suspended"));
M
Matthias Bolte 已提交
1733
        goto cleanup;
1734 1735
    }

1736
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
1737
                             &task) < 0 ||
1738
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1739
                                    esxVI_Occurrence_RequiredItem,
1740
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1741
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1742
        goto cleanup;
1743 1744 1745
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1746 1747
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not resume domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
1748
        goto cleanup;
1749 1750
    }

M
Matthias Bolte 已提交
1751 1752
    result = 0;

1753
 cleanup:
1754 1755 1756
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1757
    VIR_FREE(taskInfoErrorMessage);
1758 1759 1760 1761 1762 1763 1764

    return result;
}



static int
1765
esxDomainShutdownFlags(virDomainPtr domain, unsigned int flags)
1766
{
M
Matthias Bolte 已提交
1767
    int result = -1;
M
Matthias Bolte 已提交
1768
    esxPrivate *priv = domain->conn->privateData;
1769 1770 1771 1772
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1773 1774
    virCheckFlags(0, -1);

1775
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1776
        return -1;
1777

1778
    if (esxVI_String_AppendValueToList(&propertyNameList,
1779
                                       "runtime.powerState") < 0 ||
1780
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1781
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1782
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1783
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1784
        goto cleanup;
1785 1786 1787
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1788 1789
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1790
        goto cleanup;
1791 1792
    }

1793
    if (esxVI_ShutdownGuest(priv->primary, virtualMachine->obj) < 0)
M
Matthias Bolte 已提交
1794
        goto cleanup;
1795

M
Matthias Bolte 已提交
1796 1797
    result = 0;

1798
 cleanup:
1799 1800 1801 1802 1803 1804 1805
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}


1806 1807 1808 1809 1810 1811
static int
esxDomainShutdown(virDomainPtr domain)
{
    return esxDomainShutdownFlags(domain, 0);
}

1812 1813

static int
E
Eric Blake 已提交
1814
esxDomainReboot(virDomainPtr domain, unsigned int flags)
1815
{
M
Matthias Bolte 已提交
1816
    int result = -1;
M
Matthias Bolte 已提交
1817
    esxPrivate *priv = domain->conn->privateData;
1818 1819 1820 1821
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

E
Eric Blake 已提交
1822 1823
    virCheckFlags(0, -1);

1824
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1825
        return -1;
1826

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

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

1842
    if (esxVI_RebootGuest(priv->primary, virtualMachine->obj) < 0)
M
Matthias Bolte 已提交
1843
        goto cleanup;
1844

M
Matthias Bolte 已提交
1845 1846
    result = 0;

1847
 cleanup:
1848 1849 1850 1851 1852 1853 1854 1855 1856
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
1857 1858
esxDomainDestroyFlags(virDomainPtr domain,
                      unsigned int flags)
1859
{
M
Matthias Bolte 已提交
1860
    int result = -1;
M
Matthias Bolte 已提交
1861
    esxPrivate *priv = domain->conn->privateData;
1862
    esxVI_Context *ctx = NULL;
1863 1864 1865 1866 1867
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1868
    char *taskInfoErrorMessage = NULL;
1869

1870 1871
    virCheckFlags(0, -1);

1872
    if (priv->vCenter) {
1873 1874 1875 1876 1877
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

1878
    if (esxVI_EnsureSession(ctx) < 0)
M
Matthias Bolte 已提交
1879
        return -1;
1880

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

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1891 1892
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1893
        goto cleanup;
1894 1895
    }

1896
    if (esxVI_PowerOffVM_Task(ctx, virtualMachine->obj, &task) < 0 ||
1897 1898
        esxVI_WaitForTaskCompletion(ctx, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
1899
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1900
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1901
        goto cleanup;
1902 1903 1904
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1905 1906
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not destroy domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
1907
        goto cleanup;
1908 1909
    }

1910
    domain->id = -1;
M
Matthias Bolte 已提交
1911 1912
    result = 0;

1913
 cleanup:
1914 1915 1916
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1917
    VIR_FREE(taskInfoErrorMessage);
1918 1919 1920 1921 1922

    return result;
}


1923 1924 1925 1926 1927 1928
static int
esxDomainDestroy(virDomainPtr dom)
{
    return esxDomainDestroyFlags(dom, 0);
}

1929 1930

static char *
1931
esxDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED)
1932
{
1933
    char *osType;
1934

1935
    ignore_value(VIR_STRDUP(osType, "hvm"));
1936
    return osType;
1937 1938 1939 1940
}



1941
static unsigned long long
1942 1943
esxDomainGetMaxMemory(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1944
    esxPrivate *priv = domain->conn->privateData;
1945 1946 1947 1948 1949
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    unsigned long memoryMB = 0;

1950
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1951
        return 0;
1952

1953
    if (esxVI_String_AppendValueToList(&propertyNameList,
1954
                                       "config.hardware.memoryMB") < 0 ||
1955
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1956
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1957
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
1958
        goto cleanup;
1959 1960
    }

1961
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
1962 1963
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
1964
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1965
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1966
                goto cleanup;
1967 1968 1969
            }

            if (dynamicProperty->val->int32 < 0) {
1970 1971 1972
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Got invalid memory size %d"),
                               dynamicProperty->val->int32);
1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
            } else {
                memoryMB = dynamicProperty->val->int32;
            }

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

1983
 cleanup:
1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994
    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 已提交
1995
    int result = -1;
M
Matthias Bolte 已提交
1996
    esxPrivate *priv = domain->conn->privateData;
1997
    esxVI_String *propertyNameList = NULL;
1998
    esxVI_ObjectContent *virtualMachine = NULL;
1999
    esxVI_VirtualMachinePowerState powerState;
2000 2001 2002
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2003
    char *taskInfoErrorMessage = NULL;
2004

2005
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
2006
        return -1;
2007

2008 2009 2010 2011
    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "runtime.powerState") < 0 ||
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
2012
           priv->parsedUri->autoAnswer) < 0 ||
2013 2014 2015 2016 2017
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2018 2019
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered off"));
2020 2021 2022 2023
        goto cleanup;
    }

    if (esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
2024
        esxVI_Long_Alloc(&spec->memoryMB) < 0) {
M
Matthias Bolte 已提交
2025
        goto cleanup;
2026 2027
    }

2028
    /* max-memory must be a multiple of 4096 kilobyte */
2029
    spec->memoryMB->value =
2030
      VIR_DIV_UP(memory, 4096) * 4; /* Scale from kilobytes to megabytes */
2031

2032
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2033
                              &task) < 0 ||
2034
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2035
                                    esxVI_Occurrence_RequiredItem,
2036
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2037
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2038
        goto cleanup;
2039 2040 2041
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2042 2043 2044
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set max-memory to %lu kilobytes: %s"), memory,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2045
        goto cleanup;
2046 2047
    }

M
Matthias Bolte 已提交
2048 2049
    result = 0;

2050
 cleanup:
2051
    esxVI_String_Free(&propertyNameList);
2052 2053 2054
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2055
    VIR_FREE(taskInfoErrorMessage);
2056 2057 2058 2059 2060 2061 2062 2063 2064

    return result;
}



static int
esxDomainSetMemory(virDomainPtr domain, unsigned long memory)
{
M
Matthias Bolte 已提交
2065
    int result = -1;
M
Matthias Bolte 已提交
2066
    esxPrivate *priv = domain->conn->privateData;
2067 2068 2069 2070
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2071
    char *taskInfoErrorMessage = NULL;
2072

2073
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
2074
        return -1;
2075

2076
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2077
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2078
           priv->parsedUri->autoAnswer) < 0 ||
2079 2080 2081
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0 ||
        esxVI_Long_Alloc(&spec->memoryAllocation->limit) < 0) {
M
Matthias Bolte 已提交
2082
        goto cleanup;
2083 2084 2085
    }

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

2088
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2089
                              &task) < 0 ||
2090
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2091
                                    esxVI_Occurrence_RequiredItem,
2092
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2093
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2094
        goto cleanup;
2095 2096 2097
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2098 2099 2100
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set memory to %lu kilobytes: %s"), memory,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2101
        goto cleanup;
2102 2103
    }

M
Matthias Bolte 已提交
2104 2105
    result = 0;

2106
 cleanup:
2107 2108 2109
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2110
    VIR_FREE(taskInfoErrorMessage);
2111 2112 2113 2114 2115 2116

    return result;
}



2117 2118 2119 2120 2121 2122 2123 2124 2125
/*
 * 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

2126 2127 2128
static int
esxDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info)
{
M
Matthias Bolte 已提交
2129
    int result = -1;
M
Matthias Bolte 已提交
2130
    esxPrivate *priv = domain->conn->privateData;
2131 2132 2133 2134 2135
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int64_t memory_limit = -1;
2136
#if ESX_QUERY_FOR_USED_CPU_TIME
2137 2138 2139 2140 2141 2142 2143
    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;
2144 2145
    esxVI_PerfEntityMetricBase *perfEntityMetricBase = NULL;
    esxVI_PerfEntityMetricBase *perfEntityMetricBaseList = NULL;
2146 2147 2148
    esxVI_PerfEntityMetric *perfEntityMetric = NULL;
    esxVI_PerfMetricIntSeries *perfMetricIntSeries = NULL;
    esxVI_Long *value = NULL;
2149
#endif
2150

2151
    memset(info, 0, sizeof(*info));
M
Matthias Bolte 已提交
2152

2153
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
2154
        return -1;
2155

2156
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2157 2158 2159 2160
                                           "runtime.powerState\0"
                                           "config.hardware.memoryMB\0"
                                           "config.hardware.numCPU\0"
                                           "config.memoryAllocation.limit\0") < 0 ||
2161
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2162
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2163
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2164
        goto cleanup;
2165 2166 2167 2168
    }

    info->state = VIR_DOMAIN_NOSTATE;

2169
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
2170 2171 2172
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.powerState")) {
            if (esxVI_VirtualMachinePowerState_CastFromAnyType
2173
                  (dynamicProperty->val, &powerState) < 0) {
M
Matthias Bolte 已提交
2174
                goto cleanup;
2175 2176
            }

2177 2178
            info->state = esxVI_VirtualMachinePowerState_ConvertToLibvirt
                            (powerState);
2179
        } else if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2180
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2181
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2182
                goto cleanup;
2183 2184 2185 2186
            }

            info->maxMem = dynamicProperty->val->int32 * 1024; /* Scale from megabyte to kilobyte */
        } else if (STREQ(dynamicProperty->name, "config.hardware.numCPU")) {
2187
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2188
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2189
                goto cleanup;
2190 2191 2192 2193 2194
            }

            info->nrVirtCpu = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "config.memoryAllocation.limit")) {
2195
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2196
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
2197
                goto cleanup;
2198 2199 2200 2201
            }

            memory_limit = dynamicProperty->val->int64;

2202
            if (memory_limit > 0)
2203 2204 2205 2206 2207 2208 2209 2210 2211
                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;

2212
#if ESX_QUERY_FOR_USED_CPU_TIME
2213
    /* Verify the cached 'used CPU time' performance counter ID */
2214
    /* FIXME: Currently no host for a vpx:// connection */
2215
    if (priv->host) {
2216
        if (info->state == VIR_DOMAIN_RUNNING && priv->usedCpuTimeCounterId >= 0) {
2217
            if (esxVI_Int_Alloc(&counterId) < 0)
2218
                goto cleanup;
2219

2220
            counterId->value = priv->usedCpuTimeCounterId;
2221

2222
            if (esxVI_Int_AppendToList(&counterIdList, counterId) < 0)
2223
                goto cleanup;
2224

2225 2226 2227 2228
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfo) < 0) {
                goto cleanup;
            }
2229

2230 2231 2232 2233 2234
            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);
2235

2236 2237 2238 2239 2240
                priv->usedCpuTimeCounterId = -1;
            }

            esxVI_Int_Free(&counterIdList);
            esxVI_PerfCounterInfo_Free(&perfCounterInfo);
2241 2242
        }

2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
        /*
         * 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;
            }
2253

2254
            for (perfMetricId = perfMetricIdList; perfMetricId;
2255 2256 2257
                 perfMetricId = perfMetricId->_next) {
                VIR_DEBUG("perfMetricId counterId %d, instance '%s'",
                          perfMetricId->counterId->value, perfMetricId->instance);
2258

2259
                counterId = NULL;
2260

2261 2262 2263 2264 2265
                if (esxVI_Int_DeepCopy(&counterId, perfMetricId->counterId) < 0 ||
                    esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                    goto cleanup;
                }
            }
2266

2267 2268
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfoList) < 0) {
M
Matthias Bolte 已提交
2269
                goto cleanup;
2270 2271
            }

2272
            for (perfCounterInfo = perfCounterInfoList; perfCounterInfo;
2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288
                 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;
                }
2289 2290
            }

2291
            if (priv->usedCpuTimeCounterId < 0)
2292
                VIR_WARN("Could not find 'used CPU time' performance counter");
2293 2294
        }

2295 2296 2297 2298 2299 2300
        /*
         * 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);
2301

2302 2303 2304 2305 2306 2307
            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;
            }
2308

2309 2310 2311 2312 2313 2314 2315 2316 2317 2318
            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;
            }
2319

2320
            for (perfEntityMetricBase = perfEntityMetricBaseList;
2321
                 perfEntityMetricBase;
2322
                 perfEntityMetricBase = perfEntityMetricBase->_next) {
2323
                VIR_DEBUG("perfEntityMetric ...");
2324

2325 2326
                perfEntityMetric =
                  esxVI_PerfEntityMetric_DynamicCast(perfEntityMetricBase);
2327

2328
                if (!perfEntityMetric) {
2329 2330 2331
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("QueryPerf returned object with unexpected type '%s'"),
                                   esxVI_Type_ToString(perfEntityMetricBase->_type));
2332
                    goto cleanup;
2333
                }
2334

2335 2336
                perfMetricIntSeries =
                  esxVI_PerfMetricIntSeries_DynamicCast(perfEntityMetric->value);
2337

2338
                if (!perfMetricIntSeries) {
2339 2340 2341
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("QueryPerf returned object with unexpected type '%s'"),
                                   esxVI_Type_ToString(perfEntityMetric->value->_type));
2342
                    goto cleanup;
2343
                }
2344

2345
                for (; perfMetricIntSeries;
2346
                     perfMetricIntSeries = perfMetricIntSeries->_next) {
2347
                    VIR_DEBUG("perfMetricIntSeries ...");
2348

2349
                    for (value = perfMetricIntSeries->value;
2350
                         value;
2351 2352 2353
                         value = value->_next) {
                        VIR_DEBUG("value %lld", (long long int)value->value);
                    }
2354 2355 2356
                }
            }

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

2359
            /*
E
Eric Blake 已提交
2360
             * FIXME: Cannot map between relative used-cpu-time and absolute
2361 2362 2363
             *        info->cpuTime
             */
        }
2364
    }
2365
#endif
2366

M
Matthias Bolte 已提交
2367 2368
    result = 0;

2369
 cleanup:
2370
#if ESX_QUERY_FOR_USED_CPU_TIME
2371 2372 2373 2374
    /*
     * Remove values owned by data structures to prevent them from being freed
     * by the call to esxVI_PerfQuerySpec_Free().
     */
2375
    if (querySpec) {
2376 2377 2378
        querySpec->entity = NULL;
        querySpec->format = NULL;

2379
        if (querySpec->metricId)
2380 2381
            querySpec->metricId->instance = NULL;
    }
2382
#endif
2383

2384 2385
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2386
#if ESX_QUERY_FOR_USED_CPU_TIME
2387 2388 2389 2390
    esxVI_PerfMetricId_Free(&perfMetricIdList);
    esxVI_Int_Free(&counterIdList);
    esxVI_PerfCounterInfo_Free(&perfCounterInfoList);
    esxVI_PerfQuerySpec_Free(&querySpec);
2391
    esxVI_PerfEntityMetricBase_Free(&perfEntityMetricBaseList);
2392
#endif
2393 2394 2395 2396 2397 2398

    return result;
}



2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412
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);

2413
    if (esxVI_EnsureSession(priv->primary) < 0)
2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431
        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;

2432
 cleanup:
2433 2434 2435 2436 2437 2438 2439 2440
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
}



2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518
static char *
esxDomainScreenshot(virDomainPtr domain, virStreamPtr stream,
                    unsigned int screen, unsigned int flags)
{
    char *mimeType = NULL;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_Boolean supportsScreenshot = esxVI_Boolean_Undefined;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    char *url = NULL;

    virCheckFlags(0, NULL);

    if (screen != 0) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Screen cannot be selected"));
        return NULL;
    }

    supportsScreenshot = esxSupportsScreenshot(priv);

    if (supportsScreenshot == esxVI_Boolean_Undefined)
        return NULL;

    if (supportsScreenshot != esxVI_Boolean_True) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                       _("Screenshot feature is unsupported"));
        return NULL;
    }

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

    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;

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
        goto cleanup;
    }

    /* Build URL */
    virBufferAsprintf(&buffer, "%s://%s:%d/screen?id=", priv->parsedUri->transport,
                      domain->conn->uri->server, domain->conn->uri->port);
    virBufferURIEncodeString(&buffer, virtualMachine->obj->value);

    if (virBufferCheckError(&buffer))
        goto cleanup;

    url = virBufferContentAndReset(&buffer);

    if (VIR_STRDUP(mimeType, "image/png") < 0)
        goto cleanup;

    if (esxStreamOpenDownload(stream, priv, url, 0, 0) < 0) {
        VIR_FREE(mimeType);
        goto cleanup;
    }

 cleanup:
    virBufferFreeAndReset(&buffer);

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

    return mimeType;
}



2519
static int
2520 2521
esxDomainSetVcpusFlags(virDomainPtr domain, unsigned int nvcpus,
                       unsigned int flags)
2522
{
M
Matthias Bolte 已提交
2523
    int result = -1;
M
Matthias Bolte 已提交
2524
    esxPrivate *priv = domain->conn->privateData;
M
Matthias Bolte 已提交
2525
    int maxVcpus;
2526 2527 2528 2529
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2530
    char *taskInfoErrorMessage = NULL;
2531

2532
    if (flags != VIR_DOMAIN_AFFECT_LIVE) {
2533
        virReportError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
2534 2535 2536
        return -1;
    }

2537
    if (nvcpus < 1) {
2538 2539
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Requested number of virtual CPUs must at least be 1"));
M
Matthias Bolte 已提交
2540
        return -1;
2541 2542
    }

2543
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
2544
        return -1;
2545

M
Matthias Bolte 已提交
2546
    maxVcpus = esxDomainGetMaxVcpus(domain);
2547

2548
    if (maxVcpus < 0)
M
Matthias Bolte 已提交
2549
        return -1;
2550

M
Matthias Bolte 已提交
2551
    if (nvcpus > maxVcpus) {
2552 2553 2554 2555
        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 已提交
2556
        return -1;
2557 2558
    }

2559
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2560
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2561
           priv->parsedUri->autoAnswer) < 0 ||
2562 2563
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Int_Alloc(&spec->numCPUs) < 0) {
M
Matthias Bolte 已提交
2564
        goto cleanup;
2565 2566 2567 2568
    }

    spec->numCPUs->value = nvcpus;

2569
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2570
                              &task) < 0 ||
2571
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2572
                                    esxVI_Occurrence_RequiredItem,
2573
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2574
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2575
        goto cleanup;
2576 2577 2578
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2579 2580 2581
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set number of virtual CPUs to %d: %s"), nvcpus,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2582
        goto cleanup;
2583 2584
    }

M
Matthias Bolte 已提交
2585 2586
    result = 0;

2587
 cleanup:
2588 2589 2590
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2591
    VIR_FREE(taskInfoErrorMessage);
2592 2593 2594 2595 2596

    return result;
}


M
Matthias Bolte 已提交
2597

2598 2599 2600
static int
esxDomainSetVcpus(virDomainPtr domain, unsigned int nvcpus)
{
2601
    return esxDomainSetVcpusFlags(domain, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
2602 2603
}

2604

M
Matthias Bolte 已提交
2605

2606
static int
2607
esxDomainGetVcpusFlags(virDomainPtr domain, unsigned int flags)
2608
{
M
Matthias Bolte 已提交
2609
    esxPrivate *priv = domain->conn->privateData;
2610 2611 2612 2613
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

2614
    if (flags != (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_VCPU_MAXIMUM)) {
2615
        virReportError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
2616 2617 2618
        return -1;
    }

2619
    if (priv->maxVcpus > 0)
M
Matthias Bolte 已提交
2620
        return priv->maxVcpus;
2621

M
Matthias Bolte 已提交
2622 2623
    priv->maxVcpus = -1;

2624
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
2625
        return -1;
2626

2627
    if (esxVI_String_AppendValueToList(&propertyNameList,
2628
                                       "capability.maxSupportedVcpus") < 0 ||
2629 2630
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
2631
        goto cleanup;
2632 2633
    }

2634
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
2635 2636
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "capability.maxSupportedVcpus")) {
2637
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2638
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2639
                goto cleanup;
2640 2641
            }

M
Matthias Bolte 已提交
2642
            priv->maxVcpus = dynamicProperty->val->int32;
2643 2644 2645 2646 2647 2648
            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

2649
 cleanup:
2650 2651 2652
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
2653
    return priv->maxVcpus;
2654 2655
}

M
Matthias Bolte 已提交
2656 2657


2658 2659 2660
static int
esxDomainGetMaxVcpus(virDomainPtr domain)
{
2661
    return esxDomainGetVcpusFlags(domain, (VIR_DOMAIN_AFFECT_LIVE |
2662 2663
                                           VIR_DOMAIN_VCPU_MAXIMUM));
}
2664

M
Matthias Bolte 已提交
2665 2666


2667
static char *
2668
esxDomainGetXMLDesc(virDomainPtr domain, unsigned int flags)
2669
{
M
Matthias Bolte 已提交
2670
    esxPrivate *priv = domain->conn->privateData;
2671 2672
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
2673 2674
    esxVI_VirtualMachinePowerState powerState;
    int id;
2675
    char *vmPathName = NULL;
2676
    char *datastoreName = NULL;
M
Matthias Bolte 已提交
2677
    char *directoryName = NULL;
2678
    char *directoryAndFileName = NULL;
2679
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
2680 2681
    char *url = NULL;
    char *vmx = NULL;
2682
    virVMXContext ctx;
2683
    esxVMX_Data data;
2684 2685 2686
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2687 2688
    /* Flags checked by virDomainDefFormat */

2689
    memset(&data, 0, sizeof(data));
2690

2691
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
2692
        return NULL;
2693

2694 2695 2696
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "config.files.vmPathName\0"
                                           "runtime.powerState\0") < 0 ||
2697
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2698
                                         propertyNameList, &virtualMachine,
2699
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2700 2701
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0 ||
2702 2703
        esxVI_GetStringValue(virtualMachine, "config.files.vmPathName",
                             &vmPathName, esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2704
        goto cleanup;
2705 2706
    }

2707
    if (esxUtil_ParseDatastorePath(vmPathName, &datastoreName, &directoryName,
2708
                                   &directoryAndFileName) < 0) {
M
Matthias Bolte 已提交
2709
        goto cleanup;
2710 2711
    }

2712
    virBufferAsprintf(&buffer, "%s://%s:%d/folder/", priv->parsedUri->transport,
2713
                      domain->conn->uri->server, domain->conn->uri->port);
2714
    virBufferURIEncodeString(&buffer, directoryAndFileName);
2715
    virBufferAddLit(&buffer, "?dcPath=");
2716
    virBufferURIEncodeString(&buffer, priv->primary->datacenterPath);
2717 2718 2719
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

2720
    if (virBufferCheckError(&buffer) < 0)
M
Matthias Bolte 已提交
2721
        goto cleanup;
2722

2723 2724
    url = virBufferContentAndReset(&buffer);

2725
    if (esxVI_CURL_Download(priv->primary->curl, url, &vmx, 0, NULL) < 0)
M
Matthias Bolte 已提交
2726
        goto cleanup;
2727

2728
    data.ctx = priv->primary;
2729

2730
    if (!directoryName) {
2731
        if (virAsprintf(&data.datastorePathWithoutFileName, "[%s]",
2732
                        datastoreName) < 0)
2733 2734 2735
            goto cleanup;
    } else {
        if (virAsprintf(&data.datastorePathWithoutFileName, "[%s] %s",
2736
                        datastoreName, directoryName) < 0)
2737 2738
            goto cleanup;
    }
2739 2740 2741 2742 2743 2744

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

2745
    def = virVMXParseConfig(&ctx, priv->xmlopt, vmx);
2746

2747
    if (def) {
2748
        if (powerState != esxVI_VirtualMachinePowerState_PoweredOff)
2749 2750
            def->id = id;

2751 2752
        xml = virDomainDefFormat(def,
                                 virDomainDefFormatConvertXMLFlags(flags));
2753 2754
    }

2755
 cleanup:
2756
    if (!url)
M
Matthias Bolte 已提交
2757 2758
        virBufferFreeAndReset(&buffer);

2759 2760
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2761
    VIR_FREE(datastoreName);
M
Matthias Bolte 已提交
2762
    VIR_FREE(directoryName);
2763
    VIR_FREE(directoryAndFileName);
2764
    VIR_FREE(url);
2765
    VIR_FREE(data.datastorePathWithoutFileName);
2766
    VIR_FREE(vmx);
2767
    virDomainDefFree(def);
2768 2769 2770 2771 2772 2773 2774

    return xml;
}



static char *
2775 2776 2777
esxConnectDomainXMLFromNative(virConnectPtr conn, const char *nativeFormat,
                              const char *nativeConfig,
                              unsigned int flags)
2778
{
M
Matthias Bolte 已提交
2779
    esxPrivate *priv = conn->privateData;
2780
    virVMXContext ctx;
2781
    esxVMX_Data data;
2782 2783 2784
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2785 2786
    virCheckFlags(0, NULL);

2787
    memset(&data, 0, sizeof(data));
2788

2789
    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2790 2791
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Unsupported config format '%s'"), nativeFormat);
2792
        return NULL;
2793 2794
    }

2795
    data.ctx = priv->primary;
2796
    data.datastorePathWithoutFileName = (char *)"[?] ?";
2797 2798 2799 2800 2801 2802

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

2803
    def = virVMXParseConfig(&ctx, priv->xmlopt, nativeConfig);
2804

2805
    if (def)
2806
        xml = virDomainDefFormat(def, VIR_DOMAIN_DEF_FORMAT_INACTIVE);
2807 2808 2809 2810 2811 2812 2813 2814

    virDomainDefFree(def);

    return xml;
}



M
Matthias Bolte 已提交
2815
static char *
2816 2817 2818
esxConnectDomainXMLToNative(virConnectPtr conn, const char *nativeFormat,
                            const char *domainXml,
                            unsigned int flags)
M
Matthias Bolte 已提交
2819
{
M
Matthias Bolte 已提交
2820
    esxPrivate *priv = conn->privateData;
2821 2822
    int virtualHW_version;
    virVMXContext ctx;
2823
    esxVMX_Data data;
M
Matthias Bolte 已提交
2824 2825 2826
    virDomainDefPtr def = NULL;
    char *vmx = NULL;

E
Eric Blake 已提交
2827 2828
    virCheckFlags(0, NULL);

2829
    memset(&data, 0, sizeof(data));
2830

M
Matthias Bolte 已提交
2831
    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2832 2833
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Unsupported config format '%s'"), nativeFormat);
M
Matthias Bolte 已提交
2834 2835 2836
        return NULL;
    }

2837
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
2838
                          (priv->primary->productLine, priv->primary->productVersion);
2839

2840
    if (virtualHW_version < 0)
2841 2842
        return NULL;

2843
    def = virDomainDefParseString(domainXml, priv->caps, priv->xmlopt,
2844
                                  VIR_DOMAIN_DEF_PARSE_INACTIVE);
M
Matthias Bolte 已提交
2845

2846
    if (!def)
M
Matthias Bolte 已提交
2847 2848
        return NULL;

2849
    data.ctx = priv->primary;
2850
    data.datastorePathWithoutFileName = NULL;
2851 2852 2853 2854 2855 2856

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

2857
    vmx = virVMXFormatConfig(&ctx, priv->xmlopt, def, virtualHW_version);
M
Matthias Bolte 已提交
2858 2859 2860 2861 2862 2863 2864 2865

    virDomainDefFree(def);

    return vmx;
}



2866
static int
2867
esxConnectListDefinedDomains(virConnectPtr conn, char **const names, int maxnames)
2868
{
M
Matthias Bolte 已提交
2869
    bool success = false;
M
Matthias Bolte 已提交
2870
    esxPrivate *priv = conn->privateData;
2871 2872 2873 2874 2875
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;
2876
    size_t i;
2877

2878
    if (maxnames == 0)
2879 2880
        return 0;

2881
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
2882
        return -1;
2883

2884
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2885 2886
                                           "name\0"
                                           "runtime.powerState\0") < 0 ||
2887 2888
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2889
        goto cleanup;
2890 2891
    }

2892
    for (virtualMachine = virtualMachineList; virtualMachine;
2893
         virtualMachine = virtualMachine->_next) {
2894
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
2895
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
2896
            goto cleanup;
2897 2898
        }

2899
        if (powerState == esxVI_VirtualMachinePowerState_PoweredOn)
2900 2901
            continue;

2902
        names[count] = NULL;
2903

2904 2905 2906
        if (esxVI_GetVirtualMachineIdentity(virtualMachine, NULL, &names[count],
                                            NULL) < 0) {
            goto cleanup;
2907 2908
        }

2909 2910
        ++count;

2911
        if (count >= maxnames)
2912 2913 2914
            break;
    }

M
Matthias Bolte 已提交
2915
    success = true;
2916

2917
 cleanup:
M
Matthias Bolte 已提交
2918
    if (! success) {
2919
        for (i = 0; i < count; ++i)
M
Matthias Bolte 已提交
2920
            VIR_FREE(names[i]);
2921

M
Matthias Bolte 已提交
2922
        count = -1;
2923 2924
    }

M
Matthias Bolte 已提交
2925 2926
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
2927

M
Matthias Bolte 已提交
2928
    return count;
2929 2930 2931 2932 2933
}



static int
2934
esxConnectNumOfDefinedDomains(virConnectPtr conn)
2935
{
M
Matthias Bolte 已提交
2936
    esxPrivate *priv = conn->privateData;
2937

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

2941
    return esxVI_LookupNumberOfDomainsByPowerState
2942
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, true);
2943 2944 2945 2946 2947
}



static int
2948
esxDomainCreateWithFlags(virDomainPtr domain, unsigned int flags)
2949
{
M
Matthias Bolte 已提交
2950
    int result = -1;
M
Matthias Bolte 已提交
2951
    esxPrivate *priv = domain->conn->privateData;
2952 2953 2954
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
2955
    int id = -1;
2956 2957
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2958
    char *taskInfoErrorMessage = NULL;
2959

2960 2961
    virCheckFlags(0, -1);

2962
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
2963
        return -1;
2964

2965
    if (esxVI_String_AppendValueToList(&propertyNameList,
2966
                                       "runtime.powerState") < 0 ||
2967
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2968
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
2969
           priv->parsedUri->autoAnswer) < 0 ||
2970 2971
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0) {
M
Matthias Bolte 已提交
2972
        goto cleanup;
2973 2974 2975
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2976 2977
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered off"));
M
Matthias Bolte 已提交
2978
        goto cleanup;
2979 2980
    }

2981
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
2982
                             &task) < 0 ||
2983
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2984
                                    esxVI_Occurrence_RequiredItem,
2985
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2986
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2987
        goto cleanup;
2988 2989 2990
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2991 2992
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not start domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2993
        goto cleanup;
2994 2995
    }

2996
    domain->id = id;
M
Matthias Bolte 已提交
2997 2998
    result = 0;

2999
 cleanup:
3000 3001 3002
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
3003
    VIR_FREE(taskInfoErrorMessage);
3004 3005 3006 3007

    return result;
}

3008 3009


3010 3011 3012 3013 3014
static int
esxDomainCreate(virDomainPtr domain)
{
    return esxDomainCreateWithFlags(domain, 0);
}
3015

3016 3017


M
Matthias Bolte 已提交
3018
static virDomainPtr
3019
esxDomainDefineXMLFlags(virConnectPtr conn, const char *xml, unsigned int flags)
M
Matthias Bolte 已提交
3020
{
M
Matthias Bolte 已提交
3021
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
3022 3023
    virDomainDefPtr def = NULL;
    char *vmx = NULL;
3024
    size_t i;
3025
    virDomainDiskDefPtr disk = NULL;
M
Matthias Bolte 已提交
3026
    esxVI_ObjectContent *virtualMachine = NULL;
3027 3028
    int virtualHW_version;
    virVMXContext ctx;
3029
    esxVMX_Data data;
M
Matthias Bolte 已提交
3030 3031
    char *datastoreName = NULL;
    char *directoryName = NULL;
3032
    char *escapedName = NULL;
M
Matthias Bolte 已提交
3033 3034 3035 3036 3037 3038 3039 3040
    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;
3041
    char *taskInfoErrorMessage = NULL;
M
Matthias Bolte 已提交
3042
    virDomainPtr domain = NULL;
3043
    const char *src;
3044
    unsigned int parse_flags = VIR_DOMAIN_DEF_PARSE_INACTIVE;
M
Matthias Bolte 已提交
3045

3046 3047 3048 3049
    virCheckFlags(VIR_DOMAIN_DEFINE_VALIDATE, NULL);

    if (flags & VIR_DOMAIN_DEFINE_VALIDATE)
        parse_flags |= VIR_DOMAIN_DEF_PARSE_VALIDATE;
3050

3051
    memset(&data, 0, sizeof(data));
3052

3053
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
3054
        return NULL;
M
Matthias Bolte 已提交
3055 3056

    /* Parse domain XML */
3057
    def = virDomainDefParseString(xml, priv->caps, priv->xmlopt,
3058
                                  parse_flags);
M
Matthias Bolte 已提交
3059

3060
    if (!def)
M
Matthias Bolte 已提交
3061
        return NULL;
M
Matthias Bolte 已提交
3062 3063

    /* Check if an existing domain should be edited */
3064
    if (esxVI_LookupVirtualMachineByUuid(priv->primary, def->uuid, NULL,
M
Matthias Bolte 已提交
3065
                                         &virtualMachine,
M
Matthias Bolte 已提交
3066
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
3067
        goto cleanup;
M
Matthias Bolte 已提交
3068 3069
    }

3070
    if (!virtualMachine &&
3071 3072 3073 3074 3075 3076
        esxVI_LookupVirtualMachineByName(priv->primary, def->name, NULL,
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
    }

3077
    if (virtualMachine) {
M
Matthias Bolte 已提交
3078
        /* FIXME */
3079 3080 3081
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Domain already exists, editing existing domains is not "
                         "supported yet"));
M
Matthias Bolte 已提交
3082
        goto cleanup;
M
Matthias Bolte 已提交
3083 3084 3085
    }

    /* Build VMX from domain XML */
3086
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
3087
                          (priv->primary->productLine, priv->primary->productVersion);
3088

3089
    if (virtualHW_version < 0)
3090 3091
        goto cleanup;

3092
    data.ctx = priv->primary;
3093
    data.datastorePathWithoutFileName = NULL;
3094 3095 3096 3097 3098 3099

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

3100
    vmx = virVMXFormatConfig(&ctx, priv->xmlopt, def, virtualHW_version);
M
Matthias Bolte 已提交
3101

3102
    if (!vmx)
M
Matthias Bolte 已提交
3103
        goto cleanup;
M
Matthias Bolte 已提交
3104

3105 3106 3107
    /*
     * 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
N
Nehal J Wani 已提交
3108
     * first disk, because it may be CDROM disk and ISO images are normally not
3109 3110 3111
     * 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 已提交
3112
    if (def->ndisks < 1) {
3113 3114 3115
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Domain XML doesn't contain any disks, cannot deduce "
                         "datastore and path for VMX file"));
M
Matthias Bolte 已提交
3116
        goto cleanup;
3117 3118 3119 3120
    }

    for (i = 0; i < def->ndisks; ++i) {
        if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK &&
E
Eric Blake 已提交
3121
            virDomainDiskGetType(def->disks[i]) == VIR_STORAGE_TYPE_FILE) {
3122 3123 3124 3125 3126
            disk = def->disks[i];
            break;
        }
    }

3127
    if (!disk) {
3128 3129 3130
        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 已提交
3131
        goto cleanup;
M
Matthias Bolte 已提交
3132 3133
    }

3134 3135
    src = virDomainDiskGetSource(disk);
    if (!src) {
3136 3137 3138
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("First file-based harddisk has no source, cannot deduce "
                         "datastore and path for VMX file"));
M
Matthias Bolte 已提交
3139
        goto cleanup;
M
Matthias Bolte 已提交
3140 3141
    }

3142
    if (esxUtil_ParseDatastorePath(src, &datastoreName, &directoryName,
3143
                                   NULL) < 0) {
M
Matthias Bolte 已提交
3144
        goto cleanup;
M
Matthias Bolte 已提交
3145 3146
    }

3147
    if (! virFileHasSuffix(src, ".vmdk")) {
3148 3149
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Expecting source '%s' of first file-based harddisk to "
3150
                         "be a VMDK image"), src);
M
Matthias Bolte 已提交
3151
        goto cleanup;
M
Matthias Bolte 已提交
3152 3153
    }

3154
    virBufferAsprintf(&buffer, "%s://%s:%d/folder/", priv->parsedUri->transport,
M
Matthias Bolte 已提交
3155 3156
                      conn->uri->server, conn->uri->port);

3157
    if (directoryName) {
M
Matthias Bolte 已提交
3158 3159 3160 3161
        virBufferURIEncodeString(&buffer, directoryName);
        virBufferAddChar(&buffer, '/');
    }

3162 3163
    escapedName = esxUtil_EscapeDatastoreItem(def->name);

3164
    if (!escapedName)
3165 3166 3167
        goto cleanup;

    virBufferURIEncodeString(&buffer, escapedName);
M
Matthias Bolte 已提交
3168
    virBufferAddLit(&buffer, ".vmx?dcPath=");
3169
    virBufferURIEncodeString(&buffer, priv->primary->datacenterPath);
M
Matthias Bolte 已提交
3170 3171 3172
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

3173
    if (virBufferCheckError(&buffer) < 0)
M
Matthias Bolte 已提交
3174
        goto cleanup;
M
Matthias Bolte 已提交
3175 3176 3177

    url = virBufferContentAndReset(&buffer);

3178 3179 3180 3181 3182 3183
    /* Check, if VMX file already exists */
    /* FIXME */

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

3184
    if (esxVI_CURL_Upload(priv->primary->curl, url, vmx) < 0)
3185 3186 3187
        goto cleanup;

    /* Register the domain */
3188
    if (directoryName) {
M
Matthias Bolte 已提交
3189
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s/%s.vmx", datastoreName,
3190
                        directoryName, escapedName) < 0)
M
Matthias Bolte 已提交
3191
            goto cleanup;
M
Matthias Bolte 已提交
3192 3193
    } else {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s.vmx", datastoreName,
3194
                        escapedName) < 0)
M
Matthias Bolte 已提交
3195
            goto cleanup;
M
Matthias Bolte 已提交
3196 3197
    }

3198
    if (esxVI_RegisterVM_Task(priv->primary, priv->primary->datacenter->vmFolder,
M
Matthias Bolte 已提交
3199
                              datastoreRelatedPath, NULL, esxVI_Boolean_False,
3200 3201 3202 3203
                              priv->primary->computeResource->resourcePool,
                              priv->primary->hostSystem->_reference,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, def->uuid,
3204
                                    esxVI_Occurrence_OptionalItem,
3205
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3206
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3207
        goto cleanup;
M
Matthias Bolte 已提交
3208 3209 3210
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3211 3212
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not define domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3213
        goto cleanup;
M
Matthias Bolte 已提交
3214 3215 3216 3217
    }

    domain = virGetDomain(conn, def->name, def->uuid);

3218
    if (domain)
M
Matthias Bolte 已提交
3219 3220 3221 3222
        domain->id = -1;

    /* FIXME: Add proper rollback in case of an error */

3223
 cleanup:
3224
    if (!url)
M
Matthias Bolte 已提交
3225 3226
        virBufferFreeAndReset(&buffer);

M
Matthias Bolte 已提交
3227 3228 3229 3230
    virDomainDefFree(def);
    VIR_FREE(vmx);
    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
3231
    VIR_FREE(escapedName);
M
Matthias Bolte 已提交
3232 3233 3234 3235 3236 3237 3238
    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);
3239
    VIR_FREE(taskInfoErrorMessage);
M
Matthias Bolte 已提交
3240 3241 3242 3243

    return domain;
}

3244 3245 3246 3247 3248
static virDomainPtr
esxDomainDefineXML(virConnectPtr conn, const char *xml)
{
    return esxDomainDefineXMLFlags(conn, xml, 0);
}
M
Matthias Bolte 已提交
3249

3250
static int
3251 3252
esxDomainUndefineFlags(virDomainPtr domain,
                       unsigned int flags)
3253
{
M
Matthias Bolte 已提交
3254
    int result = -1;
M
Matthias Bolte 已提交
3255
    esxPrivate *priv = domain->conn->privateData;
3256
    esxVI_Context *ctx = NULL;
3257 3258 3259 3260
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

3261 3262 3263 3264
    /* 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);
3265

3266
    if (priv->vCenter) {
3267 3268 3269 3270 3271
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

3272
    if (esxVI_EnsureSession(ctx) < 0)
M
Matthias Bolte 已提交
3273
        return -1;
3274

3275
    if (esxVI_String_AppendValueToList(&propertyNameList,
3276
                                       "runtime.powerState") < 0 ||
3277 3278
        esxVI_LookupVirtualMachineByUuid(ctx, domain->uuid, propertyNameList,
                                         &virtualMachine,
M
Matthias Bolte 已提交
3279
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3280
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
3281
        goto cleanup;
3282 3283 3284 3285
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended &&
        powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
3286 3287
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not suspended or powered off"));
M
Matthias Bolte 已提交
3288
        goto cleanup;
3289 3290
    }

3291
    if (esxVI_UnregisterVM(ctx, virtualMachine->obj) < 0)
M
Matthias Bolte 已提交
3292
        goto cleanup;
3293

M
Matthias Bolte 已提交
3294 3295
    result = 0;

3296
 cleanup:
3297 3298 3299 3300 3301 3302 3303
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}


3304 3305 3306 3307 3308
static int
esxDomainUndefine(virDomainPtr domain)
{
    return esxDomainUndefineFlags(domain, 0);
}
3309

3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322
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;

3323
    if (esxVI_EnsureSession(priv->primary) < 0)
3324 3325 3326
        return -1;

    /* Check general autostart config */
3327
    if (esxVI_LookupAutoStartDefaults(priv->primary, &defaults) < 0)
3328 3329 3330 3331 3332 3333 3334 3335 3336
        goto cleanup;

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

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

3340
    if (!powerInfoList) {
3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351
        /* 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;
    }

3352
    for (powerInfo = powerInfoList; powerInfo;
3353 3354
         powerInfo = powerInfo->_next) {
        if (STREQ(powerInfo->key->value, virtualMachine->obj->value)) {
3355
            if (STRCASEEQ(powerInfo->startAction, "powerOn"))
3356 3357 3358 3359 3360 3361 3362 3363
                *autostart = 1;

            break;
        }
    }

    result = 0;

3364
 cleanup:
3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386
    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;

3387
    if (esxVI_EnsureSession(priv->primary) < 0)
3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403
        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.
         */
3404
        if (esxVI_LookupAutoStartDefaults(priv->primary, &defaults) < 0)
3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418
            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;
            }

3419
            for (powerInfo = powerInfoList; powerInfo;
3420 3421
                 powerInfo = powerInfo->_next) {
                if (STRNEQ(powerInfo->key->value, virtualMachine->obj->value)) {
3422 3423 3424
                    virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                                   _("Cannot enable general autostart option "
                                     "without affecting other domains"));
3425 3426 3427 3428 3429
                    goto cleanup;
                }
            }

            /* Enable autostart in general */
3430
            if (esxVI_AutoStartDefaults_Alloc(&spec->defaults) < 0)
3431 3432 3433 3434 3435 3436 3437 3438 3439
                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 ||
3440
        esxVI_Int_Alloc(&newPowerInfo->stopDelay) < 0) {
3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451
        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";

3452 3453 3454 3455 3456
    if (esxVI_AutoStartPowerInfo_AppendToList(&spec->powerInfo,
                                              newPowerInfo) < 0) {
        goto cleanup;
    }

3457
    newPowerInfo = NULL;
3458

3459 3460 3461 3462 3463 3464 3465 3466 3467
    if (esxVI_ReconfigureAutostart
          (priv->primary,
           priv->primary->hostSystem->configManager->autoStartManager,
           spec) < 0) {
        goto cleanup;
    }

    result = 0;

3468
 cleanup:
3469
    if (newPowerInfo) {
3470 3471 3472 3473 3474 3475 3476 3477 3478 3479
        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);

3480
    esxVI_AutoStartPowerInfo_Free(&newPowerInfo);
3481

3482 3483 3484 3485 3486
    return result;
}



3487 3488 3489 3490 3491 3492 3493 3494 3495 3496
/*
 * 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:
 *
3497
 * - reservation (VIR_TYPED_PARAM_LLONG >= 0, in megaherz)
3498
 *
3499
 *   The amount of CPU resource that is guaranteed to be available to the domain.
3500 3501
 *
 *
3502
 * - limit (VIR_TYPED_PARAM_LLONG >= 0, or -1, in megaherz)
3503
 *
3504 3505
 *   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
3506 3507 3508 3509
 *   utilization of the domain is unlimited. If the limit is not set to -1, it
 *   must be greater than or equal to the reservation.
 *
 *
3510
 * - shares (VIR_TYPED_PARAM_INT >= 0, or in {-1, -2, -3}, no unit)
3511 3512 3513 3514 3515 3516
 *
 *   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'.
 */
3517
static char *
3518
esxDomainGetSchedulerType(virDomainPtr domain ATTRIBUTE_UNUSED, int *nparams)
3519
{
3520
    char *type;
3521

3522
    if (VIR_STRDUP(type, "allocation") < 0)
3523
        return NULL;
3524

3525
    if (nparams)
3526
        *nparams = 3; /* reservation, limit, shares */
3527 3528 3529 3530 3531 3532 3533

    return type;
}



static int
3534 3535 3536
esxDomainGetSchedulerParametersFlags(virDomainPtr domain,
                                     virTypedParameterPtr params, int *nparams,
                                     unsigned int flags)
3537
{
M
Matthias Bolte 已提交
3538
    int result = -1;
M
Matthias Bolte 已提交
3539
    esxPrivate *priv = domain->conn->privateData;
3540 3541 3542 3543 3544
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    unsigned int mask = 0;
3545
    size_t i = 0;
3546

3547 3548
    virCheckFlags(0, -1);

3549
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
3550
        return -1;
3551

3552
    if (esxVI_String_AppendValueListToList(&propertyNameList,
3553 3554 3555
                                           "config.cpuAllocation.reservation\0"
                                           "config.cpuAllocation.limit\0"
                                           "config.cpuAllocation.shares\0") < 0 ||
3556
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
3557
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3558
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3559
        goto cleanup;
3560 3561 3562
    }

    for (dynamicProperty = virtualMachine->propSet;
3563
         dynamicProperty && mask != 7 && i < 3 && i < *nparams;
3564 3565
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.cpuAllocation.reservation") &&
M
Matthias Bolte 已提交
3566
            ! (mask & (1 << 0))) {
3567
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3568
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3569
                goto cleanup;
3570
            }
3571 3572 3573 3574 3575
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_SCHEDULER_RESERVATION,
                                        VIR_TYPED_PARAM_LLONG,
                                        dynamicProperty->val->int64) < 0)
                goto cleanup;
3576 3577 3578 3579
            mask |= 1 << 0;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.limit") &&
M
Matthias Bolte 已提交
3580
                   ! (mask & (1 << 1))) {
3581
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3582
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3583
                goto cleanup;
3584
            }
3585 3586 3587 3588 3589
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_SCHEDULER_LIMIT,
                                        VIR_TYPED_PARAM_LLONG,
                                        dynamicProperty->val->int64) < 0)
                goto cleanup;
3590 3591 3592 3593
            mask |= 1 << 1;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.shares") &&
M
Matthias Bolte 已提交
3594
                   ! (mask & (1 << 2))) {
3595 3596 3597 3598
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_SCHEDULER_SHARES,
                                        VIR_TYPED_PARAM_INT, 0) < 0)
                goto cleanup;
3599
            if (esxVI_SharesInfo_CastFromAnyType(dynamicProperty->val,
3600
                                                 &sharesInfo) < 0) {
M
Matthias Bolte 已提交
3601
                goto cleanup;
3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621
            }

            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:
3622 3623 3624
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Shares level has unknown value %d"),
                               (int)sharesInfo->level);
3625
                esxVI_SharesInfo_Free(&sharesInfo);
M
Matthias Bolte 已提交
3626
                goto cleanup;
3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638
            }

            esxVI_SharesInfo_Free(&sharesInfo);

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

    *nparams = i;
M
Matthias Bolte 已提交
3639
    result = 0;
3640

3641
 cleanup:
3642 3643 3644 3645 3646 3647
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
}

3648 3649 3650 3651 3652 3653
static int
esxDomainGetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int *nparams)
{
    return esxDomainGetSchedulerParametersFlags(domain, params, nparams, 0);
}
3654 3655 3656


static int
3657 3658 3659
esxDomainSetSchedulerParametersFlags(virDomainPtr domain,
                                     virTypedParameterPtr params, int nparams,
                                     unsigned int flags)
3660
{
M
Matthias Bolte 已提交
3661
    int result = -1;
M
Matthias Bolte 已提交
3662
    esxPrivate *priv = domain->conn->privateData;
3663 3664 3665 3666 3667
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3668
    char *taskInfoErrorMessage = NULL;
3669
    size_t i;
3670

3671
    virCheckFlags(0, -1);
3672 3673 3674 3675 3676 3677 3678 3679
    if (virTypedParamsValidate(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)
3680
        return -1;
3681

3682
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
3683
        return -1;
3684

3685
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3686
          (priv->primary, domain->uuid, NULL, &virtualMachine,
3687
           priv->parsedUri->autoAnswer) < 0 ||
3688 3689
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->cpuAllocation) < 0) {
M
Matthias Bolte 已提交
3690
        goto cleanup;
3691 3692 3693
    }

    for (i = 0; i < nparams; ++i) {
3694
        if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_RESERVATION)) {
3695
            if (esxVI_Long_Alloc(&spec->cpuAllocation->reservation) < 0)
M
Matthias Bolte 已提交
3696
                goto cleanup;
3697 3698

            if (params[i].value.l < 0) {
3699 3700 3701
                virReportError(VIR_ERR_INVALID_ARG,
                               _("Could not set reservation to %lld MHz, expecting "
                                 "positive value"), params[i].value.l);
M
Matthias Bolte 已提交
3702
                goto cleanup;
3703 3704 3705
            }

            spec->cpuAllocation->reservation->value = params[i].value.l;
3706
        } else if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_LIMIT)) {
3707
            if (esxVI_Long_Alloc(&spec->cpuAllocation->limit) < 0)
M
Matthias Bolte 已提交
3708
                goto cleanup;
3709 3710

            if (params[i].value.l < -1) {
3711 3712 3713 3714
                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 已提交
3715
                goto cleanup;
3716 3717 3718
            }

            spec->cpuAllocation->limit->value = params[i].value.l;
3719
        } else if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_SHARES)) {
3720 3721
            if (esxVI_SharesInfo_Alloc(&sharesInfo) < 0 ||
                esxVI_Int_Alloc(&sharesInfo->shares) < 0) {
M
Matthias Bolte 已提交
3722
                goto cleanup;
3723 3724 3725
            }

            spec->cpuAllocation->shares = sharesInfo;
3726
            sharesInfo = NULL;
3727

3728
            if (params[i].value.i >= 0) {
3729
                spec->cpuAllocation->shares->level = esxVI_SharesLevel_Custom;
3730
                spec->cpuAllocation->shares->shares->value = params[i].value.i;
3731
            } else {
3732
                switch (params[i].value.i) {
3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750
                  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:
3751 3752 3753 3754
                    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 已提交
3755
                    goto cleanup;
3756 3757 3758 3759 3760
                }
            }
        }
    }

3761
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
3762
                              &task) < 0 ||
3763
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3764
                                    esxVI_Occurrence_RequiredItem,
3765
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3766
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3767
        goto cleanup;
3768 3769 3770
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3771 3772 3773
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not change scheduler parameters: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3774
        goto cleanup;
3775 3776
    }

M
Matthias Bolte 已提交
3777 3778
    result = 0;

3779
 cleanup:
3780
    esxVI_SharesInfo_Free(&sharesInfo);
3781 3782 3783
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
3784
    VIR_FREE(taskInfoErrorMessage);
3785 3786 3787 3788

    return result;
}

3789 3790 3791 3792 3793 3794
static int
esxDomainSetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int nparams)
{
    return esxDomainSetSchedulerParametersFlags(domain, params, nparams, 0);
}
3795

E
Eric Blake 已提交
3796 3797 3798 3799 3800 3801
/* 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)
3802 3803 3804 3805 3806

static int
esxDomainMigratePrepare(virConnectPtr dconn,
                        char **cookie ATTRIBUTE_UNUSED,
                        int *cookielen ATTRIBUTE_UNUSED,
3807 3808
                        const char *uri_in ATTRIBUTE_UNUSED,
                        char **uri_out,
E
Eric Blake 已提交
3809
                        unsigned long flags,
3810 3811 3812
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
3813
    esxPrivate *priv = dconn->privateData;
3814

E
Eric Blake 已提交
3815 3816
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

3817
    if (!uri_in) {
3818 3819 3820
        if (virAsprintf(uri_out, "vpxmigr://%s/%s/%s",
                        priv->vCenter->ipAddress,
                        priv->vCenter->computeResource->resourcePool->value,
3821
                        priv->vCenter->hostSystem->_reference->value) < 0)
3822
            return -1;
3823 3824
    }

3825
    return 0;
3826 3827 3828 3829 3830 3831 3832 3833 3834
}



static int
esxDomainMigratePerform(virDomainPtr domain,
                        const char *cookie ATTRIBUTE_UNUSED,
                        int cookielen ATTRIBUTE_UNUSED,
                        const char *uri,
E
Eric Blake 已提交
3835
                        unsigned long flags,
3836 3837 3838
                        const char *dname,
                        unsigned long bandwidth ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
3839
    int result = -1;
M
Matthias Bolte 已提交
3840
    esxPrivate *priv = domain->conn->privateData;
M
Martin Kletzander 已提交
3841
    virURIPtr parsedUri = NULL;
3842 3843 3844
    char *saveptr;
    char *path_resourcePool;
    char *path_hostSystem;
3845
    esxVI_ObjectContent *virtualMachine = NULL;
3846 3847
    esxVI_ManagedObjectReference resourcePool;
    esxVI_ManagedObjectReference hostSystem;
3848 3849 3850
    esxVI_Event *eventList = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3851
    char *taskInfoErrorMessage = NULL;
3852

E
Eric Blake 已提交
3853 3854
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

3855
    if (!priv->vCenter) {
3856 3857
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration not possible without a vCenter"));
M
Matthias Bolte 已提交
3858
        return -1;
3859 3860
    }

3861
    if (dname) {
3862 3863
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Renaming domains on migration not supported"));
M
Matthias Bolte 已提交
3864
        return -1;
3865 3866
    }

3867
    if (esxVI_EnsureSession(priv->vCenter) < 0)
M
Matthias Bolte 已提交
3868
        return -1;
3869

3870
    /* Parse migration URI */
3871
    if (!(parsedUri = virURIParse(uri)))
M
Matthias Bolte 已提交
3872
        return -1;
3873

3874
    if (!parsedUri->scheme || STRCASENEQ(parsedUri->scheme, "vpxmigr")) {
3875 3876
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Only vpxmigr:// migration URIs are supported"));
M
Matthias Bolte 已提交
3877
        goto cleanup;
3878 3879
    }

3880
    if (STRCASENEQ(priv->vCenter->ipAddress, parsedUri->server)) {
3881 3882 3883
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration source and destination have to refer to "
                         "the same vCenter"));
3884 3885 3886 3887 3888 3889
        goto cleanup;
    }

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

3890
    if (!path_resourcePool || !path_hostSystem) {
3891 3892
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration URI has to specify resource pool and host system"));
M
Matthias Bolte 已提交
3893
        goto cleanup;
3894 3895
    }

3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908
    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,
3909
           priv->parsedUri->autoAnswer) < 0) {
M
Matthias Bolte 已提交
3910
        goto cleanup;
3911 3912 3913
    }

    /* Validate the purposed migration */
3914
    if (esxVI_ValidateMigration(priv->vCenter, virtualMachine->obj,
3915 3916
                                esxVI_VirtualMachinePowerState_Undefined, NULL,
                                &resourcePool, &hostSystem, &eventList) < 0) {
M
Matthias Bolte 已提交
3917
        goto cleanup;
3918 3919
    }

3920
    if (eventList) {
3921 3922 3923 3924
        /*
         * FIXME: Need to report the complete list of events. Limit reporting
         *        to the first event for now.
         */
3925
        if (eventList->fullFormattedMessage) {
3926 3927 3928
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not migrate domain, validation reported a "
                             "problem: %s"), eventList->fullFormattedMessage);
3929
        } else {
3930 3931 3932
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Could not migrate domain, validation reported a "
                             "problem"));
3933 3934
        }

M
Matthias Bolte 已提交
3935
        goto cleanup;
3936 3937 3938
    }

    /* Perform the purposed migration */
3939 3940
    if (esxVI_MigrateVM_Task(priv->vCenter, virtualMachine->obj,
                             &resourcePool, &hostSystem,
3941 3942 3943
                             esxVI_VirtualMachineMovePriority_DefaultPriority,
                             esxVI_VirtualMachinePowerState_Undefined,
                             &task) < 0 ||
3944
        esxVI_WaitForTaskCompletion(priv->vCenter, task, domain->uuid,
3945
                                    esxVI_Occurrence_RequiredItem,
3946
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3947
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3948
        goto cleanup;
3949 3950 3951
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3952 3953 3954 3955
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not migrate domain, migration task finished with "
                         "an error: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3956
        goto cleanup;
3957 3958
    }

M
Matthias Bolte 已提交
3959 3960
    result = 0;

3961
 cleanup:
3962
    virURIFree(parsedUri);
3963 3964 3965
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Event_Free(&eventList);
    esxVI_ManagedObjectReference_Free(&task);
3966
    VIR_FREE(taskInfoErrorMessage);
3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977

    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 已提交
3978
                       unsigned long flags)
3979
{
E
Eric Blake 已提交
3980 3981
    virCheckFlags(ESX_MIGRATION_FLAGS, NULL);

3982 3983 3984 3985 3986
    return esxDomainLookupByName(dconn, dname);
}



M
Matthias Bolte 已提交
3987 3988 3989 3990
static unsigned long long
esxNodeGetFreeMemory(virConnectPtr conn)
{
    unsigned long long result = 0;
3991
    unsigned long long usageBytes = 0;
M
Matthias Bolte 已提交
3992
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
3993
    esxVI_String *propertyNameList = NULL;
3994 3995 3996
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_Int *memoryUsage = NULL;
    esxVI_Long *memorySize = NULL;
M
Matthias Bolte 已提交
3997

3998
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
3999
        return 0;
M
Matthias Bolte 已提交
4000

4001 4002 4003 4004 4005 4006 4007 4008 4009 4010
    /* Get memory usage of host system */
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "summary.quickStats.overallMemoryUsage\0"
                                           "hardware.memorySize\0") < 0 ||
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0 ||
        esxVI_GetInt(hostSystem, "summary.quickStats.overallMemoryUsage",
                      &memoryUsage, esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_GetLong(hostSystem, "hardware.memorySize", &memorySize,
                      esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4011
        goto cleanup;
M
Matthias Bolte 已提交
4012 4013
    }

4014 4015
    usageBytes = (unsigned long long) (memoryUsage->value) * 1048576;
    result = memorySize->value - usageBytes;
M
Matthias Bolte 已提交
4016

4017
 cleanup:
M
Matthias Bolte 已提交
4018
    esxVI_String_Free(&propertyNameList);
4019 4020 4021
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_Int_Free(&memoryUsage);
    esxVI_Long_Free(&memorySize);
M
Matthias Bolte 已提交
4022 4023 4024 4025 4026 4027

    return result;
}



4028
static int
4029
esxConnectIsEncrypted(virConnectPtr conn)
4030
{
M
Matthias Bolte 已提交
4031
    esxPrivate *priv = conn->privateData;
4032

4033
    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
4034 4035 4036 4037 4038 4039 4040 4041 4042
        return 1;
    } else {
        return 0;
    }
}



static int
4043
esxConnectIsSecure(virConnectPtr conn)
4044
{
M
Matthias Bolte 已提交
4045
    esxPrivate *priv = conn->privateData;
4046

4047
    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
4048 4049 4050 4051 4052 4053 4054 4055
        return 1;
    } else {
        return 0;
    }
}



4056
static int
4057
esxConnectIsAlive(virConnectPtr conn)
4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072
{
    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;
}



4073 4074 4075
static int
esxDomainIsActive(virDomainPtr domain)
{
M
Matthias Bolte 已提交
4076
    int result = -1;
M
Matthias Bolte 已提交
4077
    esxPrivate *priv = domain->conn->privateData;
4078 4079 4080 4081
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

4082
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4083
        return -1;
4084

4085
    if (esxVI_String_AppendValueToList(&propertyNameList,
4086
                                       "runtime.powerState") < 0 ||
4087
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
4088
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
4089
                                         esxVI_Occurrence_RequiredItem) < 0 ||
4090
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
4091
        goto cleanup;
4092 4093 4094 4095 4096 4097 4098 4099
    }

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

4100
 cleanup:
4101 4102 4103 4104 4105 4106 4107 4108 4109
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
4110
esxDomainIsPersistent(virDomainPtr domain)
4111
{
4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127
    /* 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;

4128
 cleanup:
4129 4130 4131
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
4132 4133
}

M
Matthias Bolte 已提交
4134 4135


4136 4137 4138
static int
esxDomainIsUpdated(virDomainPtr domain ATTRIBUTE_UNUSED)
{
4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154
    /* 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;

4155
 cleanup:
4156 4157 4158
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
4159
}
4160

M
Matthias Bolte 已提交
4161 4162


4163 4164
static virDomainSnapshotPtr
esxDomainSnapshotCreateXML(virDomainPtr domain, const char *xmlDesc,
4165
                           unsigned int flags)
4166 4167 4168 4169 4170 4171 4172 4173
{
    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;
4174
    char *taskInfoErrorMessage = NULL;
4175
    virDomainSnapshotPtr snapshot = NULL;
4176 4177
    bool diskOnly = (flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY) != 0;
    bool quiesce = (flags & VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE) != 0;
4178

4179 4180 4181 4182 4183
    /* ESX supports disk-only and quiesced snapshots; libvirt tracks no
     * snapshot metadata so supporting that flag is trivial.  */
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY |
                  VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE |
                  VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA, NULL);
4184

4185
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4186
        return NULL;
4187

4188
    def = virDomainSnapshotDefParseString(xmlDesc, priv->caps,
4189
                                          priv->xmlopt, 0);
4190

4191
    if (!def)
M
Matthias Bolte 已提交
4192
        return NULL;
4193

4194
    if (def->ndisks) {
4195 4196
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("disk snapshots not supported yet"));
4197 4198 4199
        return NULL;
    }

4200
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
4201
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4202
           priv->parsedUri->autoAnswer) < 0 ||
4203
        esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4204 4205
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, def->name,
4206
                                    &snapshotTree, NULL,
4207
                                    esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4208
        goto cleanup;
4209 4210
    }

4211
    if (snapshotTree) {
4212 4213
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Snapshot '%s' already exists"), def->name);
M
Matthias Bolte 已提交
4214
        goto cleanup;
4215 4216
    }

4217
    if (esxVI_CreateSnapshot_Task(priv->primary, virtualMachine->obj,
4218
                                  def->name, def->description,
4219 4220 4221
                                  diskOnly ? esxVI_Boolean_False : esxVI_Boolean_True,
                                  quiesce ? esxVI_Boolean_True : esxVI_Boolean_False,
                                  &task) < 0 ||
4222
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
4223
                                    esxVI_Occurrence_RequiredItem,
4224
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4225
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4226
        goto cleanup;
4227 4228 4229
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4230 4231
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not create snapshot: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4232
        goto cleanup;
4233 4234 4235 4236
    }

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

4237
 cleanup:
4238 4239 4240 4241
    virDomainSnapshotDefFree(def);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4242
    VIR_FREE(taskInfoErrorMessage);
4243 4244 4245 4246 4247 4248 4249

    return snapshot;
}



static char *
4250 4251
esxDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                            unsigned int flags)
4252 4253 4254 4255 4256 4257 4258 4259 4260
{
    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;

4261 4262
    virCheckFlags(0, NULL);

4263
    memset(&def, 0, sizeof(def));
4264

4265
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4266
        return NULL;
4267

4268
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4269 4270 4271 4272
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4273
        goto cleanup;
4274 4275 4276 4277
    }

    def.name = snapshot->name;
    def.description = snapshotTree->description;
4278
    def.parent = snapshotTreeParent ? snapshotTreeParent->name : NULL;
4279 4280 4281

    if (esxVI_DateTime_ConvertToCalendarTime(snapshotTree->createTime,
                                             &def.creationTime) < 0) {
M
Matthias Bolte 已提交
4282
        goto cleanup;
4283 4284 4285 4286 4287 4288 4289
    }

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

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

4290 4291 4292
    xml = virDomainSnapshotDefFormat(uuid_string, &def,
                                     virDomainDefFormatConvertXMLFlags(flags),
                                     0);
4293

4294
 cleanup:
4295 4296 4297 4298 4299 4300 4301 4302
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return xml;
}



static int
4303
esxDomainSnapshotNum(virDomainPtr domain, unsigned int flags)
4304
{
M
Matthias Bolte 已提交
4305
    int count;
4306 4307
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
4308
    bool recurse;
4309
    bool leaves;
4310

4311
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
4312 4313
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4314 4315

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) == 0;
4316
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4317

4318
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4319
        return -1;
4320

4321 4322 4323 4324
    /* ESX snapshots do not require libvirt to maintain any metadata.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA)
        return 0;

4325
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4326
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4327
        return -1;
4328 4329
    }

4330 4331
    count = esxVI_GetNumberOfSnapshotTrees(rootSnapshotTreeList, recurse,
                                           leaves);
4332 4333 4334

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

M
Matthias Bolte 已提交
4335
    return count;
4336 4337 4338 4339 4340 4341
}



static int
esxDomainSnapshotListNames(virDomainPtr domain, char **names, int nameslen,
4342
                           unsigned int flags)
4343
{
M
Matthias Bolte 已提交
4344
    int result;
4345 4346
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
4347
    bool recurse;
4348
    bool leaves;
4349 4350

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
4351 4352
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4353

4354
    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) == 0;
4355
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4356

4357
    if (!names || nameslen < 0) {
4358
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
4359 4360 4361
        return -1;
    }

4362
    if (nameslen == 0 || (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA))
4363 4364
        return 0;

4365
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4366
        return -1;
4367

4368
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4369
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4370
        return -1;
4371 4372
    }

4373
    result = esxVI_GetSnapshotTreeNames(rootSnapshotTreeList, names, nameslen,
4374
                                        recurse, leaves);
4375 4376 4377 4378 4379 4380 4381 4382

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



4383 4384 4385 4386 4387 4388 4389 4390
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;
4391
    bool leaves;
4392 4393

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

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

4400
    if (esxVI_EnsureSession(priv->primary) < 0)
4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417
        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,
4418
                                           recurse, leaves);
4419

4420
 cleanup:
4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437
    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;
4438
    bool leaves;
4439 4440

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

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

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

4452
    if (nameslen == 0)
4453 4454
        return 0;

4455
    if (esxVI_EnsureSession(priv->primary) < 0)
4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472
        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,
4473
                                        names, nameslen, recurse, leaves);
4474

4475
 cleanup:
4476 4477 4478 4479 4480 4481 4482
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



4483 4484
static virDomainSnapshotPtr
esxDomainSnapshotLookupByName(virDomainPtr domain, const char *name,
4485
                              unsigned int flags)
4486 4487 4488 4489 4490 4491
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    virDomainSnapshotPtr snapshot = NULL;

4492 4493
    virCheckFlags(0, NULL);

4494
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4495
        return NULL;
4496

4497
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4498 4499
                                         &rootSnapshotTreeList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotTreeList, name, &snapshotTree,
4500
                                    NULL,
4501 4502 4503 4504 4505 4506
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    snapshot = virGetDomainSnapshot(domain, name);

4507
 cleanup:
4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return snapshot;
}



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

4521
    virCheckFlags(0, -1);
4522

4523
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4524
        return -1;
4525

4526
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4527 4528
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4529
        return -1;
4530 4531
    }

4532
    if (currentSnapshotTree) {
M
Matthias Bolte 已提交
4533 4534
        esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);
        return 1;
4535 4536
    }

M
Matthias Bolte 已提交
4537
    return 0;
4538 4539 4540 4541
}



E
Eric Blake 已提交
4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552
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);

4553
    if (esxVI_EnsureSession(priv->primary) < 0)
E
Eric Blake 已提交
4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564
        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) {
4565 4566 4567
        virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                       _("snapshot '%s' does not have a parent"),
                       snapshotTree->name);
E
Eric Blake 已提交
4568 4569 4570 4571 4572
        goto cleanup;
    }

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

4573
 cleanup:
E
Eric Blake 已提交
4574 4575 4576 4577 4578 4579 4580
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return parent;
}



4581 4582 4583 4584 4585
static virDomainSnapshotPtr
esxDomainSnapshotCurrent(virDomainPtr domain, unsigned int flags)
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *currentSnapshotTree = NULL;
M
Matthias Bolte 已提交
4586
    virDomainSnapshotPtr snapshot = NULL;
4587

4588
    virCheckFlags(0, NULL);
4589

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

4593
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4594 4595
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4596
        return NULL;
4597 4598 4599 4600 4601 4602 4603 4604 4605 4606
    }

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

    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return snapshot;
}


4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617
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);

4618
    if (esxVI_EnsureSession(priv->primary) < 0)
4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637
        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);

4638
 cleanup:
4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654
    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);

4655
    if (esxVI_EnsureSession(priv->primary) < 0)
4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668
        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;

4669
 cleanup:
4670 4671 4672 4673
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    return ret;
}

4674 4675 4676 4677

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

4686
    virCheckFlags(0, -1);
4687

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

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

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

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

M
Matthias Bolte 已提交
4715 4716
    result = 0;

4717
 cleanup:
4718 4719
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4720
    VIR_FREE(taskInfoErrorMessage);
4721 4722 4723 4724 4725 4726 4727 4728 4729

    return result;
}



static int
esxDomainSnapshotDelete(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4730
    int result = -1;
4731 4732 4733 4734 4735 4736
    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;
4737
    char *taskInfoErrorMessage = NULL;
4738

4739 4740
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
                  VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY, -1);
4741

4742
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4743
        return -1;
4744

4745
    if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN)
4746 4747
        removeChildren = esxVI_Boolean_True;

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

4756 4757 4758 4759 4760 4761 4762
    /* 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;
    }

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

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

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

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

    return result;
}



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

    virCheckFlags(0, -1);
4805 4806 4807 4808
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_MEMORY_MIN_GUARANTEE,
                               VIR_TYPED_PARAM_ULLONG,
                               NULL) < 0)
4809
        return -1;
4810

4811
    if (esxVI_EnsureSession(priv->primary) < 0)
4812 4813 4814 4815
        return -1;

    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4816
           priv->parsedUri->autoAnswer) < 0 ||
4817 4818 4819 4820 4821 4822
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0) {
        goto cleanup;
    }

    for (i = 0; i < nparams; ++i) {
4823
        if (STREQ(params[i].field, VIR_DOMAIN_MEMORY_MIN_GUARANTEE)) {
4824
            if (esxVI_Long_Alloc(&spec->memoryAllocation->reservation) < 0)
4825 4826 4827
                goto cleanup;

            spec->memoryAllocation->reservation->value =
4828
              VIR_DIV_UP(params[i].value.ul, 1024); /* Scale from kilobytes to megabytes */
4829 4830 4831 4832 4833 4834 4835
        }
    }

    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
4836
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4837
                                    &taskInfoErrorMessage) < 0) {
4838 4839 4840 4841
        goto cleanup;
    }

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

    result = 0;

4850
 cleanup:
4851 4852 4853
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
4854
    VIR_FREE(taskInfoErrorMessage);
4855 4856 4857 4858 4859 4860 4861

    return result;
}



static int
4862
esxDomainGetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877
                             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;
    }

4878
    if (esxVI_EnsureSession(priv->primary) < 0)
4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890
        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;
    }

4891 4892 4893 4894
    /* Scale from megabytes to kilobytes */
    if (virTypedParameterAssign(params, VIR_DOMAIN_MEMORY_MIN_GUARANTEE,
                                VIR_TYPED_PARAM_ULLONG,
                                reservation->value * 1024) < 0)
4895 4896 4897 4898 4899
        goto cleanup;

    *nparams = 1;
    result = 0;

4900
 cleanup:
4901 4902 4903 4904 4905 4906 4907
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Long_Free(&reservation);

    return result;
}

4908 4909
#define MATCH(FLAG) (flags & (FLAG))
static int
4910 4911 4912
esxConnectListAllDomains(virConnectPtr conn,
                         virDomainPtr **domains,
                         unsigned int flags)
4913 4914 4915
{
    int ret = -1;
    esxPrivate *priv = conn->privateData;
4916 4917
    bool needIdentity;
    bool needPowerState;
4918 4919 4920
    virDomainPtr dom;
    virDomainPtr *doms = NULL;
    size_t ndoms = 0;
4921
    esxVI_String *propertyNameList = NULL;
4922 4923
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
4924
    esxVI_AutoStartDefaults *autoStartDefaults = NULL;
4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941
    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
     */
4942
    if ((MATCH(VIR_CONNECT_LIST_DOMAINS_TRANSIENT) &&
4943 4944 4945 4946 4947
         !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)
4948
            goto cleanup;
4949 4950 4951 4952 4953

        ret = 0;
        goto cleanup;
    }

4954
    if (esxVI_EnsureSession(priv->primary) < 0)
4955 4956 4957 4958 4959
        return -1;

    /* check system default autostart value */
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_AUTOSTART)) {
        if (esxVI_LookupAutoStartDefaults(priv->primary,
4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972
                                          &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) ||
4973
                   domains;
4974 4975 4976 4977 4978 4979 4980

    if (needIdentity) {
        /* Request required data for esxVI_GetVirtualMachineIdentity */
        if (esxVI_String_AppendValueListToList(&propertyNameList,
                                               "configStatus\0"
                                               "name\0"
                                               "config.uuid\0") < 0) {
4981
            goto cleanup;
4982 4983 4984 4985 4986
        }
    }

    needPowerState = MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_ACTIVE) ||
                     MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_STATE) ||
4987
                     domains;
4988

4989 4990 4991
    if (needPowerState) {
        if (esxVI_String_AppendValueToList(&propertyNameList,
                                           "runtime.powerState") < 0) {
4992
            goto cleanup;
4993
        }
4994 4995
    }

4996
    if (esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
4997 4998 4999 5000 5001
                                       &virtualMachineList) < 0)
        goto cleanup;

    if (domains) {
        if (VIR_ALLOC_N(doms, 1) < 0)
5002
            goto cleanup;
5003 5004 5005
        ndoms = 1;
    }

5006
    for (virtualMachine = virtualMachineList; virtualMachine;
5007
         virtualMachine = virtualMachine->_next) {
5008 5009
        if (needIdentity) {
            VIR_FREE(name);
5010

5011 5012 5013 5014 5015
            if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id,
                                                &name, uuid) < 0) {
                goto cleanup;
            }
        }
5016

5017 5018 5019 5020 5021 5022
        if (needPowerState) {
            if (esxVI_GetVirtualMachinePowerState(virtualMachine,
                                                  &powerState) < 0) {
                goto cleanup;
            }
        }
5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033

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

5036 5037 5038 5039 5040 5041
            if (esxVI_LookupRootSnapshotTreeList(priv->primary, uuid,
                                                 &rootSnapshotTreeList) < 0) {
                goto cleanup;
            }

            if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT) &&
5042
                   rootSnapshotTreeList) ||
5043
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT) &&
5044
                   !rootSnapshotTreeList)))
5045 5046 5047 5048 5049 5050 5051
                continue;
        }

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

5052
            if (autoStartDefaults->enabled == esxVI_Boolean_True) {
5053
                for (powerInfo = powerInfoList; powerInfo;
5054 5055 5056 5057
                     powerInfo = powerInfo->_next) {
                    if (STREQ(powerInfo->key->value, virtualMachine->obj->value)) {
                        if (STRCASEEQ(powerInfo->startAction, "powerOn"))
                            autostart = true;
5058

5059 5060
                        break;
                    }
5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073
                }
            }

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

5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093
            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;
        }

5094
        if (VIR_RESIZE_N(doms, ndoms, count, 2) < 0)
5095
            goto cleanup;
5096

5097 5098 5099
        if (!(dom = virGetDomain(conn, name, uuid)))
            goto cleanup;

5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113
        /* 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;

5114
 cleanup:
5115
    if (doms) {
5116
        for (id = 0; id < count; id++)
5117
            virObjectUnref(doms[id]);
5118 5119

        VIR_FREE(doms);
5120
    }
5121

5122
    VIR_FREE(name);
5123 5124
    esxVI_AutoStartDefaults_Free(&autoStartDefaults);
    esxVI_AutoStartPowerInfo_Free(&powerInfoList);
5125 5126
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
5127 5128
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

5129 5130 5131
    return ret;
}
#undef MATCH
5132

5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168
static int
esxDomainHasManagedSaveImage(virDomainPtr domain, unsigned int flags)
{
    int result = -1;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_ManagedObjectReference *managedObjectReference = NULL;
    char uuid_string[VIR_UUID_STRING_BUFLEN] = "";

    virCheckFlags(0, -1);

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

    virUUIDFormat(domain->uuid, uuid_string);

    if (esxVI_FindByUuid(priv->primary, priv->primary->datacenter->_reference,
                         uuid_string, esxVI_Boolean_True,
                         esxVI_Boolean_Undefined,
                         &managedObjectReference) < 0) {
        return -1;
    }

    if (!managedObjectReference) {
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("Could not find domain with UUID '%s'"),
                       uuid_string);
        goto cleanup;
    }

    result = 0;

 cleanup:
    esxVI_ManagedObjectReference_Free(&managedObjectReference);
    return result;
}

5169

5170
static virHypervisorDriver esxHypervisorDriver = {
5171
    .name = "ESX",
5172 5173 5174 5175 5176 5177
    .connectOpen = esxConnectOpen, /* 0.7.0 */
    .connectClose = esxConnectClose, /* 0.7.0 */
    .connectSupportsFeature = esxConnectSupportsFeature, /* 0.7.0 */
    .connectGetType = esxConnectGetType, /* 0.7.0 */
    .connectGetVersion = esxConnectGetVersion, /* 0.7.0 */
    .connectGetHostname = esxConnectGetHostname, /* 0.7.0 */
5178
    .nodeGetInfo = esxNodeGetInfo, /* 0.7.0 */
5179 5180 5181 5182
    .connectGetCapabilities = esxConnectGetCapabilities, /* 0.7.1 */
    .connectListDomains = esxConnectListDomains, /* 0.7.0 */
    .connectNumOfDomains = esxConnectNumOfDomains, /* 0.7.0 */
    .connectListAllDomains = esxConnectListAllDomains, /* 0.10.2 */
5183 5184 5185 5186 5187 5188
    .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 */
5189
    .domainShutdownFlags = esxDomainShutdownFlags, /* 0.9.10 */
5190 5191
    .domainReboot = esxDomainReboot, /* 0.7.0 */
    .domainDestroy = esxDomainDestroy, /* 0.7.0 */
5192
    .domainDestroyFlags = esxDomainDestroyFlags, /* 0.9.4 */
5193 5194 5195 5196 5197 5198 5199 5200
    .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 */
5201
    .domainScreenshot = esxDomainScreenshot, /* 1.2.10 */
5202 5203 5204 5205 5206
    .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 */
5207 5208 5209 5210
    .connectDomainXMLFromNative = esxConnectDomainXMLFromNative, /* 0.7.0 */
    .connectDomainXMLToNative = esxConnectDomainXMLToNative, /* 0.7.2 */
    .connectListDefinedDomains = esxConnectListDefinedDomains, /* 0.7.0 */
    .connectNumOfDefinedDomains = esxConnectNumOfDefinedDomains, /* 0.7.0 */
5211 5212 5213
    .domainCreate = esxDomainCreate, /* 0.7.0 */
    .domainCreateWithFlags = esxDomainCreateWithFlags, /* 0.8.2 */
    .domainDefineXML = esxDomainDefineXML, /* 0.7.2 */
5214
    .domainDefineXMLFlags = esxDomainDefineXMLFlags, /* 1.2.12 */
5215
    .domainUndefine = esxDomainUndefine, /* 0.7.1 */
5216
    .domainUndefineFlags = esxDomainUndefineFlags, /* 0.9.4 */
5217 5218 5219 5220
    .domainGetAutostart = esxDomainGetAutostart, /* 0.9.0 */
    .domainSetAutostart = esxDomainSetAutostart, /* 0.9.0 */
    .domainGetSchedulerType = esxDomainGetSchedulerType, /* 0.7.0 */
    .domainGetSchedulerParameters = esxDomainGetSchedulerParameters, /* 0.7.0 */
5221
    .domainGetSchedulerParametersFlags = esxDomainGetSchedulerParametersFlags, /* 0.9.2 */
5222
    .domainSetSchedulerParameters = esxDomainSetSchedulerParameters, /* 0.7.0 */
5223
    .domainSetSchedulerParametersFlags = esxDomainSetSchedulerParametersFlags, /* 0.9.2 */
5224 5225 5226 5227
    .domainMigratePrepare = esxDomainMigratePrepare, /* 0.7.0 */
    .domainMigratePerform = esxDomainMigratePerform, /* 0.7.0 */
    .domainMigrateFinish = esxDomainMigrateFinish, /* 0.7.0 */
    .nodeGetFreeMemory = esxNodeGetFreeMemory, /* 0.7.2 */
5228 5229
    .connectIsEncrypted = esxConnectIsEncrypted, /* 0.7.3 */
    .connectIsSecure = esxConnectIsSecure, /* 0.7.3 */
5230 5231 5232 5233 5234 5235 5236
    .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 */
5237 5238
    .domainSnapshotNumChildren = esxDomainSnapshotNumChildren, /* 0.9.7 */
    .domainSnapshotListChildrenNames = esxDomainSnapshotListChildrenNames, /* 0.9.7 */
5239 5240
    .domainSnapshotLookupByName = esxDomainSnapshotLookupByName, /* 0.8.0 */
    .domainHasCurrentSnapshot = esxDomainHasCurrentSnapshot, /* 0.8.0 */
E
Eric Blake 已提交
5241
    .domainSnapshotGetParent = esxDomainSnapshotGetParent, /* 0.9.7 */
5242 5243
    .domainSnapshotCurrent = esxDomainSnapshotCurrent, /* 0.8.0 */
    .domainRevertToSnapshot = esxDomainRevertToSnapshot, /* 0.8.0 */
5244 5245
    .domainSnapshotIsCurrent = esxDomainSnapshotIsCurrent, /* 0.9.13 */
    .domainSnapshotHasMetadata = esxDomainSnapshotHasMetadata, /* 0.9.13 */
5246
    .domainSnapshotDelete = esxDomainSnapshotDelete, /* 0.8.0 */
5247
    .connectIsAlive = esxConnectIsAlive, /* 0.9.8 */
5248
    .domainHasManagedSaveImage = esxDomainHasManagedSaveImage, /* 1.2.13 */
5249 5250 5251
};


5252 5253 5254 5255 5256 5257
static virConnectDriver esxConnectDriver = {
    .hypervisorDriver = &esxHypervisorDriver,
    .interfaceDriver = &esxInterfaceDriver,
    .networkDriver = &esxNetworkDriver,
    .storageDriver = &esxStorageDriver,
};
5258 5259 5260 5261

int
esxRegister(void)
{
5262 5263
    return virRegisterConnectDriver(&esxConnectDriver,
                                    false);
5264
}