esx_driver.c 171.2 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
 *
 */

#include <config.h>

#include "internal.h"
27
#include "virdomainobjlist.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
 *
 * 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
270
 * datastore and its 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
                 char **vCenterIPAddress)
616 617 618 619 620 621 622 623 624
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
    char *password = NULL;
    char *url = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_Boolean inMaintenanceMode = esxVI_Boolean_Undefined;
625 626 627
    esxVI_ProductLine expectedProductLine = STRCASEEQ(conn->uri->scheme, "esx")
        ? esxVI_ProductLine_ESX
        : esxVI_ProductLine_GSX;
628

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

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

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

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

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

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

656
    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->parsedUri->transport,
657
                    conn->uri->server, conn->uri->port) < 0)
658 659 660 661
        goto cleanup;

    if (esxVI_Context_Alloc(&priv->host) < 0 ||
        esxVI_Context_Connect(priv->host, url, ipAddress, username, password,
662
                              priv->parsedUri) < 0 ||
663
        esxVI_Context_LookupManagedObjects(priv->host) < 0) {
664 665 666
        goto cleanup;
    }

667 668 669 670 671 672 673
    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;
674 675 676 677 678 679
    }

    /* Query the host for maintenance mode and vCenter IP address */
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "runtime.inMaintenanceMode\0"
                                           "summary.managementServerIp\0") < 0 ||
680 681
        esxVI_LookupHostSystemProperties(priv->host, propertyNameList,
                                         &hostSystem) < 0 ||
682 683 684 685
        esxVI_GetBoolean(hostSystem, "runtime.inMaintenanceMode",
                         &inMaintenanceMode,
                         esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_GetStringValue(hostSystem, "summary.managementServerIp",
686
                             vCenterIPAddress,
687 688 689 690 691
                             esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
    }

    /* Warn if host is in maintenance mode */
692
    if (inMaintenanceMode == esxVI_Boolean_True)
693
        VIR_WARN("The server is in maintenance mode");
694

695
    if (VIR_STRDUP(*vCenterIPAddress, *vCenterIPAddress) < 0)
696
        goto cleanup;
697 698 699

    result = 0;

700
 cleanup:
701
    VIR_FREE(username);
M
Matthias Bolte 已提交
702
    VIR_FREE(password);
703 704 705 706 707 708 709 710 711 712
    VIR_FREE(url);
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



static int
713 714
esxConnectToVCenter(esxPrivate *priv,
                    virConnectPtr conn,
715 716
                    virConnectAuthPtr auth,
                    const char *hostname,
717
                    const char *hostSystemIPAddress)
718 719 720 721 722 723 724
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
    char *password = NULL;
    char *url = NULL;

725
    if (!hostSystemIPAddress &&
726
        (!priv->parsedUri->path || STREQ(priv->parsedUri->path, "/"))) {
727 728
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Path has to specify the datacenter and compute resource"));
729 730 731
        return -1;
    }

732
    if (esxUtil_ResolveHostname(hostname, ipAddress, NI_MAXHOST) < 0)
733 734
        return -1;

735
    if (conn->uri->user) {
736
        if (VIR_STRDUP(username, conn->uri->user) < 0)
737 738
            goto cleanup;
    } else {
739
        username = virAuthGetUsername(conn, auth, "esx", "administrator", hostname);
740

741
        if (!username) {
742
            virReportError(VIR_ERR_AUTH_FAILED, "%s", _("Username request failed"));
743 744 745 746
            goto cleanup;
        }
    }

747
    password = virAuthGetPassword(conn, auth, "esx", username, hostname);
748

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

754
    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->parsedUri->transport,
755
                    hostname, conn->uri->port) < 0)
756 757 758 759
        goto cleanup;

    if (esxVI_Context_Alloc(&priv->vCenter) < 0 ||
        esxVI_Context_Connect(priv->vCenter, url, ipAddress, username,
760
                              password, priv->parsedUri) < 0) {
761 762 763
        goto cleanup;
    }

764
    if (priv->vCenter->productLine != esxVI_ProductLine_VPX) {
765
        virReportError(VIR_ERR_INTERNAL_ERROR,
766 767 768 769
                       _("Expecting '%s' to be a %s host but found a %s host"),
                       hostname,
                       esxVI_ProductLineToDisplayName(esxVI_ProductLine_VPX),
                       esxVI_ProductLineToDisplayName(priv->vCenter->productLine));
770 771 772
        goto cleanup;
    }

773
    if (hostSystemIPAddress) {
774
        if (esxVI_Context_LookupManagedObjectsByHostSystemIp
775
              (priv->vCenter, hostSystemIPAddress) < 0) {
776 777 778
            goto cleanup;
        }
    } else {
779 780
        if (esxVI_Context_LookupManagedObjectsByPath(priv->vCenter,
                                                     priv->parsedUri->path) < 0) {
781 782 783 784
            goto cleanup;
        }
    }

785 786
    result = 0;

787
 cleanup:
788
    VIR_FREE(username);
M
Matthias Bolte 已提交
789
    VIR_FREE(password);
790 791 792 793 794 795 796
    VIR_FREE(url);

    return result;
}



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

E
Eric Blake 已提交
853 854
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

855
    /* Decline if the URI is NULL or the scheme is NULL */
856
    if (!conn->uri || !conn->uri->scheme)
857 858
        return VIR_DRV_OPEN_DECLINED;

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

862
    if (!plus) {
863 864 865 866 867 868 869 870 871 872 873 874 875
        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;
        }

876 877 878
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Transport '%s' in URI scheme is not supported, try again "
                         "without the transport part"), plus + 1);
879 880 881
        return VIR_DRV_OPEN_ERROR;
    }

882
    if (STRCASENEQ(conn->uri->scheme, "vpx") &&
883
        conn->uri->path && STRNEQ(conn->uri->path, "/")) {
884 885 886 887
        VIR_WARN("Ignoring unexpected path '%s' for non-vpx scheme '%s'",
                 conn->uri->path, conn->uri->scheme);
    }

888
    /* Require server part */
889
    if (!conn->uri->server) {
890 891
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("URI is missing the server part"));
892 893 894 895
        return VIR_DRV_OPEN_ERROR;
    }

    /* Require auth */
896
    if (!auth || !auth->cb) {
897 898
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Missing or invalid auth pointer"));
899
        return VIR_DRV_OPEN_ERROR;
900 901 902
    }

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

906
    if (esxUtil_ParseUri(&priv->parsedUri, conn->uri) < 0)
907 908
        goto cleanup;

M
Matthias Bolte 已提交
909 910
    priv->maxVcpus = -1;
    priv->supportsVMotion = esxVI_Boolean_Undefined;
911
    priv->supportsLongMode = esxVI_Boolean_Undefined;
912
    priv->supportsScreenshot = esxVI_Boolean_Undefined;
913 914
    priv->usedCpuTimeCounterId = -1;

M
Matthias Bolte 已提交
915 916 917 918 919 920 921
    /*
     * 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) {
922 923
        if (STRCASEEQ(conn->uri->scheme, "vpx") ||
            STRCASEEQ(conn->uri->scheme, "esx")) {
924
            if (STRCASEEQ(priv->parsedUri->transport, "https")) {
M
Matthias Bolte 已提交
925 926 927 928 929
                conn->uri->port = 443;
            } else {
                conn->uri->port = 80;
            }
        } else { /* GSX */
930
            if (STRCASEEQ(priv->parsedUri->transport, "https")) {
M
Matthias Bolte 已提交
931 932 933 934
                conn->uri->port = 8333;
            } else {
                conn->uri->port = 8222;
            }
935
        }
M
Matthias Bolte 已提交
936
    }
937

938 939 940
    if (STRCASEEQ(conn->uri->scheme, "esx") ||
        STRCASEEQ(conn->uri->scheme, "gsx")) {
        /* Connect to host */
941
        if (esxConnectToHost(priv, conn, auth,
942
                             &potentialVCenterIPAddress) < 0) {
M
Matthias Bolte 已提交
943
            goto cleanup;
944
        }
945

946
        /* Connect to vCenter */
947
        if (priv->parsedUri->vCenter) {
948
            if (STREQ(priv->parsedUri->vCenter, "*")) {
949
                if (!potentialVCenterIPAddress) {
950 951
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("This host is not managed by a vCenter"));
M
Matthias Bolte 已提交
952
                    goto cleanup;
953 954
                }

955 956
                if (!virStrcpyStatic(vCenterIPAddress,
                                     potentialVCenterIPAddress)) {
957 958
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("vCenter IP address %s too big for destination"),
959
                                   potentialVCenterIPAddress);
960 961 962
                    goto cleanup;
                }
            } else {
963
                if (esxUtil_ResolveHostname(priv->parsedUri->vCenter,
964
                                            vCenterIPAddress, NI_MAXHOST) < 0) {
965 966
                    goto cleanup;
                }
967

968 969
                if (potentialVCenterIPAddress &&
                    STRNEQ(vCenterIPAddress, potentialVCenterIPAddress)) {
970 971 972 973
                    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"),
974 975
                                   potentialVCenterIPAddress, priv->parsedUri->vCenter,
                                   vCenterIPAddress);
M
Matthias Bolte 已提交
976
                    goto cleanup;
977 978
                }
            }
979

980
            if (esxConnectToVCenter(priv, conn, auth,
981
                                    vCenterIPAddress,
982
                                    priv->host->ipAddress) < 0) {
983 984
                goto cleanup;
            }
985 986
        }

987 988 989
        priv->primary = priv->host;
    } else { /* VPX */
        /* Connect to vCenter */
990
        if (esxConnectToVCenter(priv, conn, auth,
991 992
                                conn->uri->server,
                                NULL) < 0) {
M
Matthias Bolte 已提交
993
            goto cleanup;
994 995
        }

996
        priv->primary = priv->vCenter;
997 998
    }

M
Matthias Bolte 已提交
999
    /* Setup capabilities */
1000
    priv->caps = esxCapsInit(priv);
1001

1002
    if (!priv->caps)
M
Matthias Bolte 已提交
1003
        goto cleanup;
1004

1005
    if (!(priv->xmlopt = virVMXDomainXMLConfInit()))
1006 1007
        goto cleanup;

1008 1009
    conn->privateData = priv;
    priv = NULL;
M
Matthias Bolte 已提交
1010
    result = VIR_DRV_OPEN_SUCCESS;
1011

1012
 cleanup:
1013
    esxFreePrivate(&priv);
1014
    VIR_FREE(potentialVCenterIPAddress);
1015

M
Matthias Bolte 已提交
1016
    return result;
1017 1018 1019 1020 1021
}



static int
1022
esxConnectClose(virConnectPtr conn)
1023
{
M
Matthias Bolte 已提交
1024
    esxPrivate *priv = conn->privateData;
E
Eric Blake 已提交
1025
    int result = 0;
1026

1027
    if (priv->host) {
1028 1029 1030 1031 1032
        if (esxVI_EnsureSession(priv->host) < 0 ||
            esxVI_Logout(priv->host) < 0) {
            result = -1;
        }
    }
1033

1034
    if (priv->vCenter) {
E
Eric Blake 已提交
1035 1036 1037 1038
        if (esxVI_EnsureSession(priv->vCenter) < 0 ||
            esxVI_Logout(priv->vCenter) < 0) {
            result = -1;
        }
1039 1040
    }

1041
    esxFreePrivate(&priv);
1042 1043 1044

    conn->privateData = NULL;

E
Eric Blake 已提交
1045
    return result;
1046 1047 1048 1049 1050
}



static esxVI_Boolean
1051
esxSupportsVMotion(esxPrivate *priv)
1052 1053 1054 1055
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;

1056
    if (priv->supportsVMotion != esxVI_Boolean_Undefined)
M
Matthias Bolte 已提交
1057
        return priv->supportsVMotion;
1058

1059
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1060
        return esxVI_Boolean_Undefined;
1061

1062
    if (esxVI_String_AppendValueToList(&propertyNameList,
1063
                                       "capability.vmotionSupported") < 0 ||
1064
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
1065 1066
                                         &hostSystem) < 0 ||
        esxVI_GetBoolean(hostSystem, "capability.vmotionSupported",
1067 1068 1069
                         &priv->supportsVMotion,
                         esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
1070 1071
    }

1072
 cleanup:
M
Matthias Bolte 已提交
1073 1074 1075 1076
    /*
     * 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.
     */
1077 1078 1079
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
1080
    return priv->supportsVMotion;
1081 1082 1083 1084
}



1085 1086 1087 1088 1089 1090 1091 1092 1093 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
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;
}



