esx_driver.c 170.6 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 616 617 618 619 620 621 622 623 624
                 char **vCenterIpAddress)
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
    char *password = NULL;
    char *url = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_Boolean inMaintenanceMode = esxVI_Boolean_Undefined;
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 686 687 688 689 690 691
        esxVI_GetBoolean(hostSystem, "runtime.inMaintenanceMode",
                         &inMaintenanceMode,
                         esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_GetStringValue(hostSystem, "summary.managementServerIp",
                             vCenterIpAddress,
                             esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
    }

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

695 696
    if (VIR_STRDUP(*vCenterIpAddress, *vCenterIpAddress) < 0)
        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 726
    if (!hostSystemIpAddress &&
        (!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 775
        if (esxVI_Context_LookupManagedObjectsByHostSystemIp
              (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 844
esxConnectOpen(virConnectPtr conn, virConnectAuthPtr auth,
               unsigned int flags)
845
{
M
Matthias Bolte 已提交
846
    virDrvOpenStatus result = VIR_DRV_OPEN_ERROR;
847
    char *plus;
848
    esxPrivate *priv = NULL;
849
    char *potentialVCenterIpAddress = NULL;
M
Matthias Bolte 已提交
850
    char vCenterIpAddress[NI_MAXHOST] = "";
851

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

967
                if (potentialVCenterIpAddress &&
968
                    STRNEQ(vCenterIpAddress, potentialVCenterIpAddress)) {
969 970 971 972 973 974
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("This host is managed by a vCenter with IP "
                                     "address %s, but a mismachting vCenter '%s' "
                                     "(%s) has been specified"),
                                   potentialVCenterIpAddress, priv->parsedUri->vCenter,
                                   vCenterIpAddress);
M
Matthias Bolte 已提交
975
                    goto cleanup;
976 977
                }
            }
978

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

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

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

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

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

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

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

1011
 cleanup:
1012
    esxFreePrivate(&priv);
1013
    VIR_FREE(potentialVCenterIpAddress);
1014

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



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

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

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

1040
    esxFreePrivate(&priv);
1041 1042 1043

    conn->privateData = NULL;

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



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

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

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

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

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

M
Matthias Bolte 已提交
1079
    return priv->supportsVMotion;
1080 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
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;
}



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

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

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

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

      default:
        return 0;
    }
}



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



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

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

    return 0;
}



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

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

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

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

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

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

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

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

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

    return complete;
}



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

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

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

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

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

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

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

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

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

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

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

            ptr = dynamicProperty->val->string;

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

                ++ptr;
            }

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

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

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

    return result;
}



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

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



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

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

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

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

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

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

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

        count++;

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

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

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

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



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

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

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



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

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

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

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

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

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

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

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

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

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

        domain->id = id;

        break;
    }

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

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

    return domain;
}



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

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

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

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

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

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

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

    return domain;
}



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

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

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

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

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

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

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

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

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

    return domain;
}



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

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

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

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

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

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

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

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

    return result;
}



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

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

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

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

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

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

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

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

    return result;
}



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

1759 1760
    virCheckFlags(0, -1);

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

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

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

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

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

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

    return result;
}


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

1798 1799

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

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

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

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

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

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

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

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

    return result;
}



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

1856 1857
    virCheckFlags(0, -1);

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

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

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

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

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

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

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

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

    return result;
}


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

1915 1916

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

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



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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return result;
}



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

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

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

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

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

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

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

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

    return result;
}



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

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

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

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

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

    info->state = VIR_DOMAIN_NOSTATE;

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

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

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

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

            memory_limit = dynamicProperty->val->int64;

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

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

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

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

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

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

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

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

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

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

2245
                counterId = NULL;
2246

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

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

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

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

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

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

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

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

2311 2312
                perfEntityMetric =
                  esxVI_PerfEntityMetric_DynamicCast(perfEntityMetricBase);
2313

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

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

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

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

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

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

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

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

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

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

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

    return result;
}



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

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

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

    return result;
}



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



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

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

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

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

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

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

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

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

    spec->numCPUs->value = nvcpus;

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

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

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

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

    return result;
}