1119
static int
1120
esxConnectSupportsFeature(virConnectPtr conn, int feature)
1121
{
M
Matthias Bolte 已提交
1122
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1123
    esxVI_Boolean supportsVMotion = esxVI_Boolean_Undefined;
1124 1125 1126

    switch (feature) {
      case VIR_DRV_FEATURE_MIGRATION_V1:
1127
        supportsVMotion = esxSupportsVMotion(priv);
1128

1129
        if (supportsVMotion == esxVI_Boolean_Undefined)
1130 1131
            return -1;

M
Matthias Bolte 已提交
1132
        /* Migration is only possible via a vCenter and if VMotion is enabled */
1133
        return priv->vCenter &&
M
Matthias Bolte 已提交
1134
               supportsVMotion == esxVI_Boolean_True ? 1 : 0;
1135 1136 1137 1138 1139 1140 1141 1142 1143

      default:
        return 0;
    }
}



static const char *
1144
esxConnectGetType(virConnectPtr conn ATTRIBUTE_UNUSED)
1145 1146 1147 1148 1149 1150 1151
{
    return "ESX";
}



static int
1152
esxConnectGetVersion(virConnectPtr conn, unsigned long *version)
1153
{
M
Matthias Bolte 已提交
1154
    esxPrivate *priv = conn->privateData;
1155

1156
    *version = priv->primary->productVersion;
1157 1158 1159 1160 1161 1162 1163

    return 0;
}



static char *
1164
esxConnectGetHostname(virConnectPtr conn)
1165
{
M
Matthias Bolte 已提交
1166
    esxPrivate *priv = conn->privateData;
1167 1168 1169 1170 1171 1172 1173
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    const char *hostName = NULL;
    const char *domainName = NULL;
    char *complete = NULL;

1174
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1175
        return NULL;
1176 1177

    if (esxVI_String_AppendValueListToList
1178
          (&propertyNameList,
1179 1180
           "config.network.dnsConfig.hostName\0"
           "config.network.dnsConfig.domainName\0") < 0 ||
1181 1182
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1183
        goto cleanup;
1184 1185
    }

1186
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
1187 1188 1189
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name,
                  "config.network.dnsConfig.hostName")) {
1190
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1191
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1192
                goto cleanup;
1193 1194 1195 1196 1197
            }

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

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

1209
    if (!hostName || strlen(hostName) < 1) {
1210 1211
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing or empty 'hostName' property"));
M
Matthias Bolte 已提交
1212
        goto cleanup;
1213 1214
    }

1215
    if (!domainName || strlen(domainName) < 1) {
1216
        if (VIR_STRDUP(complete, hostName) < 0)
M
Matthias Bolte 已提交
1217
            goto cleanup;
1218
    } else {
1219
        if (virAsprintf(&complete, "%s.%s", hostName, domainName) < 0)
M
Matthias Bolte 已提交
1220
            goto cleanup;
1221 1222
    }

1223
 cleanup:
M
Matthias Bolte 已提交
1224 1225
    /*
     * If we goto cleanup in case of an error then complete is still NULL,
1226
     * either VIR_STRDUP returned -1 or virAsprintf failed. When virAsprintf
M
Matthias Bolte 已提交
1227 1228
     * fails it guarantees setting complete to NULL
     */
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return complete;
}



static int
esxNodeGetInfo(virConnectPtr conn, virNodeInfoPtr nodeinfo)
{
M
Matthias Bolte 已提交
1240
    int result = -1;
M
Matthias Bolte 已提交
1241
    esxPrivate *priv = conn->privateData;
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
    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;

1253
    memset(nodeinfo, 0, sizeof(*nodeinfo));
1254

1255
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1256
        return -1;
1257

1258
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1259 1260 1261 1262 1263 1264 1265
                                           "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 ||
1266 1267
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1268
        goto cleanup;
1269 1270
    }

1271
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
1272 1273
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuInfo.hz")) {
1274
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1275
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1276
                goto cleanup;
1277 1278 1279 1280 1281
            }

            cpuInfo_hz = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuCores")) {
1282
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1283
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1284
                goto cleanup;
1285 1286 1287 1288 1289
            }

            cpuInfo_numCpuCores = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuPackages")) {
1290
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1291
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1292
                goto cleanup;
1293 1294 1295 1296 1297
            }

            cpuInfo_numCpuPackages = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuThreads")) {
1298
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1299
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1300
                goto cleanup;
1301 1302 1303 1304
            }

            cpuInfo_numCpuThreads = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name, "hardware.memorySize")) {
1305
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1306
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1307
                goto cleanup;
1308 1309 1310 1311 1312
            }

            memorySize = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.numaInfo.numNodes")) {
1313
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1314
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1315
                goto cleanup;
1316 1317 1318 1319 1320
            }

            numaInfo_numNodes = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "summary.hardware.cpuModel")) {
1321
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1322
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1323
                goto cleanup;
1324 1325 1326 1327 1328 1329
            }

            ptr = dynamicProperty->val->string;

            /* Strip the string to fit more relevant information in 32 chars */
            while (*ptr != '\0') {
M
Matthias Bolte 已提交
1330 1331
                if (STRPREFIX(ptr, "  ")) {
                    memmove(ptr, ptr + 1, strlen(ptr + 1) + 1);
1332
                    continue;
1333
                } else if (STRPREFIX(ptr, "(R)") || STRPREFIX(ptr, "(C)")) {
M
Matthias Bolte 已提交
1334
                    memmove(ptr, ptr + 3, strlen(ptr + 3) + 1);
1335
                    continue;
1336 1337 1338
                } else if (STRPREFIX(ptr, "(TM)")) {
                    memmove(ptr, ptr + 4, strlen(ptr + 4) + 1);
                    continue;
1339 1340 1341 1342 1343
                }

                ++ptr;
            }

1344 1345 1346
            if (!virStrncpy(nodeinfo->model, dynamicProperty->val->string,
                            sizeof(nodeinfo->model) - 1,
                            sizeof(nodeinfo->model))) {
1347 1348 1349
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("CPU Model %s too long for destination"),
                               dynamicProperty->val->string);
M
Matthias Bolte 已提交
1350
                goto cleanup;
C
Chris Lalancette 已提交
1351
            }
1352 1353 1354 1355 1356 1357 1358
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    nodeinfo->memory = memorySize / 1024; /* Scale from bytes to kilobytes */
    nodeinfo->cpus = cpuInfo_numCpuCores;
1359
    nodeinfo->mhz = cpuInfo_hz / (1000 * 1000); /* Scale from hz to mhz */
1360 1361 1362 1363 1364 1365 1366 1367 1368
    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 已提交
1369 1370
    result = 0;

1371
 cleanup:
1372 1373 1374 1375 1376 1377 1378 1379
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



1380
static char *
1381
esxConnectGetCapabilities(virConnectPtr conn)
1382
{
M
Matthias Bolte 已提交
1383
    esxPrivate *priv = conn->privateData;
1384

1385
    return virCapabilitiesFormatXML(priv->caps);
1386 1387 1388 1389
}



1390
static int
1391
esxConnectListDomains(virConnectPtr conn, int *ids, int maxids)
1392
{
M
Matthias Bolte 已提交
1393
    bool success = false;
M
Matthias Bolte 已提交
1394
    esxPrivate *priv = conn->privateData;
1395 1396 1397 1398 1399 1400
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;

1401
    if (maxids == 0)
1402 1403
        return 0;

1404
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1405
        return -1;
1406

1407
    if (esxVI_String_AppendValueToList(&propertyNameList,
1408
                                       "runtime.powerState") < 0 ||
1409 1410
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1411
        goto cleanup;
1412 1413
    }

1414
    for (virtualMachine = virtualMachineList; virtualMachine;
1415
         virtualMachine = virtualMachine->_next) {
1416
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1417
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1418
            goto cleanup;
1419 1420
        }

1421
        if (powerState != esxVI_VirtualMachinePowerState_PoweredOn)
1422 1423 1424 1425 1426
            continue;

        if (esxUtil_ParseVirtualMachineIDString(virtualMachine->obj->value,
                                                &ids[count]) < 0 ||
            ids[count] <= 0) {
1427 1428 1429
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to parse positive integer from '%s'"),
                           virtualMachine->obj->value);
M
Matthias Bolte 已提交
1430
            goto cleanup;
1431 1432 1433 1434
        }

        count++;

1435
        if (count >= maxids)
1436 1437 1438
            break;
    }

M
Matthias Bolte 已提交
1439 1440
    success = true;

1441
 cleanup:
1442 1443 1444
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
1445
    return success ? count : -1;
1446 1447 1448 1449 1450
}



static int
1451
esxConnectNumOfDomains(virConnectPtr conn)
1452
{
M
Matthias Bolte 已提交
1453
    esxPrivate *priv = conn->privateData;
1454

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

1458
    return esxVI_LookupNumberOfDomainsByPowerState
1459
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, false);
1460 1461 1462 1463 1464 1465 1466
}



static virDomainPtr
esxDomainLookupByID(virConnectPtr conn, int id)
{
M
Matthias Bolte 已提交
1467
    esxPrivate *priv = conn->privateData;
1468 1469 1470 1471
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
M
Matthias Bolte 已提交
1472 1473 1474
    int id_candidate = -1;
    char *name_candidate = NULL;
    unsigned char uuid_candidate[VIR_UUID_BUFLEN];
1475 1476
    virDomainPtr domain = NULL;

1477
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1478
        return NULL;
1479

1480
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1481
                                           "configStatus\0"
1482 1483
                                           "name\0"
                                           "runtime.powerState\0"
1484
                                           "config.uuid\0") < 0 ||
1485 1486
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1487
        goto cleanup;
1488 1489
    }

1490
    for (virtualMachine = virtualMachineList; virtualMachine;
1491
         virtualMachine = virtualMachine->_next) {
1492
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1493
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1494
            goto cleanup;
1495 1496 1497
        }

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

M
Matthias Bolte 已提交
1501
        VIR_FREE(name_candidate);
1502

1503
        if (esxVI_GetVirtualMachineIdentity(virtualMachine,
M
Matthias Bolte 已提交
1504 1505
                                            &id_candidate, &name_candidate,
                                            uuid_candidate) < 0) {
M
Matthias Bolte 已提交
1506
            goto cleanup;
1507 1508
        }

1509
        if (id != id_candidate)
1510 1511
            continue;

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

1514
        if (!domain)
M
Matthias Bolte 已提交
1515
            goto cleanup;
1516 1517 1518 1519 1520 1521

        domain->id = id;

        break;
    }

1522
    if (!domain)
1523
        virReportError(VIR_ERR_NO_DOMAIN, _("No domain with ID %d"), id);
1524

1525
 cleanup:
1526 1527
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
M
Matthias Bolte 已提交
1528
    VIR_FREE(name_candidate);
1529 1530 1531 1532 1533 1534 1535 1536 1537

    return domain;
}



static virDomainPtr
esxDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
M
Matthias Bolte 已提交
1538
    esxPrivate *priv = conn->privateData;
1539 1540 1541
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1542 1543
    int id = -1;
    char *name = NULL;
1544 1545
    virDomainPtr domain = NULL;

1546
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1547
        return NULL;
1548

1549
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1550
                                           "name\0"
1551
                                           "runtime.powerState\0") < 0 ||
1552
        esxVI_LookupVirtualMachineByUuid(priv->primary, uuid, propertyNameList,
1553
                                         &virtualMachine,
M
Matthias Bolte 已提交
1554
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1555 1556
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, &name, NULL) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1557
        goto cleanup;
1558 1559
    }

1560
    domain = virGetDomain(conn, name, uuid);
1561

1562
    if (!domain)
M
Matthias Bolte 已提交
1563
        goto cleanup;
1564

1565 1566 1567 1568 1569
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1570 1571
    }

1572
 cleanup:
1573
    esxVI_String_Free(&propertyNameList);
1574 1575
    esxVI_ObjectContent_Free(&virtualMachine);
    VIR_FREE(name);
1576 1577 1578 1579 1580 1581 1582 1583 1584

    return domain;
}



static virDomainPtr
esxDomainLookupByName(virConnectPtr conn, const char *name)
{
M
Matthias Bolte 已提交
1585
    esxPrivate *priv = conn->privateData;
1586 1587 1588
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1589 1590
    int id = -1;
    unsigned char uuid[VIR_UUID_BUFLEN];
1591 1592
    virDomainPtr domain = NULL;

1593
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1594
        return NULL;
1595

1596
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1597
                                           "configStatus\0"
1598
                                           "runtime.powerState\0"
1599
                                           "config.uuid\0") < 0 ||
1600
        esxVI_LookupVirtualMachineByName(priv->primary, name, propertyNameList,
1601 1602
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
1603
        goto cleanup;
1604 1605
    }

1606
    if (!virtualMachine) {
1607
        virReportError(VIR_ERR_NO_DOMAIN, _("No domain with name '%s'"), name);
M
Matthias Bolte 已提交
1608
        goto cleanup;
1609
    }
1610

M
Matthias Bolte 已提交
1611 1612 1613
    if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, uuid) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
1614
    }
1615

1616
    domain = virGetDomain(conn, name, uuid);
1617

1618
    if (!domain)
M
Matthias Bolte 已提交
1619
        goto cleanup;
1620

1621 1622 1623 1624 1625
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1626 1627
    }

1628
 cleanup:
1629
    esxVI_String_Free(&propertyNameList);
1630
    esxVI_ObjectContent_Free(&virtualMachine);
1631 1632 1633 1634 1635 1636 1637 1638 1639

    return domain;
}



static int
esxDomainSuspend(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1640
    int result = -1;
M
Matthias Bolte 已提交
1641
    esxPrivate *priv = domain->conn->privateData;
1642 1643 1644 1645 1646
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1647
    char *taskInfoErrorMessage = NULL;
1648

1649
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1650
        return -1;
1651

1652
    if (esxVI_String_AppendValueToList(&propertyNameList,
1653
                                       "runtime.powerState") < 0 ||
1654
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1655
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1656
           priv->parsedUri->autoAnswer) < 0 ||
1657
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1658
        goto cleanup;
1659 1660 1661
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1662 1663
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1664
        goto cleanup;
1665 1666
    }

1667 1668
    if (esxVI_SuspendVM_Task(priv->primary, virtualMachine->obj, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1669
                                    esxVI_Occurrence_RequiredItem,
1670
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1671
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1672
        goto cleanup;
1673 1674 1675
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1676 1677
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not suspend domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
1678
        goto cleanup;
1679 1680
    }

M
Matthias Bolte 已提交
1681 1682
    result = 0;

1683
 cleanup:
1684 1685 1686
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1687
    VIR_FREE(taskInfoErrorMessage);
1688 1689 1690 1691 1692 1693 1694 1695 1696

    return result;
}



static int
esxDomainResume(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1697
    int result = -1;
M
Matthias Bolte 已提交
1698
    esxPrivate *priv = domain->conn->privateData;
1699 1700 1701 1702 1703
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1704
    char *taskInfoErrorMessage = NULL;
1705

1706
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1707
        return -1;
1708

1709
    if (esxVI_String_AppendValueToList(&propertyNameList,
1710
                                       "runtime.powerState") < 0 ||
1711
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1712
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1713
           priv->parsedUri->autoAnswer) < 0 ||
1714
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1715
        goto cleanup;
1716 1717 1718
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended) {
1719
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not suspended"));
M
Matthias Bolte 已提交
1720
        goto cleanup;
1721 1722
    }

1723
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
1724
                             &task) < 0 ||
1725
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1726
                                    esxVI_Occurrence_RequiredItem,
1727
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1728
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1729
        goto cleanup;
1730 1731 1732
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1733 1734
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not resume domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
1735
        goto cleanup;
1736 1737
    }

M
Matthias Bolte 已提交
1738 1739
    result = 0;

1740
 cleanup:
1741 1742 1743
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1744
    VIR_FREE(taskInfoErrorMessage);
1745 1746 1747 1748 1749 1750 1751

    return result;
}



static int
1752
esxDomainShutdownFlags(virDomainPtr domain, unsigned int flags)
1753
{
M
Matthias Bolte 已提交
1754
    int result = -1;
M
Matthias Bolte 已提交
1755
    esxPrivate *priv = domain->conn->privateData;
1756 1757 1758 1759
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1760 1761
    virCheckFlags(0, -1);

1762
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1763
        return -1;
1764

1765
    if (esxVI_String_AppendValueToList(&propertyNameList,
1766
                                       "runtime.powerState") < 0 ||
1767
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1768
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1769
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1770
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1771
        goto cleanup;
1772 1773 1774
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1775 1776
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1777
        goto cleanup;
1778 1779
    }

1780
    if (esxVI_ShutdownGuest(priv->primary, virtualMachine->obj) < 0)
M
Matthias Bolte 已提交
1781
        goto cleanup;
1782

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

1785
 cleanup:
1786 1787 1788 1789 1790 1791 1792
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}


1793 1794 1795 1796 1797 1798
static int
esxDomainShutdown(virDomainPtr domain)
{
    return esxDomainShutdownFlags(domain, 0);
}

1799 1800

static int
E
Eric Blake 已提交
1801
esxDomainReboot(virDomainPtr domain, unsigned int flags)
1802
{
M
Matthias Bolte 已提交
1803
    int result = -1;
M
Matthias Bolte 已提交
1804
    esxPrivate *priv = domain->conn->privateData;
1805 1806 1807 1808
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

E
Eric Blake 已提交
1809 1810
    virCheckFlags(0, -1);

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

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

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1824 1825
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1826
        goto cleanup;
1827 1828
    }

1829
    if (esxVI_RebootGuest(priv->primary, virtualMachine->obj) < 0)
M
Matthias Bolte 已提交
1830
        goto cleanup;
1831

M
Matthias Bolte 已提交
1832 1833
    result = 0;

1834
 cleanup:
1835 1836 1837 1838 1839 1840 1841 1842 1843
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
1844 1845
esxDomainDestroyFlags(virDomainPtr domain,
                      unsigned int flags)
1846
{
M
Matthias Bolte 已提交
1847
    int result = -1;
M
Matthias Bolte 已提交
1848
    esxPrivate *priv = domain->conn->privateData;
1849
    esxVI_Context *ctx = NULL;
1850 1851 1852 1853 1854
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1855
    char *taskInfoErrorMessage = NULL;
1856

1857 1858
    virCheckFlags(0, -1);

1859
    if (priv->vCenter) {
1860 1861 1862 1863 1864
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

1865
    if (esxVI_EnsureSession(ctx) < 0)
M
Matthias Bolte 已提交
1866
        return -1;
1867

1868
    if (esxVI_String_AppendValueToList(&propertyNameList,
1869
                                       "runtime.powerState") < 0 ||
1870
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1871
          (ctx, domain->uuid, propertyNameList, &virtualMachine,
1872
           priv->parsedUri->autoAnswer) < 0 ||
1873
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1874
        goto cleanup;
1875 1876 1877
    }

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

1883
    if (esxVI_PowerOffVM_Task(ctx, virtualMachine->obj, &task) < 0 ||
1884 1885
        esxVI_WaitForTaskCompletion(ctx, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
1886
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1887
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1888
        goto cleanup;
1889 1890 1891
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1892 1893
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not destroy domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
1894
        goto cleanup;
1895 1896
    }

1897
    domain->id = -1;
M
Matthias Bolte 已提交
1898 1899
    result = 0;

1900
 cleanup:
1901 1902 1903
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1904
    VIR_FREE(taskInfoErrorMessage);
1905 1906 1907 1908 1909

    return result;
}


1910 1911 1912 1913 1914 1915
static int
esxDomainDestroy(virDomainPtr dom)
{
    return esxDomainDestroyFlags(dom, 0);
}

1916 1917

static char *
1918
esxDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED)
1919
{
1920
    char *osType;
1921

1922
    ignore_value(VIR_STRDUP(osType, "hvm"));
1923
    return osType;
1924 1925 1926 1927
}



1928
static unsigned long long
1929 1930
esxDomainGetMaxMemory(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1931
    esxPrivate *priv = domain->conn->privateData;
1932 1933 1934 1935 1936
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    unsigned long memoryMB = 0;

1937
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1938
        return 0;
1939

1940
    if (esxVI_String_AppendValueToList(&propertyNameList,
1941
                                       "config.hardware.memoryMB") < 0 ||
1942
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1943
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1944
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
1945
        goto cleanup;
1946 1947
    }

1948
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
1949 1950
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
1951
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1952
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1953
                goto cleanup;
1954 1955 1956
            }

            if (dynamicProperty->val->int32 < 0) {
1957 1958 1959
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Got invalid memory size %d"),
                               dynamicProperty->val->int32);
1960 1961 1962 1963 1964 1965 1966 1967 1968 1969
            } else {
                memoryMB = dynamicProperty->val->int32;
            }

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

1970
 cleanup:
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981
    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 已提交
1982
    int result = -1;
M
Matthias Bolte 已提交
1983
    esxPrivate *priv = domain->conn->privateData;
1984
    esxVI_String *propertyNameList = NULL;
1985
    esxVI_ObjectContent *virtualMachine = NULL;
1986
    esxVI_VirtualMachinePowerState powerState;
1987 1988 1989
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1990
    char *taskInfoErrorMessage = NULL;
1991

1992
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1993
        return -1;
1994

1995 1996 1997 1998
    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "runtime.powerState") < 0 ||
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1999
           priv->parsedUri->autoAnswer) < 0 ||
2000 2001 2002 2003 2004
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2005 2006
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered off"));
2007 2008 2009 2010
        goto cleanup;
    }

    if (esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
2011
        esxVI_Long_Alloc(&spec->memoryMB) < 0) {
M
Matthias Bolte 已提交
2012
        goto cleanup;
2013 2014
    }

2015
    /* max-memory must be a multiple of 4096 kilobyte */
2016
    spec->memoryMB->value =
2017
      VIR_DIV_UP(memory, 4096) * 4; /* Scale from kilobytes to megabytes */
2018

2019
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2020
                              &task) < 0 ||
2021
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2022
                                    esxVI_Occurrence_RequiredItem,
2023
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2024
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2025
        goto cleanup;
2026 2027 2028
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2029 2030 2031
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set max-memory to %lu kilobytes: %s"), memory,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2032
        goto cleanup;
2033 2034
    }

M
Matthias Bolte 已提交
2035 2036
    result = 0;

2037
 cleanup:
2038
    esxVI_String_Free(&propertyNameList);
2039 2040 2041
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2042
    VIR_FREE(taskInfoErrorMessage);
2043 2044 2045 2046 2047 2048 2049 2050 2051

    return result;
}



static int
esxDomainSetMemory(virDomainPtr domain, unsigned long memory)
{
M
Matthias Bolte 已提交
2052
    int result = -1;
M
Matthias Bolte 已提交
2053
    esxPrivate *priv = domain->conn->privateData;
2054 2055 2056 2057
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2058
    char *taskInfoErrorMessage = NULL;
2059

2060
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
2061
        return -1;
2062

2063
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2064
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2065
           priv->parsedUri->autoAnswer) < 0 ||
2066 2067 2068
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0 ||
        esxVI_Long_Alloc(&spec->memoryAllocation->limit) < 0) {
M
Matthias Bolte 已提交
2069
        goto cleanup;
2070 2071 2072
    }

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

2075
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2076
                              &task) < 0 ||
2077
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2078
                                    esxVI_Occurrence_RequiredItem,
2079
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2080
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2081
        goto cleanup;
2082 2083 2084
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2085 2086 2087
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set memory to %lu kilobytes: %s"), memory,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2088
        goto cleanup;
2089 2090
    }

M
Matthias Bolte 已提交
2091 2092
    result = 0;

2093
 cleanup:
2094 2095 2096
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2097
    VIR_FREE(taskInfoErrorMessage);
2098 2099 2100 2101 2102 2103

    return result;
}



2104 2105 2106 2107 2108 2109 2110 2111 2112
/*
 * 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

2113 2114 2115
static int
esxDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info)
{
M
Matthias Bolte 已提交
2116
    int result = -1;
M
Matthias Bolte 已提交
2117
    esxPrivate *priv = domain->conn->privateData;
2118 2119 2120 2121 2122
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int64_t memory_limit = -1;
2123
#if ESX_QUERY_FOR_USED_CPU_TIME
2124 2125 2126 2127 2128 2129 2130
    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;
2131 2132
    esxVI_PerfEntityMetricBase *perfEntityMetricBase = NULL;
    esxVI_PerfEntityMetricBase *perfEntityMetricBaseList = NULL;
2133 2134 2135
    esxVI_PerfEntityMetric *perfEntityMetric = NULL;
    esxVI_PerfMetricIntSeries *perfMetricIntSeries = NULL;
    esxVI_Long *value = NULL;
2136
#endif
2137

2138
    memset(info, 0, sizeof(*info));
M
Matthias Bolte 已提交
2139

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

2143
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2144 2145 2146 2147
                                           "runtime.powerState\0"
                                           "config.hardware.memoryMB\0"
                                           "config.hardware.numCPU\0"
                                           "config.memoryAllocation.limit\0") < 0 ||
2148
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2149
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2150
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2151
        goto cleanup;
2152 2153 2154 2155
    }

    info->state = VIR_DOMAIN_NOSTATE;

2156
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
2157 2158 2159
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.powerState")) {
            if (esxVI_VirtualMachinePowerState_CastFromAnyType
2160
                  (dynamicProperty->val, &powerState) < 0) {
M
Matthias Bolte 已提交
2161
                goto cleanup;
2162 2163
            }

2164 2165
            info->state = esxVI_VirtualMachinePowerState_ConvertToLibvirt
                            (powerState);
2166
        } else if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2167
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2168
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2169
                goto cleanup;
2170 2171 2172 2173
            }

            info->maxMem = dynamicProperty->val->int32 * 1024; /* Scale from megabyte to kilobyte */
        } else if (STREQ(dynamicProperty->name, "config.hardware.numCPU")) {
2174
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2175
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2176
                goto cleanup;
2177 2178 2179 2180 2181
            }

            info->nrVirtCpu = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "config.memoryAllocation.limit")) {
2182
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2183
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
2184
                goto cleanup;
2185 2186 2187 2188
            }

            memory_limit = dynamicProperty->val->int64;