M
Matthias Bolte 已提交
2583

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

2590

M
Matthias Bolte 已提交
2591

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

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

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

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

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

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

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

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

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

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

M
Matthias Bolte 已提交
2642 2643


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

M
Matthias Bolte 已提交
2651 2652


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

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

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

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

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

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

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

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

2709 2710
    url = virBufferContentAndReset(&buffer);

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

2714
    data.ctx = priv->primary;
2715

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

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

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

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

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

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

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

    return xml;
}



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

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

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

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

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

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

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

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

    virDomainDefFree(def);

    return xml;
}



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

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

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

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

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

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

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

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

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

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

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

    virDomainDefFree(def);

    return vmx;
}



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

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

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

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

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

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

2892
        names[count] = NULL;
2893

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

2899 2900
        ++count;

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

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

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

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

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

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



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

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

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



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

2950 2951
    virCheckFlags(0, -1);

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

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

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

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

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

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

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

    return result;
}

2998 2999


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

3006 3007


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

3036 3037 3038
    virCheckFlags(VIR_DOMAIN_DEFINE_VALIDATE, NULL);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    url = virBufferContentAndReset(&buffer);

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

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

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

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

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

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

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

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

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

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

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

    return domain;
}

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

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

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

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

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

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

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

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

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

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

    return result;
}


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

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

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

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

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

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

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

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

            break;
        }
    }

    result = 0;

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

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

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

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

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

3448
    newPowerInfo = NULL;
3449

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

    result = 0;

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

3471
    esxVI_AutoStartPowerInfo_Free(&newPowerInfo);
3472

3473 3474 3475 3476 3477
    return result;
}



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

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

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

    return type;
}



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

3538 3539
    virCheckFlags(0, -1);

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

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

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

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

            esxVI_SharesInfo_Free(&sharesInfo);

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

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

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

    return result;
}

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return result;
}

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

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

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

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

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

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



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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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



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

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

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

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

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

    return result;
}



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

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



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

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



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



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

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

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

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

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

    return result;
}



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

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

    return result;
4123 4124
}

M
Matthias Bolte 已提交
4125 4126


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

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

    return result;
4150
}
4151

M
Matthias Bolte 已提交
4152 4153


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

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

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

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

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

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

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

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

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

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

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

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

    return snapshot;
}



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

4252 4253
    virCheckFlags(0, NULL);

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

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

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

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

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

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

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

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

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

    return xml;
}



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

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

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

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

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

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

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

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

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



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

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

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

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

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

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

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

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

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



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

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

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

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

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

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

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

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

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

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

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

    return result;
}



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

4483 4484
    virCheckFlags(0, NULL);

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

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

    snapshot = virGetDomainSnapshot(domain, name);

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

    return snapshot;
}



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

4512
    virCheckFlags(0, -1);
4513

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

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

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

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



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

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

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

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

    return parent;
}



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

4579
    virCheckFlags(0, NULL);
4580

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

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

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

    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return snapshot;
}


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

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

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

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

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

4665 4666 4667 4668

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

4677
    virCheckFlags(0, -1);
4678

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

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

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

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

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

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

    return result;
}



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

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

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

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

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

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

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

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

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

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

    return result;
}



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

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

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

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

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

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

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

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

    result = 0;

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

    return result;
}



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

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

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

    *nparams = 1;
    result = 0;

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

    return result;
}

4899 4900
#define MATCH(FLAG) (flags & (FLAG))
static int
4901 4902 4903
esxConnectListAllDomains(virConnectPtr conn,
                         virDomainPtr **domains,
                         unsigned int flags)