2189
            if (memory_limit > 0)
2190 2191 2192 2193 2194 2195 2196 2197 2198
                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;

2199
#if ESX_QUERY_FOR_USED_CPU_TIME
2200
    /* Verify the cached 'used CPU time' performance counter ID */
2201
    /* FIXME: Currently no host for a vpx:// connection */
2202
    if (priv->host) {
2203
        if (info->state == VIR_DOMAIN_RUNNING && priv->usedCpuTimeCounterId >= 0) {
2204
            if (esxVI_Int_Alloc(&counterId) < 0)
2205
                goto cleanup;
2206

2207
            counterId->value = priv->usedCpuTimeCounterId;
2208

2209
            if (esxVI_Int_AppendToList(&counterIdList, counterId) < 0)
2210
                goto cleanup;
2211

2212 2213 2214 2215
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfo) < 0) {
                goto cleanup;
            }
2216

2217 2218 2219 2220 2221
            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);
2222

2223 2224 2225 2226 2227
                priv->usedCpuTimeCounterId = -1;
            }

            esxVI_Int_Free(&counterIdList);
            esxVI_PerfCounterInfo_Free(&perfCounterInfo);
2228 2229
        }

2230 2231 2232 2233 2234 2235 2236 2237 2238 2239
        /*
         * 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;
            }
2240

2241
            for (perfMetricId = perfMetricIdList; perfMetricId;
2242 2243 2244
                 perfMetricId = perfMetricId->_next) {
                VIR_DEBUG("perfMetricId counterId %d, instance '%s'",
                          perfMetricId->counterId->value, perfMetricId->instance);
2245

2246
                counterId = NULL;
2247

2248 2249 2250 2251 2252
                if (esxVI_Int_DeepCopy(&counterId, perfMetricId->counterId) < 0 ||
                    esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                    goto cleanup;
                }
            }
2253

2254 2255
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfoList) < 0) {
M
Matthias Bolte 已提交
2256
                goto cleanup;
2257 2258
            }

2259
            for (perfCounterInfo = perfCounterInfoList; perfCounterInfo;
2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275
                 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;
                }
2276 2277
            }

2278
            if (priv->usedCpuTimeCounterId < 0)
2279
                VIR_WARN("Could not find 'used CPU time' performance counter");
2280 2281
        }

2282 2283 2284 2285 2286 2287
        /*
         * 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);
2288

2289 2290 2291 2292 2293 2294
            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;
            }
2295

2296 2297 2298 2299 2300 2301 2302 2303 2304 2305
            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;
            }
2306

2307
            for (perfEntityMetricBase = perfEntityMetricBaseList;
2308
                 perfEntityMetricBase;
2309
                 perfEntityMetricBase = perfEntityMetricBase->_next) {
2310
                VIR_DEBUG("perfEntityMetric ...");
2311

2312 2313
                perfEntityMetric =
                  esxVI_PerfEntityMetric_DynamicCast(perfEntityMetricBase);
2314

2315
                if (!perfEntityMetric) {
2316 2317 2318
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("QueryPerf returned object with unexpected type '%s'"),
                                   esxVI_Type_ToString(perfEntityMetricBase->_type));
2319
                    goto cleanup;
2320
                }
2321

2322 2323
                perfMetricIntSeries =
                  esxVI_PerfMetricIntSeries_DynamicCast(perfEntityMetric->value);
2324

2325
                if (!perfMetricIntSeries) {
2326 2327 2328
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("QueryPerf returned object with unexpected type '%s'"),
                                   esxVI_Type_ToString(perfEntityMetric->value->_type));
2329
                    goto cleanup;
2330
                }
2331

2332
                for (; perfMetricIntSeries;
2333
                     perfMetricIntSeries = perfMetricIntSeries->_next) {
2334
                    VIR_DEBUG("perfMetricIntSeries ...");
2335

2336
                    for (value = perfMetricIntSeries->value;
2337
                         value;
2338 2339 2340
                         value = value->_next) {
                        VIR_DEBUG("value %lld", (long long int)value->value);
                    }
2341 2342 2343
                }
            }

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

2346
            /*
E
Eric Blake 已提交
2347
             * FIXME: Cannot map between relative used-cpu-time and absolute
2348 2349 2350
             *        info->cpuTime
             */
        }
2351
    }
2352
#endif
2353

M
Matthias Bolte 已提交
2354 2355
    result = 0;

2356
 cleanup:
2357
#if ESX_QUERY_FOR_USED_CPU_TIME
2358 2359 2360 2361
    /*
     * Remove values owned by data structures to prevent them from being freed
     * by the call to esxVI_PerfQuerySpec_Free().
     */
2362
    if (querySpec) {
2363 2364 2365
        querySpec->entity = NULL;
        querySpec->format = NULL;

2366
        if (querySpec->metricId)
2367 2368
            querySpec->metricId->instance = NULL;
    }
2369
#endif
2370

2371 2372
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2373
#if ESX_QUERY_FOR_USED_CPU_TIME
2374 2375 2376 2377
    esxVI_PerfMetricId_Free(&perfMetricIdList);
    esxVI_Int_Free(&counterIdList);
    esxVI_PerfCounterInfo_Free(&perfCounterInfoList);
    esxVI_PerfQuerySpec_Free(&querySpec);
2378
    esxVI_PerfEntityMetricBase_Free(&perfEntityMetricBaseList);
2379
#endif
2380 2381 2382 2383 2384 2385

    return result;
}



2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399
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);

2400
    if (esxVI_EnsureSession(priv->primary) < 0)
2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418
        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;

2419
 cleanup:
2420 2421 2422 2423 2424 2425 2426 2427
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
}



2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 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
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;
}



2506
static int
2507 2508
esxDomainSetVcpusFlags(virDomainPtr domain, unsigned int nvcpus,
                       unsigned int flags)
2509
{
M
Matthias Bolte 已提交
2510
    int result = -1;
M
Matthias Bolte 已提交
2511
    esxPrivate *priv = domain->conn->privateData;
M
Matthias Bolte 已提交
2512
    int maxVcpus;
2513 2514 2515 2516
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2517
    char *taskInfoErrorMessage = NULL;
2518

2519
    if (flags != VIR_DOMAIN_AFFECT_LIVE) {
2520
        virReportError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
2521 2522 2523
        return -1;
    }

2524
    if (nvcpus < 1) {
2525 2526
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Requested number of virtual CPUs must at least be 1"));
M
Matthias Bolte 已提交
2527
        return -1;
2528 2529
    }

2530
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
2531
        return -1;
2532

M
Matthias Bolte 已提交
2533
    maxVcpus = esxDomainGetMaxVcpus(domain);
2534

2535
    if (maxVcpus < 0)
M
Matthias Bolte 已提交
2536
        return -1;
2537

M
Matthias Bolte 已提交
2538
    if (nvcpus > maxVcpus) {
2539 2540 2541 2542
        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 已提交
2543
        return -1;
2544 2545
    }

2546
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2547
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2548
           priv->parsedUri->autoAnswer) < 0 ||
2549 2550
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Int_Alloc(&spec->numCPUs) < 0) {
M
Matthias Bolte 已提交
2551
        goto cleanup;
2552 2553 2554 2555
    }

    spec->numCPUs->value = nvcpus;

2556
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2557
                              &task) < 0 ||
2558
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2559
                                    esxVI_Occurrence_RequiredItem,
2560
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2561
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2562
        goto cleanup;
2563 2564 2565
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2566 2567 2568
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set number of virtual CPUs to %d: %s"), nvcpus,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2569
        goto cleanup;
2570 2571
    }

M
Matthias Bolte 已提交
2572 2573
    result = 0;

2574
 cleanup:
2575 2576 2577
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2578
    VIR_FREE(taskInfoErrorMessage);
2579 2580 2581 2582 2583

    return result;
}


M
Matthias Bolte 已提交
2584

2585 2586 2587
static int
esxDomainSetVcpus(virDomainPtr domain, unsigned int nvcpus)
{
2588
    return esxDomainSetVcpusFlags(domain, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
2589 2590
}

2591

M
Matthias Bolte 已提交
2592

2593
static int
2594
esxDomainGetVcpusFlags(virDomainPtr domain, unsigned int flags)
2595
{
M
Matthias Bolte 已提交
2596
    esxPrivate *priv = domain->conn->privateData;
2597 2598 2599 2600
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

2601
    if (flags != (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_VCPU_MAXIMUM)) {
2602
        virReportError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
2603 2604 2605
        return -1;
    }

2606
    if (priv->maxVcpus > 0)
M
Matthias Bolte 已提交
2607
        return priv->maxVcpus;
2608

M
Matthias Bolte 已提交
2609 2610
    priv->maxVcpus = -1;

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

2614
    if (esxVI_String_AppendValueToList(&propertyNameList,
2615
                                       "capability.maxSupportedVcpus") < 0 ||
2616 2617
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
2618
        goto cleanup;
2619 2620
    }

2621
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
2622 2623
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "capability.maxSupportedVcpus")) {
2624
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2625
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2626
                goto cleanup;
2627 2628
            }

M
Matthias Bolte 已提交
2629
            priv->maxVcpus = dynamicProperty->val->int32;
2630 2631 2632 2633 2634 2635
            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

2636
 cleanup:
2637 2638 2639
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
2640
    return priv->maxVcpus;
2641 2642
}

M
Matthias Bolte 已提交
2643 2644


2645 2646 2647
static int
esxDomainGetMaxVcpus(virDomainPtr domain)
{
2648
    return esxDomainGetVcpusFlags(domain, (VIR_DOMAIN_AFFECT_LIVE |
2649 2650
                                           VIR_DOMAIN_VCPU_MAXIMUM));
}
2651

M
Matthias Bolte 已提交
2652 2653


2654
static char *
2655
esxDomainGetXMLDesc(virDomainPtr domain, unsigned int flags)
2656
{
M
Matthias Bolte 已提交
2657
    esxPrivate *priv = domain->conn->privateData;
2658 2659
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
2660 2661
    esxVI_VirtualMachinePowerState powerState;
    int id;
2662
    char *vmPathName = NULL;
2663
    char *datastoreName = NULL;
M
Matthias Bolte 已提交
2664
    char *directoryName = NULL;
2665
    char *directoryAndFileName = NULL;
2666
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
2667 2668
    char *url = NULL;
    char *vmx = NULL;
2669
    virVMXContext ctx;
2670
    esxVMX_Data data;
2671 2672 2673
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2674 2675
    /* Flags checked by virDomainDefFormat */

2676
    memset(&data, 0, sizeof(data));
2677

2678
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
2679
        return NULL;
2680

2681 2682 2683
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "config.files.vmPathName\0"
                                           "runtime.powerState\0") < 0 ||
2684
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2685
                                         propertyNameList, &virtualMachine,
2686
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2687 2688
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0 ||
2689 2690
        esxVI_GetStringValue(virtualMachine, "config.files.vmPathName",
                             &vmPathName, esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2691
        goto cleanup;
2692 2693
    }

2694
    if (esxUtil_ParseDatastorePath(vmPathName, &datastoreName, &directoryName,
2695
                                   &directoryAndFileName) < 0) {
M
Matthias Bolte 已提交
2696
        goto cleanup;
2697 2698
    }

2699
    virBufferAsprintf(&buffer, "%s://%s:%d/folder/", priv->parsedUri->transport,
2700
                      domain->conn->uri->server, domain->conn->uri->port);
2701
    virBufferURIEncodeString(&buffer, directoryAndFileName);
2702
    virBufferAddLit(&buffer, "?dcPath=");
2703
    virBufferURIEncodeString(&buffer, priv->primary->datacenterPath);
2704 2705 2706
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

2707
    if (virBufferCheckError(&buffer) < 0)
M
Matthias Bolte 已提交
2708
        goto cleanup;
2709

2710 2711
    url = virBufferContentAndReset(&buffer);

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

2715
    data.ctx = priv->primary;
2716

2717
    if (!directoryName) {
2718
        if (virAsprintf(&data.datastorePathWithoutFileName, "[%s]",
2719
                        datastoreName) < 0)
2720 2721 2722
            goto cleanup;
    } else {
        if (virAsprintf(&data.datastorePathWithoutFileName, "[%s] %s",
2723
                        datastoreName, directoryName) < 0)
2724 2725
            goto cleanup;
    }
2726 2727 2728 2729 2730

    ctx.opaque = &data;
    ctx.parseFileName = esxParseVMXFileName;
    ctx.formatFileName = NULL;
    ctx.autodetectSCSIControllerModel = NULL;
2731
    ctx.datacenterPath = priv->primary->datacenterPath;
2732

2733
    def = virVMXParseConfig(&ctx, priv->xmlopt, priv->caps, vmx);
2734

2735
    if (def) {
2736
        if (powerState != esxVI_VirtualMachinePowerState_PoweredOff)
2737 2738
            def->id = id;

2739
        xml = virDomainDefFormat(def, priv->caps,
2740
                                 virDomainDefFormatConvertXMLFlags(flags));
2741 2742
    }

2743
 cleanup:
2744
    if (!url)
M
Matthias Bolte 已提交
2745 2746
        virBufferFreeAndReset(&buffer);

2747 2748
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2749
    VIR_FREE(datastoreName);
M
Matthias Bolte 已提交
2750
    VIR_FREE(directoryName);
2751
    VIR_FREE(directoryAndFileName);
2752
    VIR_FREE(url);
2753
    VIR_FREE(data.datastorePathWithoutFileName);
2754
    VIR_FREE(vmx);
2755
    virDomainDefFree(def);
2756 2757 2758 2759 2760 2761 2762

    return xml;
}



static char *
2763 2764 2765
esxConnectDomainXMLFromNative(virConnectPtr conn, const char *nativeFormat,
                              const char *nativeConfig,
                              unsigned int flags)
2766
{
M
Matthias Bolte 已提交
2767
    esxPrivate *priv = conn->privateData;
2768
    virVMXContext ctx;
2769
    esxVMX_Data data;
2770 2771 2772
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2773 2774
    virCheckFlags(0, NULL);

2775
    memset(&data, 0, sizeof(data));
2776

2777
    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2778 2779
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Unsupported config format '%s'"), nativeFormat);
2780
        return NULL;
2781 2782
    }

2783
    data.ctx = priv->primary;
2784
    data.datastorePathWithoutFileName = (char *)"[?] ?";
2785 2786 2787 2788 2789

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

2792
    def = virVMXParseConfig(&ctx, priv->xmlopt, priv->caps, nativeConfig);
2793

2794
    if (def)
2795 2796
        xml = virDomainDefFormat(def, priv->caps,
                                 VIR_DOMAIN_DEF_FORMAT_INACTIVE);
2797 2798 2799 2800 2801 2802 2803 2804

    virDomainDefFree(def);

    return xml;
}



M
Matthias Bolte 已提交
2805
static char *
2806 2807 2808
esxConnectDomainXMLToNative(virConnectPtr conn, const char *nativeFormat,
                            const char *domainXml,
                            unsigned int flags)
M
Matthias Bolte 已提交
2809
{
M
Matthias Bolte 已提交
2810
    esxPrivate *priv = conn->privateData;
2811 2812
    int virtualHW_version;
    virVMXContext ctx;
2813
    esxVMX_Data data;
M
Matthias Bolte 已提交
2814 2815 2816
    virDomainDefPtr def = NULL;
    char *vmx = NULL;

E
Eric Blake 已提交
2817 2818
    virCheckFlags(0, NULL);

2819
    memset(&data, 0, sizeof(data));
2820

M
Matthias Bolte 已提交
2821
    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2822 2823
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Unsupported config format '%s'"), nativeFormat);
M
Matthias Bolte 已提交
2824 2825 2826
        return NULL;
    }

2827
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
2828
                          (priv->primary->productLine, priv->primary->productVersion);
2829

2830
    if (virtualHW_version < 0)
2831 2832
        return NULL;

2833
    def = virDomainDefParseString(domainXml, priv->caps, priv->xmlopt,
2834
                                  VIR_DOMAIN_DEF_PARSE_INACTIVE);
M
Matthias Bolte 已提交
2835

2836
    if (!def)
M
Matthias Bolte 已提交
2837 2838
        return NULL;

2839
    data.ctx = priv->primary;
2840
    data.datastorePathWithoutFileName = NULL;
2841 2842 2843 2844 2845

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

2848
    vmx = virVMXFormatConfig(&ctx, priv->xmlopt, def, virtualHW_version);
M
Matthias Bolte 已提交
2849 2850 2851 2852 2853 2854 2855 2856

    virDomainDefFree(def);

    return vmx;
}



2857
static int
2858
esxConnectListDefinedDomains(virConnectPtr conn, char **const names, int maxnames)
2859
{
M
Matthias Bolte 已提交
2860
    bool success = false;
M
Matthias Bolte 已提交
2861
    esxPrivate *priv = conn->privateData;
2862 2863 2864 2865 2866
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;
2867
    size_t i;
2868

2869
    if (maxnames == 0)
2870 2871
        return 0;

2872
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
2873
        return -1;
2874

2875
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2876 2877
                                           "name\0"
                                           "runtime.powerState\0") < 0 ||
2878 2879
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2880
        goto cleanup;
2881 2882
    }

2883
    for (virtualMachine = virtualMachineList; virtualMachine;
2884
         virtualMachine = virtualMachine->_next) {
2885
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
2886
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
2887
            goto cleanup;
2888 2889
        }

2890
        if (powerState == esxVI_VirtualMachinePowerState_PoweredOn)
2891 2892
            continue;

2893
        names[count] = NULL;
2894

2895 2896 2897
        if (esxVI_GetVirtualMachineIdentity(virtualMachine, NULL, &names[count],
                                            NULL) < 0) {
            goto cleanup;
2898 2899
        }

2900 2901
        ++count;

2902
        if (count >= maxnames)
2903 2904 2905
            break;
    }

M
Matthias Bolte 已提交
2906
    success = true;
2907

2908
 cleanup:
M
Matthias Bolte 已提交
2909
    if (! success) {
2910
        for (i = 0; i < count; ++i)
M
Matthias Bolte 已提交
2911
            VIR_FREE(names[i]);
2912

M
Matthias Bolte 已提交
2913
        count = -1;
2914 2915
    }

M
Matthias Bolte 已提交
2916 2917
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
2918

M
Matthias Bolte 已提交
2919
    return count;
2920 2921 2922 2923 2924
}



static int
2925
esxConnectNumOfDefinedDomains(virConnectPtr conn)
2926
{
M
Matthias Bolte 已提交
2927
    esxPrivate *priv = conn->privateData;
2928

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

2932
    return esxVI_LookupNumberOfDomainsByPowerState
2933
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, true);
2934 2935 2936 2937 2938
}



static int
2939
esxDomainCreateWithFlags(virDomainPtr domain, unsigned int flags)
2940
{
M
Matthias Bolte 已提交
2941
    int result = -1;
M
Matthias Bolte 已提交
2942
    esxPrivate *priv = domain->conn->privateData;
2943 2944 2945
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
2946
    int id = -1;
2947 2948
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2949
    char *taskInfoErrorMessage = NULL;
2950

2951 2952
    virCheckFlags(0, -1);

2953
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
2954
        return -1;
2955

2956
    if (esxVI_String_AppendValueToList(&propertyNameList,
2957
                                       "runtime.powerState") < 0 ||
2958
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2959
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
2960
           priv->parsedUri->autoAnswer) < 0 ||
2961 2962
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0) {
M
Matthias Bolte 已提交
2963
        goto cleanup;
2964 2965 2966
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2967 2968
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered off"));
M
Matthias Bolte 已提交
2969
        goto cleanup;
2970 2971
    }

2972
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
2973
                             &task) < 0 ||
2974
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2975
                                    esxVI_Occurrence_RequiredItem,
2976
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2977
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2978
        goto cleanup;
2979 2980 2981
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2982 2983
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not start domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2984
        goto cleanup;
2985 2986
    }

2987
    domain->id = id;
M
Matthias Bolte 已提交
2988 2989
    result = 0;

2990
 cleanup:
2991 2992 2993
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
2994
    VIR_FREE(taskInfoErrorMessage);
2995 2996 2997 2998

    return result;
}

2999 3000


3001 3002 3003 3004 3005
static int
esxDomainCreate(virDomainPtr domain)
{
    return esxDomainCreateWithFlags(domain, 0);
}
3006

3007 3008


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

3037 3038 3039
    virCheckFlags(VIR_DOMAIN_DEFINE_VALIDATE, NULL);

    if (flags & VIR_DOMAIN_DEFINE_VALIDATE)
3040
        parse_flags |= VIR_DOMAIN_DEF_PARSE_VALIDATE_SCHEMA;
3041

3042
    memset(&data, 0, sizeof(data));
3043

3044
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
3045
        return NULL;
M
Matthias Bolte 已提交
3046 3047

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

3051
    if (!def)
M
Matthias Bolte 已提交
3052
        return NULL;
M
Matthias Bolte 已提交
3053 3054

    /* Check if an existing domain should be edited */
3055
    if (esxVI_LookupVirtualMachineByUuid(priv->primary, def->uuid, NULL,
M
Matthias Bolte 已提交
3056
                                         &virtualMachine,
M
Matthias Bolte 已提交
3057
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
3058
        goto cleanup;
M
Matthias Bolte 已提交
3059 3060
    }

3061
    if (!virtualMachine &&
3062 3063 3064 3065 3066 3067
        esxVI_LookupVirtualMachineByName(priv->primary, def->name, NULL,
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
    }

3068
    if (virtualMachine) {
M
Matthias Bolte 已提交
3069
        /* FIXME */
3070 3071 3072
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Domain already exists, editing existing domains is not "
                         "supported yet"));
M
Matthias Bolte 已提交
3073
        goto cleanup;
M
Matthias Bolte 已提交
3074 3075 3076
    }

    /* Build VMX from domain XML */
3077
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
3078
                          (priv->primary->productLine, priv->primary->productVersion);
3079

3080
    if (virtualHW_version < 0)
3081 3082
        goto cleanup;

3083
    data.ctx = priv->primary;
3084
    data.datastorePathWithoutFileName = NULL;
3085 3086 3087 3088 3089

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

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

3094
    if (!vmx)
M
Matthias Bolte 已提交
3095
        goto cleanup;
M
Matthias Bolte 已提交
3096

3097 3098 3099
    /*
     * 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 已提交
3100
     * first disk, because it may be CDROM disk and ISO images are normally not
3101 3102 3103
     * 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 已提交
3104
    if (def->ndisks < 1) {
3105 3106 3107
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Domain XML doesn't contain any disks, cannot deduce "
                         "datastore and path for VMX file"));
M
Matthias Bolte 已提交
3108
        goto cleanup;
3109 3110 3111 3112
    }

    for (i = 0; i < def->ndisks; ++i) {
        if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK &&
E
Eric Blake 已提交
3113
            virDomainDiskGetType(def->disks[i]) == VIR_STORAGE_TYPE_FILE) {
3114 3115 3116 3117 3118
            disk = def->disks[i];
            break;
        }
    }

3119
    if (!disk) {
3120 3121 3122
        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 已提交
3123
        goto cleanup;
M
Matthias Bolte 已提交
3124 3125
    }

3126 3127
    src = virDomainDiskGetSource(disk);
    if (!src) {
3128 3129 3130
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("First file-based harddisk has no source, cannot deduce "
                         "datastore and path for VMX file"));
M
Matthias Bolte 已提交
3131
        goto cleanup;
M
Matthias Bolte 已提交
3132 3133
    }

3134
    if (esxUtil_ParseDatastorePath(src, &datastoreName, &directoryName,
3135
                                   NULL) < 0) {
M
Matthias Bolte 已提交
3136
        goto cleanup;
M
Matthias Bolte 已提交
3137 3138
    }

3139
    if (! virFileHasSuffix(src, ".vmdk")) {
3140 3141
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Expecting source '%s' of first file-based harddisk to "
3142
                         "be a VMDK image"), src);
M
Matthias Bolte 已提交
3143
        goto cleanup;
M
Matthias Bolte 已提交
3144 3145
    }

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

3149
    if (directoryName) {
M
Matthias Bolte 已提交
3150 3151 3152 3153
        virBufferURIEncodeString(&buffer, directoryName);
        virBufferAddChar(&buffer, '/');
    }

3154 3155
    escapedName = esxUtil_EscapeDatastoreItem(def->name);

3156
    if (!escapedName)
3157 3158 3159
        goto cleanup;

    virBufferURIEncodeString(&buffer, escapedName);
M
Matthias Bolte 已提交
3160
    virBufferAddLit(&buffer, ".vmx?dcPath=");
3161
    virBufferURIEncodeString(&buffer, priv->primary->datacenterPath);
M
Matthias Bolte 已提交
3162 3163 3164
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

3165
    if (virBufferCheckError(&buffer) < 0)
M
Matthias Bolte 已提交
3166
        goto cleanup;
M
Matthias Bolte 已提交
3167 3168 3169

    url = virBufferContentAndReset(&buffer);

3170 3171 3172 3173 3174 3175
    /* Check, if VMX file already exists */
    /* FIXME */

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