4904 4905 4906
{
    int ret = -1;
    esxPrivate *priv = conn->privateData;
4907 4908
    bool needIdentity;
    bool needPowerState;
4909 4910 4911
    virDomainPtr dom;
    virDomainPtr *doms = NULL;
    size_t ndoms = 0;
4912
    esxVI_String *propertyNameList = NULL;
4913 4914
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
4915
    esxVI_AutoStartDefaults *autoStartDefaults = NULL;
4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932
    esxVI_VirtualMachinePowerState powerState;
    esxVI_AutoStartPowerInfo *powerInfoList = NULL;
    esxVI_AutoStartPowerInfo *powerInfo = NULL;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    char *name = NULL;
    int id;
    unsigned char uuid[VIR_UUID_BUFLEN];
    int count = 0;
    bool autostart;
    int state;

    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);

    /* check for flags that would produce empty output lists:
     * - persistence: all esx machines are persistent
     * - managed save: esx doesn't support managed save
     */
4933
    if ((MATCH(VIR_CONNECT_LIST_DOMAINS_TRANSIENT) &&
4934 4935 4936 4937 4938
         !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)
4939
            goto cleanup;
4940 4941 4942 4943 4944

        ret = 0;
        goto cleanup;
    }

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

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

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

    needPowerState = MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_ACTIVE) ||
                     MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_STATE) ||
4978
                     domains;
4979

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

4987
    if (esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
4988 4989 4990 4991 4992
                                       &virtualMachineList) < 0)
        goto cleanup;

    if (domains) {
        if (VIR_ALLOC_N(doms, 1) < 0)
4993
            goto cleanup;
4994 4995 4996
        ndoms = 1;
    }

4997
    for (virtualMachine = virtualMachineList; virtualMachine;
4998
         virtualMachine = virtualMachine->_next) {
4999 5000
        if (needIdentity) {
            VIR_FREE(name);
5001

5002 5003 5004 5005 5006
            if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id,
                                                &name, uuid) < 0) {
                goto cleanup;
            }
        }
5007

5008 5009 5010 5011 5012 5013
        if (needPowerState) {
            if (esxVI_GetVirtualMachinePowerState(virtualMachine,
                                                  &powerState) < 0) {
                goto cleanup;
            }
        }
5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024

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

5027 5028 5029 5030 5031 5032
            if (esxVI_LookupRootSnapshotTreeList(priv->primary, uuid,
                                                 &rootSnapshotTreeList) < 0) {
                goto cleanup;
            }

            if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT) &&
5033
                   rootSnapshotTreeList) ||
5034
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT) &&
5035
                   !rootSnapshotTreeList)))
5036 5037 5038 5039 5040 5041 5042
                continue;
        }

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

5043
            if (autoStartDefaults->enabled == esxVI_Boolean_True) {
5044
                for (powerInfo = powerInfoList; powerInfo;
5045 5046 5047 5048
                     powerInfo = powerInfo->_next) {
                    if (STREQ(powerInfo->key->value, virtualMachine->obj->value)) {
                        if (STRCASEEQ(powerInfo->startAction, "powerOn"))
                            autostart = true;
5049

5050 5051
                        break;
                    }
5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064
                }
            }

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

5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084
            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;
        }

5085
        if (VIR_RESIZE_N(doms, ndoms, count, 2) < 0)
5086
            goto cleanup;
5087

5088 5089 5090
        if (!(dom = virGetDomain(conn, name, uuid)))
            goto cleanup;

5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104
        /* 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;

5105
 cleanup:
5106
    if (doms) {
5107
        for (id = 0; id < count; id++)
5108
            virObjectUnref(doms[id]);
5109 5110

        VIR_FREE(doms);
5111
    }
5112

5113
    VIR_FREE(name);
5114 5115
    esxVI_AutoStartDefaults_Free(&autoStartDefaults);
    esxVI_AutoStartPowerInfo_Free(&powerInfoList);
5116 5117
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
5118 5119
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

5120 5121 5122
    return ret;
}
#undef MATCH
5123

5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159
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;
}

5160

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


5243 5244 5245 5246 5247 5248
static virConnectDriver esxConnectDriver = {
    .hypervisorDriver = &esxHypervisorDriver,
    .interfaceDriver = &esxInterfaceDriver,
    .networkDriver = &esxNetworkDriver,
    .storageDriver = &esxStorageDriver,
};
5249 5250 5251 5252

int
esxRegister(void)
{
5253 5254
    return virRegisterConnectDriver(&esxConnectDriver,
                                    false);
5255
}