3176
    if (esxVI_CURL_Upload(priv->primary->curl, url, vmx) < 0)
3177 3178 3179
        goto cleanup;

    /* Register the domain */
3180
    if (directoryName) {
M
Matthias Bolte 已提交
3181
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s/%s.vmx", datastoreName,
3182
                        directoryName, escapedName) < 0)
M
Matthias Bolte 已提交
3183
            goto cleanup;
M
Matthias Bolte 已提交
3184 3185
    } else {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s.vmx", datastoreName,
3186
                        escapedName) < 0)
M
Matthias Bolte 已提交
3187
            goto cleanup;
M
Matthias Bolte 已提交
3188 3189
    }

3190
    if (esxVI_RegisterVM_Task(priv->primary, priv->primary->datacenter->vmFolder,
M
Matthias Bolte 已提交
3191
                              datastoreRelatedPath, NULL, esxVI_Boolean_False,
3192 3193 3194 3195
                              priv->primary->computeResource->resourcePool,
                              priv->primary->hostSystem->_reference,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, def->uuid,
3196
                                    esxVI_Occurrence_OptionalItem,
3197
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3198
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3199
        goto cleanup;
M
Matthias Bolte 已提交
3200 3201 3202
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3203 3204
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not define domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3205
        goto cleanup;
M
Matthias Bolte 已提交
3206 3207 3208 3209
    }

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

3210
    if (domain)
M
Matthias Bolte 已提交
3211 3212 3213 3214
        domain->id = -1;

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

3215
 cleanup:
3216
    if (!url)
M
Matthias Bolte 已提交
3217 3218
        virBufferFreeAndReset(&buffer);

M
Matthias Bolte 已提交
3219 3220 3221 3222
    virDomainDefFree(def);
    VIR_FREE(vmx);
    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
3223
    VIR_FREE(escapedName);
M
Matthias Bolte 已提交
3224 3225 3226 3227 3228 3229 3230
    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);
3231
    VIR_FREE(taskInfoErrorMessage);
M
Matthias Bolte 已提交
3232 3233 3234 3235

    return domain;
}

3236 3237 3238 3239 3240
static virDomainPtr
esxDomainDefineXML(virConnectPtr conn, const char *xml)
{
    return esxDomainDefineXMLFlags(conn, xml, 0);
}
M
Matthias Bolte 已提交
3241

3242
static int
3243 3244
esxDomainUndefineFlags(virDomainPtr domain,
                       unsigned int flags)
3245
{
M
Matthias Bolte 已提交
3246
    int result = -1;
M
Matthias Bolte 已提交
3247
    esxPrivate *priv = domain->conn->privateData;
3248
    esxVI_Context *ctx = NULL;
3249 3250 3251 3252
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

3253 3254 3255 3256
    /* 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);
3257

3258
    if (priv->vCenter) {
3259 3260 3261 3262 3263
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

3264
    if (esxVI_EnsureSession(ctx) < 0)
M
Matthias Bolte 已提交
3265
        return -1;
3266

3267
    if (esxVI_String_AppendValueToList(&propertyNameList,
3268
                                       "runtime.powerState") < 0 ||
3269 3270
        esxVI_LookupVirtualMachineByUuid(ctx, domain->uuid, propertyNameList,
                                         &virtualMachine,
M
Matthias Bolte 已提交
3271
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3272
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
3273
        goto cleanup;
3274 3275 3276 3277
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended &&
        powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
3278 3279
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not suspended or powered off"));
M
Matthias Bolte 已提交
3280
        goto cleanup;
3281 3282
    }

3283
    if (esxVI_UnregisterVM(ctx, virtualMachine->obj) < 0)
M
Matthias Bolte 已提交
3284
        goto cleanup;
3285

M
Matthias Bolte 已提交
3286 3287
    result = 0;

3288
 cleanup:
3289 3290 3291 3292 3293 3294 3295
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}


3296 3297 3298 3299 3300
static int
esxDomainUndefine(virDomainPtr domain)
{
    return esxDomainUndefineFlags(domain, 0);
}
3301

3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314
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;

3315
    if (esxVI_EnsureSession(priv->primary) < 0)
3316 3317 3318
        return -1;

    /* Check general autostart config */
3319
    if (esxVI_LookupAutoStartDefaults(priv->primary, &defaults) < 0)
3320 3321 3322 3323 3324 3325 3326 3327 3328
        goto cleanup;

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

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

3332
    if (!powerInfoList) {
3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343
        /* 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;
    }

3344
    for (powerInfo = powerInfoList; powerInfo;
3345 3346
         powerInfo = powerInfo->_next) {
        if (STREQ(powerInfo->key->value, virtualMachine->obj->value)) {
3347
            if (STRCASEEQ(powerInfo->startAction, "powerOn"))
3348 3349 3350 3351 3352 3353 3354 3355
                *autostart = 1;

            break;
        }
    }

    result = 0;

3356
 cleanup:
3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378
    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;

3379
    if (esxVI_EnsureSession(priv->primary) < 0)
3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395
        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.
         */
3396
        if (esxVI_LookupAutoStartDefaults(priv->primary, &defaults) < 0)
3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410
            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;
            }

3411
            for (powerInfo = powerInfoList; powerInfo;
3412 3413
                 powerInfo = powerInfo->_next) {
                if (STRNEQ(powerInfo->key->value, virtualMachine->obj->value)) {
3414 3415 3416
                    virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                                   _("Cannot enable general autostart option "
                                     "without affecting other domains"));
3417 3418 3419 3420 3421
                    goto cleanup;
                }
            }

            /* Enable autostart in general */
3422
            if (esxVI_AutoStartDefaults_Alloc(&spec->defaults) < 0)
3423 3424 3425 3426 3427 3428 3429 3430 3431
                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 ||
3432
        esxVI_Int_Alloc(&newPowerInfo->stopDelay) < 0) {
3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443
        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";

3444 3445 3446 3447 3448
    if (esxVI_AutoStartPowerInfo_AppendToList(&spec->powerInfo,
                                              newPowerInfo) < 0) {
        goto cleanup;
    }

3449
    newPowerInfo = NULL;
3450

3451 3452 3453 3454 3455 3456 3457 3458 3459
    if (esxVI_ReconfigureAutostart
          (priv->primary,
           priv->primary->hostSystem->configManager->autoStartManager,
           spec) < 0) {
        goto cleanup;
    }

    result = 0;

3460
 cleanup:
3461
    if (newPowerInfo) {
3462 3463 3464 3465 3466 3467 3468 3469 3470 3471
        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);

3472
    esxVI_AutoStartPowerInfo_Free(&newPowerInfo);
3473

3474 3475 3476 3477 3478
    return result;
}



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

3514
    if (VIR_STRDUP(type, "allocation") < 0)
3515
        return NULL;
3516

3517
    if (nparams)
3518
        *nparams = 3; /* reservation, limit, shares */
3519 3520 3521 3522 3523 3524 3525

    return type;
}



static int
3526 3527 3528
esxDomainGetSchedulerParametersFlags(virDomainPtr domain,
                                     virTypedParameterPtr params, int *nparams,
                                     unsigned int flags)
3529
{
M
Matthias Bolte 已提交
3530
    int result = -1;
M
Matthias Bolte 已提交
3531
    esxPrivate *priv = domain->conn->privateData;
3532 3533 3534 3535 3536
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    unsigned int mask = 0;
3537
    size_t i = 0;
3538

3539 3540
    virCheckFlags(0, -1);

3541
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
3542
        return -1;
3543

3544
    if (esxVI_String_AppendValueListToList(&propertyNameList,
3545 3546 3547
                                           "config.cpuAllocation.reservation\0"
                                           "config.cpuAllocation.limit\0"
                                           "config.cpuAllocation.shares\0") < 0 ||
3548
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
3549
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3550
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3551
        goto cleanup;
3552 3553 3554
    }

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

            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:
3614 3615 3616
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Shares level has unknown value %d"),
                               (int)sharesInfo->level);
3617
                esxVI_SharesInfo_Free(&sharesInfo);
M
Matthias Bolte 已提交
3618
                goto cleanup;
3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630
            }

            esxVI_SharesInfo_Free(&sharesInfo);

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

    *nparams = i;
M
Matthias Bolte 已提交
3631
    result = 0;
3632

3633
 cleanup:
3634 3635 3636 3637 3638 3639
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
}

3640 3641 3642 3643 3644 3645
static int
esxDomainGetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int *nparams)
{
    return esxDomainGetSchedulerParametersFlags(domain, params, nparams, 0);
}
3646 3647 3648


static int
3649 3650 3651
esxDomainSetSchedulerParametersFlags(virDomainPtr domain,
                                     virTypedParameterPtr params, int nparams,
                                     unsigned int flags)
3652
{
M
Matthias Bolte 已提交
3653
    int result = -1;
M
Matthias Bolte 已提交
3654
    esxPrivate *priv = domain->conn->privateData;
3655 3656 3657 3658 3659
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3660
    char *taskInfoErrorMessage = NULL;
3661
    size_t i;
3662

3663
    virCheckFlags(0, -1);
3664 3665 3666 3667 3668 3669 3670 3671
    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)
3672
        return -1;
3673

3674
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
3675
        return -1;
3676

3677
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3678
          (priv->primary, domain->uuid, NULL, &virtualMachine,
3679
           priv->parsedUri->autoAnswer) < 0 ||
3680 3681
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->cpuAllocation) < 0) {
M
Matthias Bolte 已提交
3682
        goto cleanup;
3683 3684 3685
    }

    for (i = 0; i < nparams; ++i) {
3686
        if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_RESERVATION)) {
3687
            if (esxVI_Long_Alloc(&spec->cpuAllocation->reservation) < 0)
M
Matthias Bolte 已提交
3688
                goto cleanup;
3689 3690

            if (params[i].value.l < 0) {
3691 3692 3693
                virReportError(VIR_ERR_INVALID_ARG,
                               _("Could not set reservation to %lld MHz, expecting "
                                 "positive value"), params[i].value.l);
M
Matthias Bolte 已提交
3694
                goto cleanup;
3695 3696 3697
            }

            spec->cpuAllocation->reservation->value = params[i].value.l;
3698
        } else if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_LIMIT)) {
3699
            if (esxVI_Long_Alloc(&spec->cpuAllocation->limit) < 0)
M
Matthias Bolte 已提交
3700
                goto cleanup;
3701 3702

            if (params[i].value.l < -1) {
3703 3704 3705 3706
                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 已提交
3707
                goto cleanup;
3708 3709 3710
            }

            spec->cpuAllocation->limit->value = params[i].value.l;
3711
        } else if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_SHARES)) {
3712 3713
            if (esxVI_SharesInfo_Alloc(&sharesInfo) < 0 ||
                esxVI_Int_Alloc(&sharesInfo->shares) < 0) {
M
Matthias Bolte 已提交
3714
                goto cleanup;
3715 3716 3717
            }

            spec->cpuAllocation->shares = sharesInfo;
3718
            sharesInfo = NULL;
3719

3720
            if (params[i].value.i >= 0) {
3721
                spec->cpuAllocation->shares->level = esxVI_SharesLevel_Custom;
3722
                spec->cpuAllocation->shares->shares->value = params[i].value.i;
3723
            } else {
3724
                switch (params[i].value.i) {
3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742
                  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:
3743 3744 3745 3746
                    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 已提交
3747
                    goto cleanup;
3748 3749 3750 3751 3752
                }
            }
        }
    }

3753
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
3754
                              &task) < 0 ||
3755
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3756
                                    esxVI_Occurrence_RequiredItem,
3757
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3758
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3759
        goto cleanup;
3760 3761 3762
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3763 3764 3765
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not change scheduler parameters: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3766
        goto cleanup;
3767 3768
    }

M
Matthias Bolte 已提交
3769 3770
    result = 0;

3771
 cleanup:
3772
    esxVI_SharesInfo_Free(&sharesInfo);
3773 3774 3775
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
3776
    VIR_FREE(taskInfoErrorMessage);
3777 3778 3779 3780

    return result;
}

3781 3782 3783 3784 3785 3786
static int
esxDomainSetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int nparams)
{
    return esxDomainSetSchedulerParametersFlags(domain, params, nparams, 0);
}
3787

E
Eric Blake 已提交
3788 3789 3790 3791 3792 3793
/* 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)
3794 3795 3796 3797 3798

static int
esxDomainMigratePrepare(virConnectPtr dconn,
                        char **cookie ATTRIBUTE_UNUSED,
                        int *cookielen ATTRIBUTE_UNUSED,
3799 3800
                        const char *uri_in ATTRIBUTE_UNUSED,
                        char **uri_out,
E
Eric Blake 已提交
3801
                        unsigned long flags,
3802 3803 3804
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
3805
    esxPrivate *priv = dconn->privateData;
3806

E
Eric Blake 已提交
3807 3808
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

3809
    if (!uri_in) {
3810 3811 3812
        if (virAsprintf(uri_out, "vpxmigr://%s/%s/%s",
                        priv->vCenter->ipAddress,
                        priv->vCenter->computeResource->resourcePool->value,
3813
                        priv->vCenter->hostSystem->_reference->value) < 0)
3814
            return -1;
3815 3816
    }

3817
    return 0;
3818 3819 3820 3821 3822 3823 3824 3825 3826
}



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

E
Eric Blake 已提交
3845 3846
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

3847
    if (!priv->vCenter) {
3848 3849
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration not possible without a vCenter"));
M
Matthias Bolte 已提交
3850
        return -1;
3851 3852
    }

3853
    if (dname) {
3854 3855
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Renaming domains on migration not supported"));
M
Matthias Bolte 已提交
3856
        return -1;
3857 3858
    }

3859
    if (esxVI_EnsureSession(priv->vCenter) < 0)
M
Matthias Bolte 已提交
3860
        return -1;
3861

3862
    /* Parse migration URI */
3863
    if (!(parsedUri = virURIParse(uri)))
M
Matthias Bolte 已提交
3864
        return -1;
3865

3866
    if (!parsedUri->scheme || STRCASENEQ(parsedUri->scheme, "vpxmigr")) {
3867 3868
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Only vpxmigr:// migration URIs are supported"));
M
Matthias Bolte 已提交
3869
        goto cleanup;
3870 3871
    }

3872
    if (STRCASENEQ(priv->vCenter->ipAddress, parsedUri->server)) {
3873 3874 3875
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration source and destination have to refer to "
                         "the same vCenter"));
3876 3877 3878 3879 3880 3881
        goto cleanup;
    }

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

3882
    if (!path_resourcePool || !path_hostSystem) {
3883 3884
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration URI has to specify resource pool and host system"));
M
Matthias Bolte 已提交
3885
        goto cleanup;
3886 3887
    }

3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900
    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,
3901
           priv->parsedUri->autoAnswer) < 0) {
M
Matthias Bolte 已提交
3902
        goto cleanup;
3903 3904 3905
    }

    /* Validate the purposed migration */
3906
    if (esxVI_ValidateMigration(priv->vCenter, virtualMachine->obj,
3907 3908
                                esxVI_VirtualMachinePowerState_Undefined, NULL,
                                &resourcePool, &hostSystem, &eventList) < 0) {
M
Matthias Bolte 已提交
3909
        goto cleanup;
3910 3911
    }

3912
    if (eventList) {
3913 3914 3915 3916
        /*
         * FIXME: Need to report the complete list of events. Limit reporting
         *        to the first event for now.
         */
3917
        if (eventList->fullFormattedMessage) {
3918 3919 3920
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not migrate domain, validation reported a "
                             "problem: %s"), eventList->fullFormattedMessage);
3921
        } else {
3922 3923 3924
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Could not migrate domain, validation reported a "
                             "problem"));
3925 3926
        }

M
Matthias Bolte 已提交
3927
        goto cleanup;
3928 3929 3930
    }

    /* Perform the purposed migration */
3931 3932
    if (esxVI_MigrateVM_Task(priv->vCenter, virtualMachine->obj,
                             &resourcePool, &hostSystem,
3933 3934 3935
                             esxVI_VirtualMachineMovePriority_DefaultPriority,
                             esxVI_VirtualMachinePowerState_Undefined,
                             &task) < 0 ||
3936
        esxVI_WaitForTaskCompletion(priv->vCenter, task, domain->uuid,
3937
                                    esxVI_Occurrence_RequiredItem,
3938
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3939
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3940
        goto cleanup;
3941 3942 3943
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3944 3945 3946 3947
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not migrate domain, migration task finished with "
                         "an error: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3948
        goto cleanup;
3949 3950
    }

M
Matthias Bolte 已提交
3951 3952
    result = 0;

3953
 cleanup:
3954
    virURIFree(parsedUri);
3955 3956 3957
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Event_Free(&eventList);
    esxVI_ManagedObjectReference_Free(&task);
3958
    VIR_FREE(taskInfoErrorMessage);
3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969

    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 已提交
3970
                       unsigned long flags)
3971
{
E
Eric Blake 已提交
3972 3973
    virCheckFlags(ESX_MIGRATION_FLAGS, NULL);

3974 3975 3976 3977 3978
    return esxDomainLookupByName(dconn, dname);
}



M
Matthias Bolte 已提交
3979 3980 3981 3982
static unsigned long long
esxNodeGetFreeMemory(virConnectPtr conn)
{
    unsigned long long result = 0;
3983
    unsigned long long usageBytes = 0;
M
Matthias Bolte 已提交
3984
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
3985
    esxVI_String *propertyNameList = NULL;
3986 3987 3988
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_Int *memoryUsage = NULL;
    esxVI_Long *memorySize = NULL;
M
Matthias Bolte 已提交
3989

3990
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
3991
        return 0;
M
Matthias Bolte 已提交
3992

3993 3994 3995 3996 3997 3998 3999 4000 4001 4002
    /* 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 已提交
4003
        goto cleanup;
M
Matthias Bolte 已提交
4004 4005
    }

4006 4007
    usageBytes = (unsigned long long) (memoryUsage->value) * 1048576;
    result = memorySize->value - usageBytes;
M
Matthias Bolte 已提交
4008

4009
 cleanup:
M
Matthias Bolte 已提交
4010
    esxVI_String_Free(&propertyNameList);
4011 4012 4013
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_Int_Free(&memoryUsage);
    esxVI_Long_Free(&memorySize);
M
Matthias Bolte 已提交
4014 4015 4016 4017 4018 4019

    return result;
}



4020
static int
4021
esxConnectIsEncrypted(virConnectPtr conn)
4022
{
M
Matthias Bolte 已提交
4023
    esxPrivate *priv = conn->privateData;
4024

4025
    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
4026 4027 4028 4029 4030 4031 4032 4033 4034
        return 1;
    } else {
        return 0;
    }
}



static int
4035
esxConnectIsSecure(virConnectPtr conn)
4036
{
M
Matthias Bolte 已提交
4037
    esxPrivate *priv = conn->privateData;
4038

4039
    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
4040 4041 4042 4043 4044 4045 4046 4047
        return 1;
    } else {
        return 0;
    }
}



4048
static int
4049
esxConnectIsAlive(virConnectPtr conn)
4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064
{
    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;
}



4065 4066 4067
static int
esxDomainIsActive(virDomainPtr domain)
{
M
Matthias Bolte 已提交
4068
    int result = -1;
M
Matthias Bolte 已提交
4069
    esxPrivate *priv = domain->conn->privateData;
4070 4071 4072 4073
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

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

4077
    if (esxVI_String_AppendValueToList(&propertyNameList,
4078
                                       "runtime.powerState") < 0 ||
4079
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
4080
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
4081
                                         esxVI_Occurrence_RequiredItem) < 0 ||
4082
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
4083
        goto cleanup;
4084 4085 4086 4087 4088 4089 4090 4091
    }

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

4092
 cleanup:
4093 4094 4095 4096 4097 4098 4099 4100 4101
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
4102
esxDomainIsPersistent(virDomainPtr domain)
4103
{
4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119
    /* 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;

4120
 cleanup:
4121 4122 4123
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
4124 4125
}

M
Matthias Bolte 已提交
4126 4127


4128 4129 4130
static int
esxDomainIsUpdated(virDomainPtr domain ATTRIBUTE_UNUSED)
{
4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146
    /* 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;

4147
 cleanup:
4148 4149 4150
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
4151
}
4152

M
Matthias Bolte 已提交
4153 4154


4155 4156
static virDomainSnapshotPtr
esxDomainSnapshotCreateXML(virDomainPtr domain, const char *xmlDesc,
4157
                           unsigned int flags)
4158 4159 4160 4161 4162 4163 4164 4165
{
    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;
4166
    char *taskInfoErrorMessage = NULL;
4167
    virDomainSnapshotPtr snapshot = NULL;
4168 4169
    bool diskOnly = (flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY) != 0;
    bool quiesce = (flags & VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE) != 0;
4170

4171 4172 4173 4174 4175
    /* 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);
4176

4177
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4178
        return NULL;
4179

4180
    def = virDomainSnapshotDefParseString(xmlDesc, priv->caps,
4181
                                          priv->xmlopt, 0);
4182

4183
    if (!def)
M
Matthias Bolte 已提交
4184
        return NULL;
4185

4186
    if (def->ndisks) {
4187 4188
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("disk snapshots not supported yet"));
4189 4190 4191
        return NULL;
    }

4192
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
4193
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4194
           priv->parsedUri->autoAnswer) < 0 ||
4195
        esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4196 4197
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, def->name,
4198
                                    &snapshotTree, NULL,
4199
                                    esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4200
        goto cleanup;
4201 4202
    }

4203
    if (snapshotTree) {
4204 4205
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Snapshot '%s' already exists"), def->name);
M
Matthias Bolte 已提交
4206
        goto cleanup;
4207 4208
    }

4209
    if (esxVI_CreateSnapshot_Task(priv->primary, virtualMachine->obj,
4210
                                  def->name, def->description,
4211 4212 4213
                                  diskOnly ? esxVI_Boolean_False : esxVI_Boolean_True,
                                  quiesce ? esxVI_Boolean_True : esxVI_Boolean_False,
                                  &task) < 0 ||
4214
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
4215
                                    esxVI_Occurrence_RequiredItem,
4216
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4217
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4218
        goto cleanup;
4219 4220 4221
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4222 4223
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not create snapshot: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4224
        goto cleanup;
4225 4226 4227 4228
    }

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

4229
 cleanup:
4230 4231 4232 4233
    virDomainSnapshotDefFree(def);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4234
    VIR_FREE(taskInfoErrorMessage);
4235 4236 4237 4238 4239 4240 4241

    return snapshot;
}



static char *
4242 4243
esxDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                            unsigned int flags)
4244 4245 4246 4247 4248 4249 4250 4251 4252
{
    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;

4253 4254
    virCheckFlags(0, NULL);

4255
    memset(&def, 0, sizeof(def));
4256

4257
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4258
        return NULL;
4259

4260
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4261 4262 4263 4264
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4265
        goto cleanup;
4266 4267 4268 4269
    }

    def.name = snapshot->name;
    def.description = snapshotTree->description;
4270
    def.parent = snapshotTreeParent ? snapshotTreeParent->name : NULL;
4271 4272 4273

    if (esxVI_DateTime_ConvertToCalendarTime(snapshotTree->createTime,
                                             &def.creationTime) < 0) {
M
Matthias Bolte 已提交
4274
        goto cleanup;
4275 4276 4277 4278 4279 4280 4281
    }

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

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

4282
    xml = virDomainSnapshotDefFormat(uuid_string, &def, priv->caps,
4283 4284
                                     virDomainDefFormatConvertXMLFlags(flags),
                                     0);
4285

4286
 cleanup:
4287 4288 4289 4290 4291 4292 4293 4294
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return xml;
}



static int
4295
esxDomainSnapshotNum(virDomainPtr domain, unsigned int flags)
4296
{
M
Matthias Bolte 已提交
4297
    int count;
4298 4299
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
4300
    bool recurse;
4301
    bool leaves;
4302

4303
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
4304 4305
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4306 4307

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) == 0;
4308
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4309

4310
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4311
        return -1;
4312

4313 4314 4315 4316
    /* ESX snapshots do not require libvirt to maintain any metadata.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA)
        return 0;

4317
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4318
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4319
        return -1;
4320 4321
    }

4322 4323
    count = esxVI_GetNumberOfSnapshotTrees(rootSnapshotTreeList, recurse,
                                           leaves);
4324 4325 4326

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

M
Matthias Bolte 已提交
4327
    return count;
4328 4329 4330 4331 4332 4333
}



static int
esxDomainSnapshotListNames(virDomainPtr domain, char **names, int nameslen,
4334
                           unsigned int flags)
4335
{
M
Matthias Bolte 已提交
4336
    int result;
4337 4338
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
4339
    bool recurse;
4340
    bool leaves;
4341 4342

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
4343 4344
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4345

4346
    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) == 0;
4347
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4348

4349
    if (!names || nameslen < 0) {
4350
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
4351 4352 4353
        return -1;
    }

4354
    if (nameslen == 0 || (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA))
4355 4356
        return 0;

4357
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4358
        return -1;
4359

4360
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4361
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4362
        return -1;
4363 4364
    }

4365
    result = esxVI_GetSnapshotTreeNames(rootSnapshotTreeList, names, nameslen,
4366
                                        recurse, leaves);
4367 4368 4369 4370 4371 4372 4373 4374

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



4375 4376 4377 4378 4379 4380 4381 4382
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;
4383
    bool leaves;
4384 4385

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
4386 4387
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4388 4389

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) != 0;
4390
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4391

4392
    if (esxVI_EnsureSession(priv->primary) < 0)
4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409
        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,
4410
                                           recurse, leaves);
4411

4412
 cleanup:
4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429
    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;
4430
    bool leaves;
4431 4432

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

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

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

4444
    if (nameslen == 0)
4445 4446
        return 0;

4447
    if (esxVI_EnsureSession(priv->primary) < 0)
4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464
        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,
4465
                                        names, nameslen, recurse, leaves);
4466

4467
 cleanup:
4468 4469 4470 4471 4472 4473 4474
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



4475 4476
static virDomainSnapshotPtr
esxDomainSnapshotLookupByName(virDomainPtr domain, const char *name,
4477
                              unsigned int flags)
4478 4479 4480 4481 4482 4483
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    virDomainSnapshotPtr snapshot = NULL;

4484 4485
    virCheckFlags(0, NULL);

4486
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4487
        return NULL;
4488

4489
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4490 4491
                                         &rootSnapshotTreeList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotTreeList, name, &snapshotTree,
4492
                                    NULL,
4493 4494 4495 4496 4497 4498
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    snapshot = virGetDomainSnapshot(domain, name);

4499
 cleanup:
4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return snapshot;
}



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

4513
    virCheckFlags(0, -1);
4514

4515
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4516
        return -1;
4517

4518
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4519 4520
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4521
        return -1;
4522 4523
    }

4524
    if (currentSnapshotTree) {
M
Matthias Bolte 已提交
4525 4526
        esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);
        return 1;
4527 4528
    }

M
Matthias Bolte 已提交
4529
    return 0;
4530 4531 4532 4533
}



E
Eric Blake 已提交
4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544
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);

4545
    if (esxVI_EnsureSession(priv->primary) < 0)
E
Eric Blake 已提交
4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556
        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) {
4557 4558 4559
        virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                       _("snapshot '%s' does not have a parent"),
                       snapshotTree->name);
E
Eric Blake 已提交
4560 4561 4562 4563 4564
        goto cleanup;
    }

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

4565
 cleanup:
E
Eric Blake 已提交
4566 4567 4568 4569 4570 4571 4572
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return parent;
}



4573 4574 4575 4576 4577
static virDomainSnapshotPtr
esxDomainSnapshotCurrent(virDomainPtr domain, unsigned int flags)
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *currentSnapshotTree = NULL;
M
Matthias Bolte 已提交
4578
    virDomainSnapshotPtr snapshot = NULL;
4579

4580
    virCheckFlags(0, NULL);
4581

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

4585
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4586 4587
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4588
        return NULL;
4589 4590 4591 4592 4593 4594 4595 4596 4597 4598
    }

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

    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return snapshot;
}


4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609
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);

4610
    if (esxVI_EnsureSession(priv->primary) < 0)
4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629
        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);

4630
 cleanup:
4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646
    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);

4647
    if (esxVI_EnsureSession(priv->primary) < 0)
4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660
        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;

4661
 cleanup:
4662 4663 4664 4665
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    return ret;
}

4666 4667 4668 4669

static int
esxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4670
    int result = -1;
4671 4672 4673 4674 4675
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
4676
    char *taskInfoErrorMessage = NULL;
4677

4678
    virCheckFlags(0, -1);
4679

4680
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4681
        return -1;
4682

4683
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4684 4685
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
4686
                                    &snapshotTree, NULL,
4687
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4688
        goto cleanup;
4689 4690
    }

4691
    if (esxVI_RevertToSnapshot_Task(priv->primary, snapshotTree->snapshot, NULL,
4692
                                    esxVI_Boolean_Undefined, &task) < 0 ||
4693
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4694
                                    esxVI_Occurrence_RequiredItem,
4695
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4696
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4697
        goto cleanup;
4698 4699 4700
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4701 4702 4703
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not revert to snapshot '%s': %s"), snapshot->name,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4704
        goto cleanup;
4705 4706
    }

M
Matthias Bolte 已提交
4707 4708
    result = 0;

4709
 cleanup:
4710 4711
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4712
    VIR_FREE(taskInfoErrorMessage);
4713 4714 4715 4716 4717 4718 4719 4720 4721

    return result;
}



static int
esxDomainSnapshotDelete(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4722
    int result = -1;
4723 4724 4725 4726 4727 4728
    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;
4729
    char *taskInfoErrorMessage = NULL;
4730

4731 4732
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
                  VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY, -1);
4733

4734
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4735
        return -1;
4736

4737
    if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN)
4738 4739
        removeChildren = esxVI_Boolean_True;

4740
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4741 4742
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
4743
                                    &snapshotTree, NULL,
4744
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4745
        goto cleanup;
4746 4747
    }

4748 4749 4750 4751 4752 4753 4754
    /* 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;
    }

4755
    if (esxVI_RemoveSnapshot_Task(priv->primary, snapshotTree->snapshot,
4756
                                  removeChildren, &task) < 0 ||
4757
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4758
                                    esxVI_Occurrence_RequiredItem,
4759
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4760
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4761
        goto cleanup;
4762 4763 4764
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4765 4766 4767
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not delete snapshot '%s': %s"), snapshot->name,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4768
        goto cleanup;
4769 4770
    }

M
Matthias Bolte 已提交
4771 4772
    result = 0;

4773
 cleanup:
4774 4775
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4776
    VIR_FREE(taskInfoErrorMessage);
4777 4778 4779 4780 4781 4782

    return result;
}



4783
static int
4784
esxDomainSetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
4785 4786 4787 4788 4789 4790 4791 4792
                             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;
4793
    char *taskInfoErrorMessage = NULL;
4794
    size_t i;
4795 4796

    virCheckFlags(0, -1);
4797 4798 4799 4800
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_MEMORY_MIN_GUARANTEE,
                               VIR_TYPED_PARAM_ULLONG,
                               NULL) < 0)
4801
        return -1;
4802

4803
    if (esxVI_EnsureSession(priv->primary) < 0)
4804 4805 4806 4807
        return -1;

    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4808
           priv->parsedUri->autoAnswer) < 0 ||
4809 4810 4811 4812 4813 4814
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0) {
        goto cleanup;
    }

    for (i = 0; i < nparams; ++i) {
4815
        if (STREQ(params[i].field, VIR_DOMAIN_MEMORY_MIN_GUARANTEE)) {
4816
            if (esxVI_Long_Alloc(&spec->memoryAllocation->reservation) < 0)
4817 4818 4819
                goto cleanup;

            spec->memoryAllocation->reservation->value =
4820
              VIR_DIV_UP(params[i].value.ul, 1024); /* Scale from kilobytes to megabytes */
4821 4822 4823 4824 4825 4826 4827
        }
    }

    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
4828
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4829
                                    &taskInfoErrorMessage) < 0) {
4830 4831 4832 4833
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4834 4835 4836
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not change memory parameters: %s"),
                       taskInfoErrorMessage);
4837 4838 4839 4840 4841
        goto cleanup;
    }

    result = 0;

4842
 cleanup:
4843 4844 4845
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
4846
    VIR_FREE(taskInfoErrorMessage);
4847 4848 4849 4850 4851 4852 4853

    return result;
}



static int
4854
esxDomainGetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869
                             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;
    }

4870
    if (esxVI_EnsureSession(priv->primary) < 0)
4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882
        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;
    }

4883 4884 4885 4886
    /* Scale from megabytes to kilobytes */
    if (virTypedParameterAssign(params, VIR_DOMAIN_MEMORY_MIN_GUARANTEE,
                                VIR_TYPED_PARAM_ULLONG,
                                reservation->value * 1024) < 0)
4887 4888 4889 4890 4891
        goto cleanup;

    *nparams = 1;
    result = 0;

4892
 cleanup:
4893 4894 4895 4896 4897 4898 4899
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Long_Free(&reservation);

    return result;
}

4900 4901
#define MATCH(FLAG) (flags & (FLAG))
static int
4902 4903 4904
esxConnectListAllDomains(virConnectPtr conn,
                         virDomainPtr **domains,
                         unsigned int flags)
4905 4906 4907
{
    int ret = -1;
    esxPrivate *priv = conn->privateData;
4908 4909
    bool needIdentity;
    bool needPowerState;
4910 4911 4912
    virDomainPtr dom;
    virDomainPtr *doms = NULL;
    size_t ndoms = 0;
4913
    esxVI_String *propertyNameList = NULL;
4914 4915
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
4916
    esxVI_AutoStartDefaults *autoStartDefaults = NULL;
4917 4918 4919 4920 4921 4922 4923 4924 4925 4926
    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;
4927
    esxVI_DynamicProperty *dynamicProperty = NULL;
4928 4929 4930 4931 4932 4933 4934

    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
     */
4935
    if ((MATCH(VIR_CONNECT_LIST_DOMAINS_TRANSIENT) &&
4936 4937 4938 4939 4940
         !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)
4941
            goto cleanup;
4942 4943 4944 4945 4946

        ret = 0;
        goto cleanup;
    }

4947
    if (esxVI_EnsureSession(priv->primary) < 0)
4948 4949 4950 4951 4952
        return -1;

    /* check system default autostart value */
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_AUTOSTART)) {
        if (esxVI_LookupAutoStartDefaults(priv->primary,
4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965
                                          &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) ||
4966
                   domains;
4967 4968 4969 4970 4971 4972 4973

    if (needIdentity) {
        /* Request required data for esxVI_GetVirtualMachineIdentity */
        if (esxVI_String_AppendValueListToList(&propertyNameList,
                                               "configStatus\0"
                                               "name\0"
                                               "config.uuid\0") < 0) {
4974
            goto cleanup;
4975 4976 4977 4978 4979
        }
    }

    needPowerState = MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_ACTIVE) ||
                     MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_STATE) ||
4980
                     domains;
4981

4982 4983 4984
    if (needPowerState) {
        if (esxVI_String_AppendValueToList(&propertyNameList,
                                           "runtime.powerState") < 0) {
4985
            goto cleanup;
4986
        }
4987 4988
    }

4989 4990 4991 4992 4993 4994 4995
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_SNAPSHOT)) {
        if (esxVI_String_AppendValueToList(&propertyNameList,
                                           "snapshot.rootSnapshotList") < 0) {
            goto cleanup;
        }
    }

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 5036
            esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

5037 5038 5039 5040 5041 5042 5043 5044 5045 5046
            for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
                dynamicProperty = dynamicProperty->_next) {
                if (STREQ(dynamicProperty->name, "snapshot.rootSnapshotList")) {
                    if (esxVI_VirtualMachineSnapshotTree_CastListFromAnyType
                        (dynamicProperty->val, &rootSnapshotTreeList) < 0) {
                        goto cleanup;
                    }

                    break;
                }
5047 5048 5049
            }

            if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT) &&
5050
                   rootSnapshotTreeList) ||
5051
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT) &&
5052
                   !rootSnapshotTreeList)))
5053 5054 5055 5056 5057 5058 5059
                continue;
        }

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

5060
            if (autoStartDefaults->enabled == esxVI_Boolean_True) {
5061
                for (powerInfo = powerInfoList; powerInfo;
5062 5063 5064 5065
                     powerInfo = powerInfo->_next) {
                    if (STREQ(powerInfo->key->value, virtualMachine->obj->value)) {
                        if (STRCASEEQ(powerInfo->startAction, "powerOn"))
                            autostart = true;
5066

5067 5068
                        break;
                    }
5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081
                }
            }

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

5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101
            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;
        }

5102
        if (VIR_RESIZE_N(doms, ndoms, count, 2) < 0)
5103
            goto cleanup;
5104

5105 5106 5107
        if (!(dom = virGetDomain(conn, name, uuid)))
            goto cleanup;

5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121
        /* 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;

5122
 cleanup:
5123
    if (doms) {
5124
        for (id = 0; id < count; id++)
5125
            virObjectUnref(doms[id]);
5126 5127

        VIR_FREE(doms);
5128
    }
5129

5130
    VIR_FREE(name);
5131 5132
    esxVI_AutoStartDefaults_Free(&autoStartDefaults);
    esxVI_AutoStartPowerInfo_Free(&powerInfoList);
5133 5134
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
5135 5136
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

5137 5138 5139
    return ret;
}
#undef MATCH
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 5169 5170 5171 5172 5173 5174 5175 5176
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;
}

5177

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


5260 5261 5262 5263 5264 5265
static virConnectDriver esxConnectDriver = {
    .hypervisorDriver = &esxHypervisorDriver,
    .interfaceDriver = &esxInterfaceDriver,
    .networkDriver = &esxNetworkDriver,
    .storageDriver = &esxStorageDriver,
};
5266 5267 5268 5269

int
esxRegister(void)
{
5270 5271
    return virRegisterConnectDriver(&esxConnectDriver,
                                    false);
5272
}