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

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

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

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

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

173
            if (!tmp)
174
                continue;
175

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

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

183
            tmp = strippedFileName;
184

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

190 191
                ++tmp;
            }
192

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

197 198
            break;
        }
199

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

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

215
            esxVI_ObjectContent_Free(&datastoreList);
216

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

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

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

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

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

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

256
    return result;
257 258 259 260
}



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

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

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

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

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

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

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

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

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

324 325
                ++tmp;
            }
326
        }
327

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

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

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

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

    success = true;

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

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

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



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

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

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

392
    vmDiskFileInfo = esxVI_VmDiskFileInfo_DynamicCast(fileInfo);
393

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

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

    result = 0;

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

    return result;
}

427 428


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

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

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

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

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

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

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

                    if (edxLongModeBit == '1') {
                        priv->supportsLongMode = esxVI_Boolean_True;
                    } else if (edxLongModeBit == '0') {
                        priv->supportsLongMode = esxVI_Boolean_False;
                    } else {
476 477 478 479 480
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("Bit 29 (Long Mode) of HostSystem property "
                                         "'hardware.cpuFeature[].edx' with value '%s' "
                                         "has unexpected value '%c', expecting '0' "
                                         "or '1'"), hostCpuIdInfo->edx, edxLongModeBit);
M
Matthias Bolte 已提交
481
                        goto cleanup;
482 483 484 485 486 487 488 489 490 491 492 493
                    }

                    break;
                }
            }

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

494
 cleanup:
M
Matthias Bolte 已提交
495 496 497 498
    /*
     * If we goto cleanup in case of an error then priv->supportsLongMode
     * is still esxVI_Boolean_Undefined, therefore we don't need to set it.
     */
499 500 501 502 503 504 505 506 507
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_HostCpuIdInfo_Free(&hostCpuIdInfoList);

    return priv->supportsLongMode;
}



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

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

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

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

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

    result = 0;

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

    return result;
}


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

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

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

566
    if (!caps)
567 568
        return NULL;

569
    virCapabilitiesAddHostMigrateTransport(caps, "vpxmigr");
570

571

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

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

581
    if (!guest)
582 583
        goto failure;

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

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

594
        if (!guest)
595 596
            goto failure;

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

601 602
    return caps;

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

    return NULL;
}



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

629
    ESX_VI_CHECK_ARG_LIST(vCenterIPAddress);
630

631
    if (esxUtil_ResolveHostname(conn->uri->server, ipAddress, NI_MAXHOST) < 0)
632 633
        return -1;

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

643 644
    if (!(password = virAuthGetPassword(conn, auth, "esx", username,
                                        conn->uri->server)))
645 646
        goto cleanup;

647
    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->parsedUri->transport,
648
                    conn->uri->server, conn->uri->port) < 0)
649 650 651 652
        goto cleanup;

    if (esxVI_Context_Alloc(&priv->host) < 0 ||
        esxVI_Context_Connect(priv->host, url, ipAddress, username, password,
653
                              priv->parsedUri) < 0 ||
654
        esxVI_Context_LookupManagedObjects(priv->host) < 0) {
655 656 657
        goto cleanup;
    }

658 659 660 661 662 663 664
    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;
665 666 667 668 669 670
    }

    /* Query the host for maintenance mode and vCenter IP address */
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "runtime.inMaintenanceMode\0"
                                           "summary.managementServerIp\0") < 0 ||
671 672
        esxVI_LookupHostSystemProperties(priv->host, propertyNameList,
                                         &hostSystem) < 0 ||
673 674 675 676
        esxVI_GetBoolean(hostSystem, "runtime.inMaintenanceMode",
                         &inMaintenanceMode,
                         esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_GetStringValue(hostSystem, "summary.managementServerIp",
677
                             vCenterIPAddress,
678 679 680 681 682
                             esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
    }

    /* Warn if host is in maintenance mode */
683
    if (inMaintenanceMode == esxVI_Boolean_True)
684
        VIR_WARN("The server is in maintenance mode");
685

686
    if (VIR_STRDUP(*vCenterIPAddress, *vCenterIPAddress) < 0)
687
        goto cleanup;
688 689 690

    result = 0;

691
 cleanup:
692
    VIR_FREE(username);
M
Matthias Bolte 已提交
693
    VIR_FREE(password);
694 695 696 697 698 699 700 701 702 703
    VIR_FREE(url);
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



static int
704 705
esxConnectToVCenter(esxPrivate *priv,
                    virConnectPtr conn,
706 707
                    virConnectAuthPtr auth,
                    const char *hostname,
708
                    const char *hostSystemIPAddress)
709 710 711 712 713 714 715
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
    char *password = NULL;
    char *url = NULL;

716
    if (!hostSystemIPAddress &&
717
        (!priv->parsedUri->path || STREQ(priv->parsedUri->path, "/"))) {
718 719
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Path has to specify the datacenter and compute resource"));
720 721 722
        return -1;
    }

723
    if (esxUtil_ResolveHostname(hostname, ipAddress, NI_MAXHOST) < 0)
724 725
        return -1;

726
    if (conn->uri->user) {
727
        if (VIR_STRDUP(username, conn->uri->user) < 0)
728 729
            goto cleanup;
    } else {
730 731
        if (!(username = virAuthGetUsername(conn, auth, "esx", "administrator",
                                            hostname)))
732 733 734
            goto cleanup;
    }

735
    if (!(password = virAuthGetPassword(conn, auth, "esx", username, hostname)))
736 737
        goto cleanup;

738
    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->parsedUri->transport,
739
                    hostname, conn->uri->port) < 0)
740 741 742 743
        goto cleanup;

    if (esxVI_Context_Alloc(&priv->vCenter) < 0 ||
        esxVI_Context_Connect(priv->vCenter, url, ipAddress, username,
744
                              password, priv->parsedUri) < 0) {
745 746 747
        goto cleanup;
    }

748
    if (priv->vCenter->productLine != esxVI_ProductLine_VPX) {
749
        virReportError(VIR_ERR_INTERNAL_ERROR,
750 751 752 753
                       _("Expecting '%s' to be a %s host but found a %s host"),
                       hostname,
                       esxVI_ProductLineToDisplayName(esxVI_ProductLine_VPX),
                       esxVI_ProductLineToDisplayName(priv->vCenter->productLine));
754 755 756
        goto cleanup;
    }

757
    if (hostSystemIPAddress) {
758
        if (esxVI_Context_LookupManagedObjectsByHostSystemIp
759
              (priv->vCenter, hostSystemIPAddress) < 0) {
760 761 762
            goto cleanup;
        }
    } else {
763 764
        if (esxVI_Context_LookupManagedObjectsByPath(priv->vCenter,
                                                     priv->parsedUri->path) < 0) {
765 766 767 768
            goto cleanup;
        }
    }

769 770
    result = 0;

771
 cleanup:
772
    VIR_FREE(username);
M
Matthias Bolte 已提交
773
    VIR_FREE(password);
774 775 776 777 778 779 780
    VIR_FREE(url);

    return result;
}



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

E
Eric Blake 已提交
836 837
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

838
    if (STRCASENEQ(conn->uri->scheme, "vpx") &&
839
        STRNEQ(conn->uri->path, "/")) {
840 841 842 843
        VIR_WARN("Ignoring unexpected path '%s' for non-vpx scheme '%s'",
                 conn->uri->path, conn->uri->scheme);
    }

844
    /* Allocate per-connection private data */
845
    if (VIR_ALLOC(priv) < 0)
M
Matthias Bolte 已提交
846
        goto cleanup;
847

848
    if (esxUtil_ParseUri(&priv->parsedUri, conn->uri) < 0)
849 850
        goto cleanup;

M
Matthias Bolte 已提交
851 852
    priv->maxVcpus = -1;
    priv->supportsVMotion = esxVI_Boolean_Undefined;
853
    priv->supportsLongMode = esxVI_Boolean_Undefined;
854
    priv->supportsScreenshot = esxVI_Boolean_Undefined;
855 856
    priv->usedCpuTimeCounterId = -1;

M
Matthias Bolte 已提交
857 858 859 860 861 862 863
    /*
     * 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) {
864 865
        if (STRCASEEQ(conn->uri->scheme, "vpx") ||
            STRCASEEQ(conn->uri->scheme, "esx")) {
866
            if (STRCASEEQ(priv->parsedUri->transport, "https")) {
M
Matthias Bolte 已提交
867 868 869 870 871
                conn->uri->port = 443;
            } else {
                conn->uri->port = 80;
            }
        } else { /* GSX */
872
            if (STRCASEEQ(priv->parsedUri->transport, "https")) {
M
Matthias Bolte 已提交
873 874 875 876
                conn->uri->port = 8333;
            } else {
                conn->uri->port = 8222;
            }
877
        }
M
Matthias Bolte 已提交
878
    }
879

880 881 882
    if (STRCASEEQ(conn->uri->scheme, "esx") ||
        STRCASEEQ(conn->uri->scheme, "gsx")) {
        /* Connect to host */
883
        if (esxConnectToHost(priv, conn, auth,
884
                             &potentialVCenterIPAddress) < 0) {
M
Matthias Bolte 已提交
885
            goto cleanup;
886
        }
887

888
        /* Connect to vCenter */
889
        if (priv->parsedUri->vCenter) {
890
            if (STREQ(priv->parsedUri->vCenter, "*")) {
891
                if (!potentialVCenterIPAddress) {
892 893
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("This host is not managed by a vCenter"));
M
Matthias Bolte 已提交
894
                    goto cleanup;
895 896
                }

897 898
                if (virStrcpyStatic(vCenterIPAddress,
                                    potentialVCenterIPAddress) < 0) {
899 900
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("vCenter IP address %s too big for destination"),
901
                                   potentialVCenterIPAddress);
902 903 904
                    goto cleanup;
                }
            } else {
905
                if (esxUtil_ResolveHostname(priv->parsedUri->vCenter,
906
                                            vCenterIPAddress, NI_MAXHOST) < 0) {
907 908
                    goto cleanup;
                }
909

910 911
                if (potentialVCenterIPAddress &&
                    STRNEQ(vCenterIPAddress, potentialVCenterIPAddress)) {
912 913
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("This host is managed by a vCenter with IP "
N
Nitesh Konkar 已提交
914
                                     "address %s, but a mismatching vCenter '%s' "
915
                                     "(%s) has been specified"),
916 917
                                   potentialVCenterIPAddress, priv->parsedUri->vCenter,
                                   vCenterIPAddress);
M
Matthias Bolte 已提交
918
                    goto cleanup;
919 920
                }
            }
921

922
            if (esxConnectToVCenter(priv, conn, auth,
923
                                    vCenterIPAddress,
924
                                    priv->host->ipAddress) < 0) {
925 926
                goto cleanup;
            }
927 928
        }

929 930 931
        priv->primary = priv->host;
    } else { /* VPX */
        /* Connect to vCenter */
932
        if (esxConnectToVCenter(priv, conn, auth,
933 934
                                conn->uri->server,
                                NULL) < 0) {
M
Matthias Bolte 已提交
935
            goto cleanup;
936 937
        }

938
        priv->primary = priv->vCenter;
939 940
    }

M
Matthias Bolte 已提交
941
    /* Setup capabilities */
942
    priv->caps = esxCapsInit(priv);
943

944
    if (!priv->caps)
M
Matthias Bolte 已提交
945
        goto cleanup;
946

947
    if (!(priv->xmlopt = virVMXDomainXMLConfInit()))
948 949
        goto cleanup;

950 951
    conn->privateData = priv;
    priv = NULL;
M
Matthias Bolte 已提交
952
    result = VIR_DRV_OPEN_SUCCESS;
953

954
 cleanup:
955
    esxFreePrivate(&priv);
956
    VIR_FREE(potentialVCenterIPAddress);
957

M
Matthias Bolte 已提交
958
    return result;
959 960 961 962 963
}



static int
964
esxConnectClose(virConnectPtr conn)
965
{
M
Matthias Bolte 已提交
966
    esxPrivate *priv = conn->privateData;
E
Eric Blake 已提交
967
    int result = 0;
968

969
    if (priv->host) {
970 971 972 973 974
        if (esxVI_EnsureSession(priv->host) < 0 ||
            esxVI_Logout(priv->host) < 0) {
            result = -1;
        }
    }
975

976
    if (priv->vCenter) {
E
Eric Blake 已提交
977 978 979 980
        if (esxVI_EnsureSession(priv->vCenter) < 0 ||
            esxVI_Logout(priv->vCenter) < 0) {
            result = -1;
        }
981 982
    }

983
    esxFreePrivate(&priv);
984 985 986

    conn->privateData = NULL;

E
Eric Blake 已提交
987
    return result;
988 989 990 991 992
}



static esxVI_Boolean
993
esxSupportsVMotion(esxPrivate *priv)
994 995 996 997
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;

998
    if (priv->supportsVMotion != esxVI_Boolean_Undefined)
M
Matthias Bolte 已提交
999
        return priv->supportsVMotion;
1000

1001
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1002
        return esxVI_Boolean_Undefined;
1003

1004
    if (esxVI_String_AppendValueToList(&propertyNameList,
1005
                                       "capability.vmotionSupported") < 0 ||
1006
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
1007 1008
                                         &hostSystem) < 0 ||
        esxVI_GetBoolean(hostSystem, "capability.vmotionSupported",
1009 1010 1011
                         &priv->supportsVMotion,
                         esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
1012 1013
    }

1014
 cleanup:
M
Matthias Bolte 已提交
1015 1016 1017 1018
    /*
     * 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.
     */
1019 1020 1021
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
1022
    return priv->supportsVMotion;
1023 1024 1025 1026
}



1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
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;
}



1061
static int
1062
esxConnectSupportsFeature(virConnectPtr conn, int feature)
1063
{
M
Matthias Bolte 已提交
1064
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1065
    esxVI_Boolean supportsVMotion = esxVI_Boolean_Undefined;
1066

1067
    switch ((virDrvFeature) feature) {
1068
      case VIR_DRV_FEATURE_MIGRATION_V1:
1069
        supportsVMotion = esxSupportsVMotion(priv);
1070

1071
        if (supportsVMotion == esxVI_Boolean_Undefined)
1072 1073
            return -1;

M
Matthias Bolte 已提交
1074
        /* Migration is only possible via a vCenter and if VMotion is enabled */
1075
        return priv->vCenter &&
M
Matthias Bolte 已提交
1076
               supportsVMotion == esxVI_Boolean_True ? 1 : 0;
1077

1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
    case VIR_DRV_FEATURE_FD_PASSING:
    case VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION:
    case VIR_DRV_FEATURE_MIGRATION_DIRECT:
    case VIR_DRV_FEATURE_MIGRATION_OFFLINE:
    case VIR_DRV_FEATURE_MIGRATION_P2P:
    case VIR_DRV_FEATURE_MIGRATION_PARAMS:
    case VIR_DRV_FEATURE_MIGRATION_V2:
    case VIR_DRV_FEATURE_MIGRATION_V3:
    case VIR_DRV_FEATURE_PROGRAM_KEEPALIVE:
    case VIR_DRV_FEATURE_REMOTE:
    case VIR_DRV_FEATURE_REMOTE_CLOSE_CALLBACK:
    case VIR_DRV_FEATURE_REMOTE_EVENT_CALLBACK:
    case VIR_DRV_FEATURE_TYPED_PARAM_STRING:
    case VIR_DRV_FEATURE_XML_MIGRATABLE:
    default:
1093 1094 1095 1096 1097 1098 1099
        return 0;
    }
}



static const char *
1100
esxConnectGetType(virConnectPtr conn ATTRIBUTE_UNUSED)
1101 1102 1103 1104 1105 1106 1107
{
    return "ESX";
}



static int
1108
esxConnectGetVersion(virConnectPtr conn, unsigned long *version)
1109
{
M
Matthias Bolte 已提交
1110
    esxPrivate *priv = conn->privateData;
1111

1112
    *version = priv->primary->productVersion;
1113 1114 1115 1116 1117 1118 1119

    return 0;
}



static char *
1120
esxConnectGetHostname(virConnectPtr conn)
1121
{
M
Matthias Bolte 已提交
1122
    esxPrivate *priv = conn->privateData;
1123 1124 1125 1126 1127 1128 1129
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    const char *hostName = NULL;
    const char *domainName = NULL;
    char *complete = NULL;

1130
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1131
        return NULL;
1132 1133

    if (esxVI_String_AppendValueListToList
1134
          (&propertyNameList,
1135 1136
           "config.network.dnsConfig.hostName\0"
           "config.network.dnsConfig.domainName\0") < 0 ||
1137 1138
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1139
        goto cleanup;
1140 1141
    }

1142
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
1143 1144 1145
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name,
                  "config.network.dnsConfig.hostName")) {
1146
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1147
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1148
                goto cleanup;
1149 1150 1151 1152 1153
            }

            hostName = dynamicProperty->val->string;
        } else if (STREQ(dynamicProperty->name,
                         "config.network.dnsConfig.domainName")) {
1154
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1155
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1156
                goto cleanup;
1157 1158 1159 1160 1161 1162 1163 1164
            }

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

1165
    if (!hostName || strlen(hostName) < 1) {
1166 1167
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing or empty 'hostName' property"));
M
Matthias Bolte 已提交
1168
        goto cleanup;
1169 1170
    }

1171
    if (!domainName || strlen(domainName) < 1) {
1172
        if (VIR_STRDUP(complete, hostName) < 0)
M
Matthias Bolte 已提交
1173
            goto cleanup;
1174
    } else {
1175
        if (virAsprintf(&complete, "%s.%s", hostName, domainName) < 0)
M
Matthias Bolte 已提交
1176
            goto cleanup;
1177 1178
    }

1179
 cleanup:
M
Matthias Bolte 已提交
1180 1181
    /*
     * If we goto cleanup in case of an error then complete is still NULL,
1182
     * either VIR_STRDUP returned -1 or virAsprintf failed. When virAsprintf
M
Matthias Bolte 已提交
1183 1184
     * fails it guarantees setting complete to NULL
     */
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return complete;
}



static int
esxNodeGetInfo(virConnectPtr conn, virNodeInfoPtr nodeinfo)
{
M
Matthias Bolte 已提交
1196
    int result = -1;
M
Matthias Bolte 已提交
1197
    esxPrivate *priv = conn->privateData;
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
    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;

1209
    memset(nodeinfo, 0, sizeof(*nodeinfo));
1210

1211
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1212
        return -1;
1213

1214
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1215 1216 1217 1218 1219 1220 1221
                                           "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 ||
1222 1223
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1224
        goto cleanup;
1225 1226
    }

1227
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
1228 1229
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuInfo.hz")) {
1230
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1231
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1232
                goto cleanup;
1233 1234 1235 1236 1237
            }

            cpuInfo_hz = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuCores")) {
1238
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1239
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1240
                goto cleanup;
1241 1242 1243 1244 1245
            }

            cpuInfo_numCpuCores = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuPackages")) {
1246
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1247
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1248
                goto cleanup;
1249 1250 1251 1252 1253
            }

            cpuInfo_numCpuPackages = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuThreads")) {
1254
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1255
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1256
                goto cleanup;
1257 1258 1259 1260
            }

            cpuInfo_numCpuThreads = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name, "hardware.memorySize")) {
1261
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1262
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1263
                goto cleanup;
1264 1265 1266 1267 1268
            }

            memorySize = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.numaInfo.numNodes")) {
1269
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1270
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1271
                goto cleanup;
1272 1273 1274 1275 1276
            }

            numaInfo_numNodes = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "summary.hardware.cpuModel")) {
1277
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1278
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1279
                goto cleanup;
1280 1281 1282 1283 1284 1285
            }

            ptr = dynamicProperty->val->string;

            /* Strip the string to fit more relevant information in 32 chars */
            while (*ptr != '\0') {
M
Matthias Bolte 已提交
1286 1287
                if (STRPREFIX(ptr, "  ")) {
                    memmove(ptr, ptr + 1, strlen(ptr + 1) + 1);
1288
                    continue;
1289
                } else if (STRPREFIX(ptr, "(R)") || STRPREFIX(ptr, "(C)")) {
M
Matthias Bolte 已提交
1290
                    memmove(ptr, ptr + 3, strlen(ptr + 3) + 1);
1291
                    continue;
1292 1293 1294
                } else if (STRPREFIX(ptr, "(TM)")) {
                    memmove(ptr, ptr + 4, strlen(ptr + 4) + 1);
                    continue;
1295 1296 1297 1298 1299
                }

                ++ptr;
            }

1300 1301
            /* Make sure the string fits in mode */
            dynamicProperty->val->string[sizeof(nodeinfo->model) - 1] = '\0';
1302
            if (virStrcpyStatic(nodeinfo->model, dynamicProperty->val->string) < 0) {
1303 1304 1305
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("CPU Model %s too long for destination"),
                               dynamicProperty->val->string);
M
Matthias Bolte 已提交
1306
                goto cleanup;
C
Chris Lalancette 已提交
1307
            }
1308 1309 1310 1311 1312 1313 1314
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    nodeinfo->memory = memorySize / 1024; /* Scale from bytes to kilobytes */
    nodeinfo->cpus = cpuInfo_numCpuCores;
1315
    nodeinfo->mhz = cpuInfo_hz / (1000 * 1000); /* Scale from hz to mhz */
1316 1317 1318 1319 1320 1321 1322 1323 1324
    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 已提交
1325 1326
    result = 0;

1327
 cleanup:
1328 1329 1330 1331 1332 1333 1334 1335
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



1336
static char *
1337
esxConnectGetCapabilities(virConnectPtr conn)
1338
{
M
Matthias Bolte 已提交
1339
    esxPrivate *priv = conn->privateData;
1340

1341
    return virCapabilitiesFormatXML(priv->caps);
1342 1343 1344 1345
}



1346
static int
1347
esxConnectListDomains(virConnectPtr conn, int *ids, int maxids)
1348
{
M
Matthias Bolte 已提交
1349
    bool success = false;
M
Matthias Bolte 已提交
1350
    esxPrivate *priv = conn->privateData;
1351 1352 1353 1354 1355 1356
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;

1357
    if (maxids == 0)
1358 1359
        return 0;

1360
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1361
        return -1;
1362

1363
    if (esxVI_String_AppendValueToList(&propertyNameList,
1364
                                       "runtime.powerState") < 0 ||
1365 1366
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1367
        goto cleanup;
1368 1369
    }

1370
    for (virtualMachine = virtualMachineList; virtualMachine;
1371
         virtualMachine = virtualMachine->_next) {
1372
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1373
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1374
            goto cleanup;
1375 1376
        }

1377
        if (powerState != esxVI_VirtualMachinePowerState_PoweredOn)
1378 1379 1380 1381 1382
            continue;

        if (esxUtil_ParseVirtualMachineIDString(virtualMachine->obj->value,
                                                &ids[count]) < 0 ||
            ids[count] <= 0) {
1383 1384 1385
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to parse positive integer from '%s'"),
                           virtualMachine->obj->value);
M
Matthias Bolte 已提交
1386
            goto cleanup;
1387 1388 1389 1390
        }

        count++;

1391
        if (count >= maxids)
1392 1393 1394
            break;
    }

M
Matthias Bolte 已提交
1395 1396
    success = true;

1397
 cleanup:
1398 1399 1400
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
1401
    return success ? count : -1;
1402 1403 1404 1405 1406
}



static int
1407
esxConnectNumOfDomains(virConnectPtr conn)
1408
{
M
Matthias Bolte 已提交
1409
    esxPrivate *priv = conn->privateData;
1410

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

1414
    return esxVI_LookupNumberOfDomainsByPowerState
1415
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, false);
1416 1417 1418 1419 1420 1421 1422
}



static virDomainPtr
esxDomainLookupByID(virConnectPtr conn, int id)
{
M
Matthias Bolte 已提交
1423
    esxPrivate *priv = conn->privateData;
1424 1425 1426 1427
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
M
Matthias Bolte 已提交
1428 1429 1430
    int id_candidate = -1;
    char *name_candidate = NULL;
    unsigned char uuid_candidate[VIR_UUID_BUFLEN];
1431 1432
    virDomainPtr domain = NULL;

1433
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1434
        return NULL;
1435

1436
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1437
                                           "configStatus\0"
1438 1439
                                           "name\0"
                                           "runtime.powerState\0"
1440
                                           "config.uuid\0") < 0 ||
1441 1442
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1443
        goto cleanup;
1444 1445
    }

1446
    for (virtualMachine = virtualMachineList; virtualMachine;
1447
         virtualMachine = virtualMachine->_next) {
1448
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1449
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1450
            goto cleanup;
1451 1452 1453
        }

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

M
Matthias Bolte 已提交
1457
        VIR_FREE(name_candidate);
1458

1459
        if (esxVI_GetVirtualMachineIdentity(virtualMachine,
M
Matthias Bolte 已提交
1460 1461
                                            &id_candidate, &name_candidate,
                                            uuid_candidate) < 0) {
M
Matthias Bolte 已提交
1462
            goto cleanup;
1463 1464
        }

1465
        if (id != id_candidate)
1466 1467
            continue;

1468
        domain = virGetDomain(conn, name_candidate, uuid_candidate, id);
1469

1470
        if (!domain)
M
Matthias Bolte 已提交
1471
            goto cleanup;
1472 1473 1474 1475

        break;
    }

1476
    if (!domain)
1477
        virReportError(VIR_ERR_NO_DOMAIN, _("No domain with ID %d"), id);
1478

1479
 cleanup:
1480 1481
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
M
Matthias Bolte 已提交
1482
    VIR_FREE(name_candidate);
1483 1484 1485 1486 1487 1488 1489 1490 1491

    return domain;
}



static virDomainPtr
esxDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
M
Matthias Bolte 已提交
1492
    esxPrivate *priv = conn->privateData;
1493 1494 1495
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1496 1497
    int id = -1;
    char *name = NULL;
1498 1499
    virDomainPtr domain = NULL;

1500
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1501
        return NULL;
1502

1503
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1504
                                           "name\0"
1505
                                           "runtime.powerState\0") < 0 ||
1506
        esxVI_LookupVirtualMachineByUuid(priv->primary, uuid, propertyNameList,
1507
                                         &virtualMachine,
M
Matthias Bolte 已提交
1508
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1509 1510
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, &name, NULL) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1511
        goto cleanup;
1512 1513
    }

1514
    /* Only running/suspended virtual machines have an ID != -1 */
1515 1516 1517 1518
    if (powerState == esxVI_VirtualMachinePowerState_PoweredOff)
        id = -1;

    domain = virGetDomain(conn, name, uuid, id);
1519

1520
 cleanup:
1521
    esxVI_String_Free(&propertyNameList);
1522 1523
    esxVI_ObjectContent_Free(&virtualMachine);
    VIR_FREE(name);
1524 1525 1526 1527 1528 1529 1530 1531 1532

    return domain;
}



static virDomainPtr
esxDomainLookupByName(virConnectPtr conn, const char *name)
{
M
Matthias Bolte 已提交
1533
    esxPrivate *priv = conn->privateData;
1534 1535 1536
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1537 1538
    int id = -1;
    unsigned char uuid[VIR_UUID_BUFLEN];
1539 1540
    virDomainPtr domain = NULL;

1541
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1542
        return NULL;
1543

1544
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1545
                                           "configStatus\0"
1546
                                           "runtime.powerState\0"
1547
                                           "config.uuid\0") < 0 ||
1548
        esxVI_LookupVirtualMachineByName(priv->primary, name, propertyNameList,
1549
                                         &virtualMachine,
1550
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
1551
        goto cleanup;
1552
    }
1553

M
Matthias Bolte 已提交
1554 1555 1556
    if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, uuid) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
1557
    }
1558

1559
    /* Only running/suspended virtual machines have an ID != -1 */
1560 1561 1562 1563
    if (powerState == esxVI_VirtualMachinePowerState_PoweredOff)
        id = -1;

    domain = virGetDomain(conn, name, uuid, id);
1564

1565
 cleanup:
1566
    esxVI_String_Free(&propertyNameList);
1567
    esxVI_ObjectContent_Free(&virtualMachine);
1568 1569 1570 1571 1572 1573 1574 1575 1576

    return domain;
}



static int
esxDomainSuspend(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1577
    int result = -1;
M
Matthias Bolte 已提交
1578
    esxPrivate *priv = domain->conn->privateData;
1579 1580 1581 1582 1583
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1584
    char *taskInfoErrorMessage = NULL;
1585

1586
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1587
        return -1;
1588

1589
    if (esxVI_String_AppendValueToList(&propertyNameList,
1590
                                       "runtime.powerState") < 0 ||
1591
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1592
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1593
           priv->parsedUri->autoAnswer) < 0 ||
1594
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1595
        goto cleanup;
1596 1597 1598
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1599 1600
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1601
        goto cleanup;
1602 1603
    }

1604 1605
    if (esxVI_SuspendVM_Task(priv->primary, virtualMachine->obj, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1606
                                    esxVI_Occurrence_RequiredItem,
1607
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1608
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1609
        goto cleanup;
1610 1611 1612
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1613 1614
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not suspend domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
1615
        goto cleanup;
1616 1617
    }

M
Matthias Bolte 已提交
1618 1619
    result = 0;

1620
 cleanup:
1621 1622 1623
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1624
    VIR_FREE(taskInfoErrorMessage);
1625 1626 1627 1628 1629 1630 1631 1632 1633

    return result;
}



static int
esxDomainResume(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1634
    int result = -1;
M
Matthias Bolte 已提交
1635
    esxPrivate *priv = domain->conn->privateData;
1636 1637 1638 1639 1640
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1641
    char *taskInfoErrorMessage = NULL;
1642

1643
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1644
        return -1;
1645

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

    if (powerState != esxVI_VirtualMachinePowerState_Suspended) {
1656
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not suspended"));
M
Matthias Bolte 已提交
1657
        goto cleanup;
1658 1659
    }

1660
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
1661
                             &task) < 0 ||
1662
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1663
                                    esxVI_Occurrence_RequiredItem,
1664
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1665
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1666
        goto cleanup;
1667 1668 1669
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1670 1671
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not resume domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
1672
        goto cleanup;
1673 1674
    }

M
Matthias Bolte 已提交
1675 1676
    result = 0;

1677
 cleanup:
1678 1679 1680
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1681
    VIR_FREE(taskInfoErrorMessage);
1682 1683 1684 1685 1686 1687 1688

    return result;
}



static int
1689
esxDomainShutdownFlags(virDomainPtr domain, unsigned int flags)
1690
{
M
Matthias Bolte 已提交
1691
    int result = -1;
M
Matthias Bolte 已提交
1692
    esxPrivate *priv = domain->conn->privateData;
1693 1694 1695 1696
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1697 1698
    virCheckFlags(0, -1);

1699
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1700
        return -1;
1701

1702
    if (esxVI_String_AppendValueToList(&propertyNameList,
1703
                                       "runtime.powerState") < 0 ||
1704
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1705
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1706
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1707
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1708
        goto cleanup;
1709 1710 1711
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1712 1713
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1714
        goto cleanup;
1715 1716
    }

1717
    if (esxVI_ShutdownGuest(priv->primary, virtualMachine->obj) < 0)
M
Matthias Bolte 已提交
1718
        goto cleanup;
1719

M
Matthias Bolte 已提交
1720 1721
    result = 0;

1722
 cleanup:
1723 1724 1725 1726 1727 1728 1729
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}


1730 1731 1732 1733 1734 1735
static int
esxDomainShutdown(virDomainPtr domain)
{
    return esxDomainShutdownFlags(domain, 0);
}

1736 1737

static int
E
Eric Blake 已提交
1738
esxDomainReboot(virDomainPtr domain, unsigned int flags)
1739
{
M
Matthias Bolte 已提交
1740
    int result = -1;
M
Matthias Bolte 已提交
1741
    esxPrivate *priv = domain->conn->privateData;
1742 1743 1744 1745
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

E
Eric Blake 已提交
1746 1747
    virCheckFlags(0, -1);

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

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

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

1766
    if (esxVI_RebootGuest(priv->primary, virtualMachine->obj) < 0)
M
Matthias Bolte 已提交
1767
        goto cleanup;
1768

M
Matthias Bolte 已提交
1769 1770
    result = 0;

1771
 cleanup:
1772 1773 1774 1775 1776 1777 1778 1779 1780
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
1781 1782
esxDomainDestroyFlags(virDomainPtr domain,
                      unsigned int flags)
1783
{
M
Matthias Bolte 已提交
1784
    int result = -1;
M
Matthias Bolte 已提交
1785
    esxPrivate *priv = domain->conn->privateData;
1786
    esxVI_Context *ctx = NULL;
1787 1788 1789 1790 1791
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1792
    char *taskInfoErrorMessage = NULL;
1793

1794 1795
    virCheckFlags(0, -1);

1796
    if (priv->vCenter) {
1797 1798 1799 1800 1801
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

1802
    if (esxVI_EnsureSession(ctx) < 0)
M
Matthias Bolte 已提交
1803
        return -1;
1804

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

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1815 1816
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1817
        goto cleanup;
1818 1819
    }

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

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

1834
    domain->id = -1;
M
Matthias Bolte 已提交
1835 1836
    result = 0;

1837
 cleanup:
1838 1839 1840
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1841
    VIR_FREE(taskInfoErrorMessage);
1842 1843 1844 1845 1846

    return result;
}


1847 1848 1849 1850 1851 1852
static int
esxDomainDestroy(virDomainPtr dom)
{
    return esxDomainDestroyFlags(dom, 0);
}

1853 1854

static char *
1855
esxDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED)
1856
{
1857
    char *osType;
1858

1859
    ignore_value(VIR_STRDUP(osType, "hvm"));
1860
    return osType;
1861 1862 1863 1864
}



1865
static unsigned long long
1866 1867
esxDomainGetMaxMemory(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1868
    esxPrivate *priv = domain->conn->privateData;
1869 1870 1871 1872 1873
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    unsigned long memoryMB = 0;

1874
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1875
        return 0;
1876

1877
    if (esxVI_String_AppendValueToList(&propertyNameList,
1878
                                       "config.hardware.memoryMB") < 0 ||
1879
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1880
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1881
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
1882
        goto cleanup;
1883 1884
    }

1885
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
1886 1887
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
1888
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1889
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1890
                goto cleanup;
1891 1892 1893
            }

            if (dynamicProperty->val->int32 < 0) {
1894 1895 1896
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Got invalid memory size %d"),
                               dynamicProperty->val->int32);
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
            } else {
                memoryMB = dynamicProperty->val->int32;
            }

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

1907
 cleanup:
1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918
    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 已提交
1919
    int result = -1;
M
Matthias Bolte 已提交
1920
    esxPrivate *priv = domain->conn->privateData;
1921
    esxVI_String *propertyNameList = NULL;
1922
    esxVI_ObjectContent *virtualMachine = NULL;
1923
    esxVI_VirtualMachinePowerState powerState;
1924 1925 1926
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1927
    char *taskInfoErrorMessage = NULL;
1928

1929
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1930
        return -1;
1931

1932 1933 1934 1935
    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "runtime.powerState") < 0 ||
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1936
           priv->parsedUri->autoAnswer) < 0 ||
1937 1938 1939 1940 1941
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
1942 1943
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered off"));
1944 1945 1946 1947
        goto cleanup;
    }

    if (esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
1948
        esxVI_Long_Alloc(&spec->memoryMB) < 0) {
M
Matthias Bolte 已提交
1949
        goto cleanup;
1950 1951
    }

1952
    /* max-memory must be a multiple of 4096 kilobyte */
1953
    spec->memoryMB->value =
1954
      VIR_DIV_UP(memory, 4096) * 4; /* Scale from kilobytes to megabytes */
1955

1956
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
1957
                              &task) < 0 ||
1958
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1959
                                    esxVI_Occurrence_RequiredItem,
1960
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1961
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1962
        goto cleanup;
1963 1964 1965
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1966 1967 1968
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set max-memory to %lu kilobytes: %s"), memory,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
1969
        goto cleanup;
1970 1971
    }

M
Matthias Bolte 已提交
1972 1973
    result = 0;

1974
 cleanup:
1975
    esxVI_String_Free(&propertyNameList);
1976 1977 1978
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
1979
    VIR_FREE(taskInfoErrorMessage);
1980 1981 1982 1983 1984 1985 1986 1987 1988

    return result;
}



static int
esxDomainSetMemory(virDomainPtr domain, unsigned long memory)
{
M
Matthias Bolte 已提交
1989
    int result = -1;
M
Matthias Bolte 已提交
1990
    esxPrivate *priv = domain->conn->privateData;
1991 1992 1993 1994
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1995
    char *taskInfoErrorMessage = NULL;
1996

1997
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
1998
        return -1;
1999

2000
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2001
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2002
           priv->parsedUri->autoAnswer) < 0 ||
2003 2004 2005
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0 ||
        esxVI_Long_Alloc(&spec->memoryAllocation->limit) < 0) {
M
Matthias Bolte 已提交
2006
        goto cleanup;
2007 2008 2009
    }

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

2012
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2013
                              &task) < 0 ||
2014
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2015
                                    esxVI_Occurrence_RequiredItem,
2016
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2017
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2018
        goto cleanup;
2019 2020 2021
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2022 2023 2024
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set memory to %lu kilobytes: %s"), memory,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2025
        goto cleanup;
2026 2027
    }

M
Matthias Bolte 已提交
2028 2029
    result = 0;

2030
 cleanup:
2031 2032 2033
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2034
    VIR_FREE(taskInfoErrorMessage);
2035 2036 2037 2038 2039 2040

    return result;
}



2041 2042 2043 2044 2045 2046 2047 2048 2049
/*
 * 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

2050 2051 2052
static int
esxDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info)
{
M
Matthias Bolte 已提交
2053
    int result = -1;
M
Matthias Bolte 已提交
2054
    esxPrivate *priv = domain->conn->privateData;
2055 2056 2057 2058 2059
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int64_t memory_limit = -1;
2060
#if ESX_QUERY_FOR_USED_CPU_TIME
2061 2062 2063 2064 2065 2066 2067
    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;
2068 2069
    esxVI_PerfEntityMetricBase *perfEntityMetricBase = NULL;
    esxVI_PerfEntityMetricBase *perfEntityMetricBaseList = NULL;
2070 2071 2072
    esxVI_PerfEntityMetric *perfEntityMetric = NULL;
    esxVI_PerfMetricIntSeries *perfMetricIntSeries = NULL;
    esxVI_Long *value = NULL;
2073
#endif
2074

2075
    memset(info, 0, sizeof(*info));
M
Matthias Bolte 已提交
2076

2077
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
2078
        return -1;
2079

2080
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2081 2082 2083 2084
                                           "runtime.powerState\0"
                                           "config.hardware.memoryMB\0"
                                           "config.hardware.numCPU\0"
                                           "config.memoryAllocation.limit\0") < 0 ||
2085
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2086
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2087
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2088
        goto cleanup;
2089 2090 2091 2092
    }

    info->state = VIR_DOMAIN_NOSTATE;

2093
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
2094 2095 2096
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.powerState")) {
            if (esxVI_VirtualMachinePowerState_CastFromAnyType
2097
                  (dynamicProperty->val, &powerState) < 0) {
M
Matthias Bolte 已提交
2098
                goto cleanup;
2099 2100
            }

2101 2102
            info->state = esxVI_VirtualMachinePowerState_ConvertToLibvirt
                            (powerState);
2103
        } else if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2104
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2105
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2106
                goto cleanup;
2107 2108 2109 2110
            }

            info->maxMem = dynamicProperty->val->int32 * 1024; /* Scale from megabyte to kilobyte */
        } else if (STREQ(dynamicProperty->name, "config.hardware.numCPU")) {
2111
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2112
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2113
                goto cleanup;
2114 2115 2116 2117 2118
            }

            info->nrVirtCpu = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "config.memoryAllocation.limit")) {
2119
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2120
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
2121
                goto cleanup;
2122 2123 2124 2125
            }

            memory_limit = dynamicProperty->val->int64;

2126
            if (memory_limit > 0)
2127 2128 2129 2130 2131 2132 2133 2134 2135
                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;

2136
#if ESX_QUERY_FOR_USED_CPU_TIME
2137
    /* Verify the cached 'used CPU time' performance counter ID */
2138
    /* FIXME: Currently no host for a vpx:// connection */
2139
    if (priv->host) {
2140
        if (info->state == VIR_DOMAIN_RUNNING && priv->usedCpuTimeCounterId >= 0) {
2141
            if (esxVI_Int_Alloc(&counterId) < 0)
2142
                goto cleanup;
2143

2144
            counterId->value = priv->usedCpuTimeCounterId;
2145

2146
            if (esxVI_Int_AppendToList(&counterIdList, counterId) < 0)
2147
                goto cleanup;
2148

2149 2150 2151 2152
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfo) < 0) {
                goto cleanup;
            }
2153

2154 2155 2156 2157 2158
            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);
2159

2160 2161 2162 2163 2164
                priv->usedCpuTimeCounterId = -1;
            }

            esxVI_Int_Free(&counterIdList);
            esxVI_PerfCounterInfo_Free(&perfCounterInfo);
2165 2166
        }

2167 2168 2169 2170 2171 2172 2173 2174 2175 2176
        /*
         * 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;
            }
2177

2178
            for (perfMetricId = perfMetricIdList; perfMetricId;
2179 2180 2181
                 perfMetricId = perfMetricId->_next) {
                VIR_DEBUG("perfMetricId counterId %d, instance '%s'",
                          perfMetricId->counterId->value, perfMetricId->instance);
2182

2183
                counterId = NULL;
2184

2185 2186 2187 2188 2189
                if (esxVI_Int_DeepCopy(&counterId, perfMetricId->counterId) < 0 ||
                    esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                    goto cleanup;
                }
            }
2190

2191 2192
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfoList) < 0) {
M
Matthias Bolte 已提交
2193
                goto cleanup;
2194 2195
            }

2196
            for (perfCounterInfo = perfCounterInfoList; perfCounterInfo;
2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212
                 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;
                }
2213 2214
            }

2215
            if (priv->usedCpuTimeCounterId < 0)
2216
                VIR_WARN("Could not find 'used CPU time' performance counter");
2217 2218
        }

2219 2220 2221 2222 2223 2224
        /*
         * 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);
2225

2226 2227 2228 2229 2230 2231
            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;
            }
2232

2233 2234 2235 2236 2237 2238 2239 2240 2241 2242
            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;
            }
2243

2244
            for (perfEntityMetricBase = perfEntityMetricBaseList;
2245
                 perfEntityMetricBase;
2246
                 perfEntityMetricBase = perfEntityMetricBase->_next) {
2247
                VIR_DEBUG("perfEntityMetric ...");
2248

2249 2250
                perfEntityMetric =
                  esxVI_PerfEntityMetric_DynamicCast(perfEntityMetricBase);
2251

2252
                if (!perfEntityMetric) {
2253 2254 2255
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("QueryPerf returned object with unexpected type '%s'"),
                                   esxVI_Type_ToString(perfEntityMetricBase->_type));
2256
                    goto cleanup;
2257
                }
2258

2259 2260
                perfMetricIntSeries =
                  esxVI_PerfMetricIntSeries_DynamicCast(perfEntityMetric->value);
2261

2262
                if (!perfMetricIntSeries) {
2263 2264 2265
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("QueryPerf returned object with unexpected type '%s'"),
                                   esxVI_Type_ToString(perfEntityMetric->value->_type));
2266
                    goto cleanup;
2267
                }
2268

2269
                for (; perfMetricIntSeries;
2270
                     perfMetricIntSeries = perfMetricIntSeries->_next) {
2271
                    VIR_DEBUG("perfMetricIntSeries ...");
2272

2273
                    for (value = perfMetricIntSeries->value;
2274
                         value;
2275 2276 2277
                         value = value->_next) {
                        VIR_DEBUG("value %lld", (long long int)value->value);
                    }
2278 2279 2280
                }
            }

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

2283
            /*
E
Eric Blake 已提交
2284
             * FIXME: Cannot map between relative used-cpu-time and absolute
2285 2286 2287
             *        info->cpuTime
             */
        }
2288
    }
2289
#endif
2290

M
Matthias Bolte 已提交
2291 2292
    result = 0;

2293
 cleanup:
2294
#if ESX_QUERY_FOR_USED_CPU_TIME
2295 2296 2297 2298
    /*
     * Remove values owned by data structures to prevent them from being freed
     * by the call to esxVI_PerfQuerySpec_Free().
     */
2299
    if (querySpec) {
2300 2301 2302
        querySpec->entity = NULL;
        querySpec->format = NULL;

2303
        if (querySpec->metricId)
2304 2305
            querySpec->metricId->instance = NULL;
    }
2306
#endif
2307

2308 2309
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2310
#if ESX_QUERY_FOR_USED_CPU_TIME
2311 2312 2313 2314
    esxVI_PerfMetricId_Free(&perfMetricIdList);
    esxVI_Int_Free(&counterIdList);
    esxVI_PerfCounterInfo_Free(&perfCounterInfoList);
    esxVI_PerfQuerySpec_Free(&querySpec);
2315
    esxVI_PerfEntityMetricBase_Free(&perfEntityMetricBaseList);
2316
#endif
2317 2318 2319 2320 2321 2322

    return result;
}



2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336
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);

2337
    if (esxVI_EnsureSession(priv->primary) < 0)
2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355
        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;

2356
 cleanup:
2357 2358 2359 2360 2361 2362 2363 2364
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
}



2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442
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;
}



2443
static int
2444 2445
esxDomainSetVcpusFlags(virDomainPtr domain, unsigned int nvcpus,
                       unsigned int flags)
2446
{
M
Matthias Bolte 已提交
2447
    int result = -1;
M
Matthias Bolte 已提交
2448
    esxPrivate *priv = domain->conn->privateData;
M
Matthias Bolte 已提交
2449
    int maxVcpus;
2450 2451 2452 2453
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2454
    char *taskInfoErrorMessage = NULL;
2455

2456
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE, -1);
2457

2458
    if (nvcpus < 1) {
2459 2460
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Requested number of virtual CPUs must at least be 1"));
M
Matthias Bolte 已提交
2461
        return -1;
2462 2463
    }

2464
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
2465
        return -1;
2466

M
Matthias Bolte 已提交
2467
    maxVcpus = esxDomainGetMaxVcpus(domain);
2468

2469
    if (maxVcpus < 0)
M
Matthias Bolte 已提交
2470
        return -1;
2471

M
Matthias Bolte 已提交
2472
    if (nvcpus > maxVcpus) {
2473 2474 2475 2476
        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 已提交
2477
        return -1;
2478 2479
    }

2480
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2481
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2482
           priv->parsedUri->autoAnswer) < 0 ||
2483 2484
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Int_Alloc(&spec->numCPUs) < 0) {
M
Matthias Bolte 已提交
2485
        goto cleanup;
2486 2487 2488 2489
    }

    spec->numCPUs->value = nvcpus;

2490
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2491
                              &task) < 0 ||
2492
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2493
                                    esxVI_Occurrence_RequiredItem,
2494
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2495
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2496
        goto cleanup;
2497 2498 2499
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2500 2501 2502
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set number of virtual CPUs to %d: %s"), nvcpus,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2503
        goto cleanup;
2504 2505
    }

M
Matthias Bolte 已提交
2506 2507
    result = 0;

2508
 cleanup:
2509 2510 2511
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2512
    VIR_FREE(taskInfoErrorMessage);
2513 2514 2515 2516 2517

    return result;
}


M
Matthias Bolte 已提交
2518

2519 2520 2521
static int
esxDomainSetVcpus(virDomainPtr domain, unsigned int nvcpus)
{
2522
    return esxDomainSetVcpusFlags(domain, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
2523 2524
}

2525

M
Matthias Bolte 已提交
2526

2527
static int
2528
esxDomainGetVcpusFlags(virDomainPtr domain, unsigned int flags)
2529
{
M
Matthias Bolte 已提交
2530
    esxPrivate *priv = domain->conn->privateData;
2531 2532 2533 2534
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

2535 2536
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);
2537

2538
    if (priv->maxVcpus > 0)
M
Matthias Bolte 已提交
2539
        return priv->maxVcpus;
2540

M
Matthias Bolte 已提交
2541 2542
    priv->maxVcpus = -1;

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

2546
    if (esxVI_String_AppendValueToList(&propertyNameList,
2547
                                       "capability.maxSupportedVcpus") < 0 ||
2548 2549
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
2550
        goto cleanup;
2551 2552
    }

2553
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
2554 2555
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "capability.maxSupportedVcpus")) {
2556
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2557
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2558
                goto cleanup;
2559 2560
            }

M
Matthias Bolte 已提交
2561
            priv->maxVcpus = dynamicProperty->val->int32;
2562 2563 2564 2565 2566 2567
            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

2568
 cleanup:
2569 2570 2571
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
2572
    return priv->maxVcpus;
2573 2574
}

M
Matthias Bolte 已提交
2575 2576


2577 2578 2579
static int
esxDomainGetMaxVcpus(virDomainPtr domain)
{
2580
    return esxDomainGetVcpusFlags(domain, (VIR_DOMAIN_AFFECT_LIVE |
2581 2582
                                           VIR_DOMAIN_VCPU_MAXIMUM));
}
2583

M
Matthias Bolte 已提交
2584 2585


2586
static char *
2587
esxDomainGetXMLDesc(virDomainPtr domain, unsigned int flags)
2588
{
M
Matthias Bolte 已提交
2589
    esxPrivate *priv = domain->conn->privateData;
2590 2591
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
2592 2593
    esxVI_VirtualMachinePowerState powerState;
    int id;
2594
    char *moref = NULL;
2595
    char *vmPathName = NULL;
2596
    char *datastoreName = NULL;
M
Matthias Bolte 已提交
2597
    char *directoryName = NULL;
2598
    char *directoryAndFileName = NULL;
2599
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
2600 2601
    char *url = NULL;
    char *vmx = NULL;
2602
    virVMXContext ctx;
2603
    esxVMX_Data data;
2604 2605 2606
    virDomainDefPtr def = NULL;
    char *xml = NULL;

2607
    virCheckFlags(VIR_DOMAIN_XML_COMMON_FLAGS, NULL);
E
Eric Blake 已提交
2608

2609
    memset(&data, 0, sizeof(data));
2610

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

2614 2615 2616
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "config.files.vmPathName\0"
                                           "runtime.powerState\0") < 0 ||
2617
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2618
                                         propertyNameList, &virtualMachine,
2619
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2620
        esxVI_GetVirtualMachineMORef(virtualMachine, &moref) < 0 ||
2621 2622
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0 ||
2623 2624
        esxVI_GetStringValue(virtualMachine, "config.files.vmPathName",
                             &vmPathName, esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2625
        goto cleanup;
2626 2627
    }

2628
    if (esxUtil_ParseDatastorePath(vmPathName, &datastoreName, &directoryName,
2629
                                   &directoryAndFileName) < 0) {
M
Matthias Bolte 已提交
2630
        goto cleanup;
2631 2632
    }

2633
    virBufferAsprintf(&buffer, "%s://%s:%d/folder/", priv->parsedUri->transport,
2634
                      domain->conn->uri->server, domain->conn->uri->port);
2635
    virBufferURIEncodeString(&buffer, directoryAndFileName);
2636
    virBufferAddLit(&buffer, "?dcPath=");
2637
    virBufferURIEncodeString(&buffer, priv->primary->datacenterPath);
2638 2639 2640
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

2641
    if (virBufferCheckError(&buffer) < 0)
M
Matthias Bolte 已提交
2642
        goto cleanup;
2643

2644 2645
    url = virBufferContentAndReset(&buffer);

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

2649
    data.ctx = priv->primary;
2650

2651
    if (!directoryName) {
2652
        if (virAsprintf(&data.datastorePathWithoutFileName, "[%s]",
2653
                        datastoreName) < 0)
2654 2655 2656
            goto cleanup;
    } else {
        if (virAsprintf(&data.datastorePathWithoutFileName, "[%s] %s",
2657
                        datastoreName, directoryName) < 0)
2658 2659
            goto cleanup;
    }
2660 2661 2662 2663 2664

    ctx.opaque = &data;
    ctx.parseFileName = esxParseVMXFileName;
    ctx.formatFileName = NULL;
    ctx.autodetectSCSIControllerModel = NULL;
2665
    ctx.datacenterPath = priv->primary->datacenterPath;
2666
    ctx.moref = moref;
2667

2668
    def = virVMXParseConfig(&ctx, priv->xmlopt, priv->caps, vmx);
2669

2670
    if (def) {
2671
        if (powerState != esxVI_VirtualMachinePowerState_PoweredOff)
2672 2673
            def->id = id;

2674
        xml = virDomainDefFormat(def, priv->caps,
2675
                                 virDomainDefFormatConvertXMLFlags(flags));
2676 2677
    }

2678
 cleanup:
2679
    if (!url)
M
Matthias Bolte 已提交
2680 2681
        virBufferFreeAndReset(&buffer);

2682 2683
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2684
    VIR_FREE(moref);
2685
    VIR_FREE(datastoreName);
M
Matthias Bolte 已提交
2686
    VIR_FREE(directoryName);
2687
    VIR_FREE(directoryAndFileName);
2688
    VIR_FREE(url);
2689
    VIR_FREE(data.datastorePathWithoutFileName);
2690
    VIR_FREE(vmx);
2691
    virDomainDefFree(def);
2692 2693 2694 2695 2696 2697 2698

    return xml;
}



static char *
2699 2700 2701
esxConnectDomainXMLFromNative(virConnectPtr conn, const char *nativeFormat,
                              const char *nativeConfig,
                              unsigned int flags)
2702
{
M
Matthias Bolte 已提交
2703
    esxPrivate *priv = conn->privateData;
2704
    virVMXContext ctx;
2705
    esxVMX_Data data;
2706 2707 2708
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2709 2710
    virCheckFlags(0, NULL);

2711
    memset(&data, 0, sizeof(data));
2712

2713
    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2714 2715
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Unsupported config format '%s'"), nativeFormat);
2716
        return NULL;
2717 2718
    }

2719
    data.ctx = priv->primary;
2720
    data.datastorePathWithoutFileName = (char *)"[?] ?";
2721 2722 2723 2724 2725

    ctx.opaque = &data;
    ctx.parseFileName = esxParseVMXFileName;
    ctx.formatFileName = NULL;
    ctx.autodetectSCSIControllerModel = NULL;
2726
    ctx.datacenterPath = NULL;
2727
    ctx.moref = NULL;
2728

2729
    def = virVMXParseConfig(&ctx, priv->xmlopt, priv->caps, nativeConfig);
2730

2731
    if (def)
2732 2733
        xml = virDomainDefFormat(def, priv->caps,
                                 VIR_DOMAIN_DEF_FORMAT_INACTIVE);
2734 2735 2736 2737 2738 2739 2740 2741

    virDomainDefFree(def);

    return xml;
}



M
Matthias Bolte 已提交
2742
static char *
2743 2744 2745
esxConnectDomainXMLToNative(virConnectPtr conn, const char *nativeFormat,
                            const char *domainXml,
                            unsigned int flags)
M
Matthias Bolte 已提交
2746
{
M
Matthias Bolte 已提交
2747
    esxPrivate *priv = conn->privateData;
2748 2749
    int virtualHW_version;
    virVMXContext ctx;
2750
    esxVMX_Data data;
M
Matthias Bolte 已提交
2751 2752 2753
    virDomainDefPtr def = NULL;
    char *vmx = NULL;

E
Eric Blake 已提交
2754 2755
    virCheckFlags(0, NULL);

2756
    memset(&data, 0, sizeof(data));
2757

M
Matthias Bolte 已提交
2758
    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2759 2760
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Unsupported config format '%s'"), nativeFormat);
M
Matthias Bolte 已提交
2761 2762 2763
        return NULL;
    }

2764
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
2765
                          (priv->primary->productLine, priv->primary->productVersion);
2766

2767
    if (virtualHW_version < 0)
2768 2769
        return NULL;

2770
    def = virDomainDefParseString(domainXml, priv->caps, priv->xmlopt,
2771
                                  NULL, VIR_DOMAIN_DEF_PARSE_INACTIVE);
M
Matthias Bolte 已提交
2772

2773
    if (!def)
M
Matthias Bolte 已提交
2774 2775
        return NULL;

2776
    data.ctx = priv->primary;
2777
    data.datastorePathWithoutFileName = NULL;
2778 2779 2780 2781 2782

    ctx.opaque = &data;
    ctx.parseFileName = NULL;
    ctx.formatFileName = esxFormatVMXFileName;
    ctx.autodetectSCSIControllerModel = esxAutodetectSCSIControllerModel;
2783
    ctx.datacenterPath = NULL;
2784
    ctx.moref = NULL;
2785

2786
    vmx = virVMXFormatConfig(&ctx, priv->xmlopt, def, virtualHW_version);
M
Matthias Bolte 已提交
2787 2788 2789 2790 2791 2792 2793 2794

    virDomainDefFree(def);

    return vmx;
}



2795
static int
2796
esxConnectListDefinedDomains(virConnectPtr conn, char **const names, int maxnames)
2797
{
M
Matthias Bolte 已提交
2798
    bool success = false;
M
Matthias Bolte 已提交
2799
    esxPrivate *priv = conn->privateData;
2800 2801 2802 2803 2804
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;
2805
    size_t i;
2806

2807
    if (maxnames == 0)
2808 2809
        return 0;

2810
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
2811
        return -1;
2812

2813
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2814 2815
                                           "name\0"
                                           "runtime.powerState\0") < 0 ||
2816 2817
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2818
        goto cleanup;
2819 2820
    }

2821
    for (virtualMachine = virtualMachineList; virtualMachine;
2822
         virtualMachine = virtualMachine->_next) {
2823
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
2824
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
2825
            goto cleanup;
2826 2827
        }

2828
        if (powerState == esxVI_VirtualMachinePowerState_PoweredOn)
2829 2830
            continue;

2831
        names[count] = NULL;
2832

2833 2834 2835
        if (esxVI_GetVirtualMachineIdentity(virtualMachine, NULL, &names[count],
                                            NULL) < 0) {
            goto cleanup;
2836 2837
        }

2838 2839
        ++count;

2840
        if (count >= maxnames)
2841 2842 2843
            break;
    }

M
Matthias Bolte 已提交
2844
    success = true;
2845

2846
 cleanup:
M
Matthias Bolte 已提交
2847
    if (! success) {
2848
        for (i = 0; i < count; ++i)
M
Matthias Bolte 已提交
2849
            VIR_FREE(names[i]);
2850

M
Matthias Bolte 已提交
2851
        count = -1;
2852 2853
    }

M
Matthias Bolte 已提交
2854 2855
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
2856

M
Matthias Bolte 已提交
2857
    return count;
2858 2859 2860 2861 2862
}



static int
2863
esxConnectNumOfDefinedDomains(virConnectPtr conn)
2864
{
M
Matthias Bolte 已提交
2865
    esxPrivate *priv = conn->privateData;
2866

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

2870
    return esxVI_LookupNumberOfDomainsByPowerState
2871
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, true);
2872 2873 2874 2875 2876
}



static int
2877
esxDomainCreateWithFlags(virDomainPtr domain, unsigned int flags)
2878
{
M
Matthias Bolte 已提交
2879
    int result = -1;
M
Matthias Bolte 已提交
2880
    esxPrivate *priv = domain->conn->privateData;
2881 2882 2883
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
2884
    int id = -1;
2885 2886
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2887
    char *taskInfoErrorMessage = NULL;
2888

2889 2890
    virCheckFlags(0, -1);

2891
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
2892
        return -1;
2893

2894
    if (esxVI_String_AppendValueToList(&propertyNameList,
2895
                                       "runtime.powerState") < 0 ||
2896
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2897
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
2898
           priv->parsedUri->autoAnswer) < 0 ||
2899 2900
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0) {
M
Matthias Bolte 已提交
2901
        goto cleanup;
2902 2903 2904
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2905 2906
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered off"));
M
Matthias Bolte 已提交
2907
        goto cleanup;
2908 2909
    }

2910
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
2911
                             &task) < 0 ||
2912
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2913
                                    esxVI_Occurrence_RequiredItem,
2914
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2915
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2916
        goto cleanup;
2917 2918 2919
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2920 2921
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not start domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2922
        goto cleanup;
2923 2924
    }

2925
    domain->id = id;
M
Matthias Bolte 已提交
2926 2927
    result = 0;

2928
 cleanup:
2929 2930 2931
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
2932
    VIR_FREE(taskInfoErrorMessage);
2933 2934 2935 2936

    return result;
}

2937 2938


2939 2940 2941 2942 2943
static int
esxDomainCreate(virDomainPtr domain)
{
    return esxDomainCreateWithFlags(domain, 0);
}
2944

2945 2946


M
Matthias Bolte 已提交
2947
static virDomainPtr
2948
esxDomainDefineXMLFlags(virConnectPtr conn, const char *xml, unsigned int flags)
M
Matthias Bolte 已提交
2949
{
M
Matthias Bolte 已提交
2950
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
2951 2952
    virDomainDefPtr def = NULL;
    char *vmx = NULL;
2953
    size_t i;
2954
    virDomainDiskDefPtr disk = NULL;
M
Matthias Bolte 已提交
2955
    esxVI_ObjectContent *virtualMachine = NULL;
2956 2957
    int virtualHW_version;
    virVMXContext ctx;
2958
    esxVMX_Data data;
M
Matthias Bolte 已提交
2959 2960
    char *datastoreName = NULL;
    char *directoryName = NULL;
2961
    char *escapedName = NULL;
M
Matthias Bolte 已提交
2962 2963 2964 2965 2966 2967 2968 2969
    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;
2970
    char *taskInfoErrorMessage = NULL;
M
Matthias Bolte 已提交
2971
    virDomainPtr domain = NULL;
2972
    const char *src;
2973
    unsigned int parse_flags = VIR_DOMAIN_DEF_PARSE_INACTIVE;
M
Matthias Bolte 已提交
2974

2975 2976 2977
    virCheckFlags(VIR_DOMAIN_DEFINE_VALIDATE, NULL);

    if (flags & VIR_DOMAIN_DEFINE_VALIDATE)
2978
        parse_flags |= VIR_DOMAIN_DEF_PARSE_VALIDATE_SCHEMA;
2979

2980
    memset(&data, 0, sizeof(data));
2981

2982
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
2983
        return NULL;
M
Matthias Bolte 已提交
2984 2985

    /* Parse domain XML */
2986
    def = virDomainDefParseString(xml, priv->caps, priv->xmlopt,
2987
                                  NULL, parse_flags);
M
Matthias Bolte 已提交
2988

2989
    if (!def)
M
Matthias Bolte 已提交
2990
        return NULL;
M
Matthias Bolte 已提交
2991

2992 2993 2994
    if (virXMLCheckIllegalChars("name", def->name, "\n") < 0)
        goto cleanup;

M
Matthias Bolte 已提交
2995
    /* Check if an existing domain should be edited */
2996
    if (esxVI_LookupVirtualMachineByUuid(priv->primary, def->uuid, NULL,
M
Matthias Bolte 已提交
2997
                                         &virtualMachine,
M
Matthias Bolte 已提交
2998
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
2999
        goto cleanup;
M
Matthias Bolte 已提交
3000 3001
    }

3002
    if (!virtualMachine &&
3003 3004 3005 3006 3007 3008
        esxVI_LookupVirtualMachineByName(priv->primary, def->name, NULL,
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
    }

3009
    if (virtualMachine) {
M
Matthias Bolte 已提交
3010
        /* FIXME */
3011 3012 3013
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Domain already exists, editing existing domains is not "
                         "supported yet"));
M
Matthias Bolte 已提交
3014
        goto cleanup;
M
Matthias Bolte 已提交
3015 3016 3017
    }

    /* Build VMX from domain XML */
3018
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
3019
                          (priv->primary->productLine, priv->primary->productVersion);
3020

3021
    if (virtualHW_version < 0)
3022 3023
        goto cleanup;

3024
    data.ctx = priv->primary;
3025
    data.datastorePathWithoutFileName = NULL;
3026 3027 3028 3029 3030

    ctx.opaque = &data;
    ctx.parseFileName = NULL;
    ctx.formatFileName = esxFormatVMXFileName;
    ctx.autodetectSCSIControllerModel = esxAutodetectSCSIControllerModel;
3031
    ctx.datacenterPath = NULL;
3032
    ctx.moref = NULL;
3033

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

3036
    if (!vmx)
M
Matthias Bolte 已提交
3037
        goto cleanup;
M
Matthias Bolte 已提交
3038

3039 3040 3041
    /*
     * 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 已提交
3042
     * first disk, because it may be CDROM disk and ISO images are normally not
3043 3044 3045
     * 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 已提交
3046
    if (def->ndisks < 1) {
3047 3048 3049
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Domain XML doesn't contain any disks, cannot deduce "
                         "datastore and path for VMX file"));
M
Matthias Bolte 已提交
3050
        goto cleanup;
3051 3052 3053 3054
    }

    for (i = 0; i < def->ndisks; ++i) {
        if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK &&
E
Eric Blake 已提交
3055
            virDomainDiskGetType(def->disks[i]) == VIR_STORAGE_TYPE_FILE) {
3056 3057 3058 3059 3060
            disk = def->disks[i];
            break;
        }
    }

3061
    if (!disk) {
3062 3063 3064
        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 已提交
3065
        goto cleanup;
M
Matthias Bolte 已提交
3066 3067
    }

3068 3069
    src = virDomainDiskGetSource(disk);
    if (!src) {
3070 3071 3072
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("First file-based harddisk has no source, cannot deduce "
                         "datastore and path for VMX file"));
M
Matthias Bolte 已提交
3073
        goto cleanup;
M
Matthias Bolte 已提交
3074 3075
    }

3076
    if (esxUtil_ParseDatastorePath(src, &datastoreName, &directoryName,
3077
                                   NULL) < 0) {
M
Matthias Bolte 已提交
3078
        goto cleanup;
M
Matthias Bolte 已提交
3079 3080
    }

3081
    if (! virFileHasSuffix(src, ".vmdk")) {
3082 3083
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Expecting source '%s' of first file-based harddisk to "
3084
                         "be a VMDK image"), src);
M
Matthias Bolte 已提交
3085
        goto cleanup;
M
Matthias Bolte 已提交
3086 3087
    }

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

3091
    if (directoryName) {
M
Matthias Bolte 已提交
3092 3093 3094 3095
        virBufferURIEncodeString(&buffer, directoryName);
        virBufferAddChar(&buffer, '/');
    }

3096 3097
    escapedName = esxUtil_EscapeDatastoreItem(def->name);

3098
    if (!escapedName)
3099 3100 3101
        goto cleanup;

    virBufferURIEncodeString(&buffer, escapedName);
M
Matthias Bolte 已提交
3102
    virBufferAddLit(&buffer, ".vmx?dcPath=");
3103
    virBufferURIEncodeString(&buffer, priv->primary->datacenterPath);
M
Matthias Bolte 已提交
3104 3105 3106
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

3107
    if (virBufferCheckError(&buffer) < 0)
M
Matthias Bolte 已提交
3108
        goto cleanup;
M
Matthias Bolte 已提交
3109 3110 3111

    url = virBufferContentAndReset(&buffer);

3112 3113 3114 3115 3116 3117
    /* Check, if VMX file already exists */
    /* FIXME */

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

3118
    if (esxVI_CURL_Upload(priv->primary->curl, url, vmx) < 0)
3119 3120 3121
        goto cleanup;

    /* Register the domain */
3122
    if (directoryName) {
M
Matthias Bolte 已提交
3123
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s/%s.vmx", datastoreName,
3124
                        directoryName, escapedName) < 0)
M
Matthias Bolte 已提交
3125
            goto cleanup;
M
Matthias Bolte 已提交
3126 3127
    } else {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s.vmx", datastoreName,
3128
                        escapedName) < 0)
M
Matthias Bolte 已提交
3129
            goto cleanup;
M
Matthias Bolte 已提交
3130 3131
    }

3132
    if (esxVI_RegisterVM_Task(priv->primary, priv->primary->datacenter->vmFolder,
M
Matthias Bolte 已提交
3133
                              datastoreRelatedPath, NULL, esxVI_Boolean_False,
3134 3135 3136 3137
                              priv->primary->computeResource->resourcePool,
                              priv->primary->hostSystem->_reference,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, def->uuid,
3138
                                    esxVI_Occurrence_OptionalItem,
3139
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3140
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3141
        goto cleanup;
M
Matthias Bolte 已提交
3142 3143 3144
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3145 3146
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not define domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3147
        goto cleanup;
M
Matthias Bolte 已提交
3148 3149
    }

3150
    domain = virGetDomain(conn, def->name, def->uuid, -1);
M
Matthias Bolte 已提交
3151 3152 3153

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

3154
 cleanup:
3155
    if (!url)
M
Matthias Bolte 已提交
3156 3157
        virBufferFreeAndReset(&buffer);

M
Matthias Bolte 已提交
3158 3159 3160 3161
    virDomainDefFree(def);
    VIR_FREE(vmx);
    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
3162
    VIR_FREE(escapedName);
M
Matthias Bolte 已提交
3163 3164 3165 3166 3167 3168 3169
    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);
3170
    VIR_FREE(taskInfoErrorMessage);
M
Matthias Bolte 已提交
3171 3172 3173 3174

    return domain;
}

3175 3176 3177 3178 3179
static virDomainPtr
esxDomainDefineXML(virConnectPtr conn, const char *xml)
{
    return esxDomainDefineXMLFlags(conn, xml, 0);
}
M
Matthias Bolte 已提交
3180

3181
static int
3182 3183
esxDomainUndefineFlags(virDomainPtr domain,
                       unsigned int flags)
3184
{
M
Matthias Bolte 已提交
3185
    int result = -1;
M
Matthias Bolte 已提交
3186
    esxPrivate *priv = domain->conn->privateData;
3187
    esxVI_Context *ctx = NULL;
3188 3189 3190 3191
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

3192 3193 3194 3195
    /* 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);
3196

3197
    if (priv->vCenter) {
3198 3199 3200 3201 3202
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

3203
    if (esxVI_EnsureSession(ctx) < 0)
M
Matthias Bolte 已提交
3204
        return -1;
3205

3206
    if (esxVI_String_AppendValueToList(&propertyNameList,
3207
                                       "runtime.powerState") < 0 ||
3208 3209
        esxVI_LookupVirtualMachineByUuid(ctx, domain->uuid, propertyNameList,
                                         &virtualMachine,
M
Matthias Bolte 已提交
3210
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3211
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
3212
        goto cleanup;
3213 3214 3215 3216
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended &&
        powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
3217 3218
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not suspended or powered off"));
M
Matthias Bolte 已提交
3219
        goto cleanup;
3220 3221
    }

3222
    if (esxVI_UnregisterVM(ctx, virtualMachine->obj) < 0)
M
Matthias Bolte 已提交
3223
        goto cleanup;
3224

M
Matthias Bolte 已提交
3225 3226
    result = 0;

3227
 cleanup:
3228 3229 3230 3231 3232 3233 3234
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}


3235 3236 3237 3238 3239
static int
esxDomainUndefine(virDomainPtr domain)
{
    return esxDomainUndefineFlags(domain, 0);
}
3240

3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253
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;

3254
    if (esxVI_EnsureSession(priv->primary) < 0)
3255 3256 3257
        return -1;

    /* Check general autostart config */
3258
    if (esxVI_LookupAutoStartDefaults(priv->primary, &defaults) < 0)
3259 3260 3261 3262 3263 3264 3265 3266 3267
        goto cleanup;

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

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

3271
    if (!powerInfoList) {
3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282
        /* 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;
    }

3283
    for (powerInfo = powerInfoList; powerInfo;
3284 3285
         powerInfo = powerInfo->_next) {
        if (STREQ(powerInfo->key->value, virtualMachine->obj->value)) {
3286
            if (STRCASEEQ(powerInfo->startAction, "powerOn"))
3287 3288 3289 3290 3291 3292 3293 3294
                *autostart = 1;

            break;
        }
    }

    result = 0;

3295
 cleanup:
3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317
    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;

3318
    if (esxVI_EnsureSession(priv->primary) < 0)
3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334
        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.
         */
3335
        if (esxVI_LookupAutoStartDefaults(priv->primary, &defaults) < 0)
3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349
            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;
            }

3350
            for (powerInfo = powerInfoList; powerInfo;
3351 3352
                 powerInfo = powerInfo->_next) {
                if (STRNEQ(powerInfo->key->value, virtualMachine->obj->value)) {
3353 3354 3355
                    virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                                   _("Cannot enable general autostart option "
                                     "without affecting other domains"));
3356 3357 3358 3359 3360
                    goto cleanup;
                }
            }

            /* Enable autostart in general */
3361
            if (esxVI_AutoStartDefaults_Alloc(&spec->defaults) < 0)
3362 3363 3364 3365 3366 3367 3368 3369 3370
                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 ||
3371 3372 3373 3374
        esxVI_Int_Alloc(&newPowerInfo->stopDelay) < 0 ||
        esxVI_AutoStartPowerInfo_AppendToList(&spec->powerInfo,
                                              newPowerInfo) < 0) {
        esxVI_AutoStartPowerInfo_Free(&newPowerInfo);
3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394
        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";

    if (esxVI_ReconfigureAutostart
          (priv->primary,
           priv->primary->hostSystem->configManager->autoStartManager,
           spec) < 0) {
        goto cleanup;
    }

    result = 0;

3395
 cleanup:
3396
    if (newPowerInfo) {
3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411
        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);

    return result;
}



3412 3413 3414 3415 3416 3417 3418 3419 3420 3421
/*
 * 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:
 *
3422
 * - reservation (VIR_TYPED_PARAM_LLONG >= 0, in megaherz)
3423
 *
3424
 *   The amount of CPU resource that is guaranteed to be available to the domain.
3425 3426
 *
 *
3427
 * - limit (VIR_TYPED_PARAM_LLONG >= 0, or -1, in megaherz)
3428
 *
3429 3430
 *   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
3431 3432 3433 3434
 *   utilization of the domain is unlimited. If the limit is not set to -1, it
 *   must be greater than or equal to the reservation.
 *
 *
3435
 * - shares (VIR_TYPED_PARAM_INT >= 0, or in {-1, -2, -3}, no unit)
3436 3437 3438 3439 3440 3441
 *
 *   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'.
 */
3442
static char *
3443
esxDomainGetSchedulerType(virDomainPtr domain ATTRIBUTE_UNUSED, int *nparams)
3444
{
3445
    char *type;
3446

3447
    if (VIR_STRDUP(type, "allocation") < 0)
3448
        return NULL;
3449

3450
    if (nparams)
3451
        *nparams = 3; /* reservation, limit, shares */
3452 3453 3454 3455 3456 3457 3458

    return type;
}



static int
3459 3460 3461
esxDomainGetSchedulerParametersFlags(virDomainPtr domain,
                                     virTypedParameterPtr params, int *nparams,
                                     unsigned int flags)
3462
{
M
Matthias Bolte 已提交
3463
    int result = -1;
M
Matthias Bolte 已提交
3464
    esxPrivate *priv = domain->conn->privateData;
3465 3466 3467 3468 3469
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    unsigned int mask = 0;
3470
    size_t i = 0;
3471

3472 3473
    virCheckFlags(0, -1);

3474
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
3475
        return -1;
3476

3477
    if (esxVI_String_AppendValueListToList(&propertyNameList,
3478 3479 3480
                                           "config.cpuAllocation.reservation\0"
                                           "config.cpuAllocation.limit\0"
                                           "config.cpuAllocation.shares\0") < 0 ||
3481
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
3482
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3483
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3484
        goto cleanup;
3485 3486 3487
    }

    for (dynamicProperty = virtualMachine->propSet;
3488
         dynamicProperty && mask != 7 && i < 3 && i < *nparams;
3489 3490
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.cpuAllocation.reservation") &&
M
Matthias Bolte 已提交
3491
            ! (mask & (1 << 0))) {
3492
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3493
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3494
                goto cleanup;
3495
            }
3496 3497 3498 3499 3500
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_SCHEDULER_RESERVATION,
                                        VIR_TYPED_PARAM_LLONG,
                                        dynamicProperty->val->int64) < 0)
                goto cleanup;
3501 3502 3503 3504
            mask |= 1 << 0;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.limit") &&
M
Matthias Bolte 已提交
3505
                   ! (mask & (1 << 1))) {
3506
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3507
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3508
                goto cleanup;
3509
            }
3510 3511 3512 3513 3514
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_SCHEDULER_LIMIT,
                                        VIR_TYPED_PARAM_LLONG,
                                        dynamicProperty->val->int64) < 0)
                goto cleanup;
3515 3516 3517 3518
            mask |= 1 << 1;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.shares") &&
M
Matthias Bolte 已提交
3519
                   ! (mask & (1 << 2))) {
3520 3521 3522 3523
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_SCHEDULER_SHARES,
                                        VIR_TYPED_PARAM_INT, 0) < 0)
                goto cleanup;
3524
            if (esxVI_SharesInfo_CastFromAnyType(dynamicProperty->val,
3525
                                                 &sharesInfo) < 0) {
M
Matthias Bolte 已提交
3526
                goto cleanup;
3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545
            }

            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;

3546
              case esxVI_SharesLevel_Undefined:
3547
              default:
3548
                virReportEnumRangeError(esxVI_SharesLevel, sharesInfo->level);
3549
                esxVI_SharesInfo_Free(&sharesInfo);
M
Matthias Bolte 已提交
3550
                goto cleanup;
3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562
            }

            esxVI_SharesInfo_Free(&sharesInfo);

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

    *nparams = i;
M
Matthias Bolte 已提交
3563
    result = 0;
3564

3565
 cleanup:
3566 3567 3568 3569 3570 3571
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
}

3572 3573 3574 3575 3576 3577
static int
esxDomainGetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int *nparams)
{
    return esxDomainGetSchedulerParametersFlags(domain, params, nparams, 0);
}
3578 3579 3580


static int
3581 3582 3583
esxDomainSetSchedulerParametersFlags(virDomainPtr domain,
                                     virTypedParameterPtr params, int nparams,
                                     unsigned int flags)
3584
{
M
Matthias Bolte 已提交
3585
    int result = -1;
M
Matthias Bolte 已提交
3586
    esxPrivate *priv = domain->conn->privateData;
3587 3588 3589 3590 3591
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3592
    char *taskInfoErrorMessage = NULL;
3593
    size_t i;
3594

3595
    virCheckFlags(0, -1);
3596 3597 3598 3599 3600 3601 3602 3603
    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)
3604
        return -1;
3605

3606
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
3607
        return -1;
3608

3609
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3610
          (priv->primary, domain->uuid, NULL, &virtualMachine,
3611
           priv->parsedUri->autoAnswer) < 0 ||
3612 3613
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->cpuAllocation) < 0) {
M
Matthias Bolte 已提交
3614
        goto cleanup;
3615 3616 3617
    }

    for (i = 0; i < nparams; ++i) {
3618
        if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_RESERVATION)) {
3619
            if (esxVI_Long_Alloc(&spec->cpuAllocation->reservation) < 0)
M
Matthias Bolte 已提交
3620
                goto cleanup;
3621 3622

            if (params[i].value.l < 0) {
3623 3624 3625
                virReportError(VIR_ERR_INVALID_ARG,
                               _("Could not set reservation to %lld MHz, expecting "
                                 "positive value"), params[i].value.l);
M
Matthias Bolte 已提交
3626
                goto cleanup;
3627 3628 3629
            }

            spec->cpuAllocation->reservation->value = params[i].value.l;
3630
        } else if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_LIMIT)) {
3631
            if (esxVI_Long_Alloc(&spec->cpuAllocation->limit) < 0)
M
Matthias Bolte 已提交
3632
                goto cleanup;
3633 3634

            if (params[i].value.l < -1) {
3635 3636 3637 3638
                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 已提交
3639
                goto cleanup;
3640 3641 3642
            }

            spec->cpuAllocation->limit->value = params[i].value.l;
3643
        } else if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_SHARES)) {
3644 3645
            if (esxVI_SharesInfo_Alloc(&sharesInfo) < 0 ||
                esxVI_Int_Alloc(&sharesInfo->shares) < 0) {
M
Matthias Bolte 已提交
3646
                goto cleanup;
3647 3648 3649
            }

            spec->cpuAllocation->shares = sharesInfo;
3650
            sharesInfo = NULL;
3651

3652
            if (params[i].value.i >= 0) {
3653
                spec->cpuAllocation->shares->level = esxVI_SharesLevel_Custom;
3654
                spec->cpuAllocation->shares->shares->value = params[i].value.i;
3655
            } else {
3656
                switch (params[i].value.i) {
3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674
                  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:
3675 3676 3677 3678
                    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 已提交
3679
                    goto cleanup;
3680 3681 3682 3683 3684
                }
            }
        }
    }

3685
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
3686
                              &task) < 0 ||
3687
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3688
                                    esxVI_Occurrence_RequiredItem,
3689
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3690
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3691
        goto cleanup;
3692 3693 3694
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3695 3696 3697
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not change scheduler parameters: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3698
        goto cleanup;
3699 3700
    }

M
Matthias Bolte 已提交
3701 3702
    result = 0;

3703
 cleanup:
3704
    esxVI_SharesInfo_Free(&sharesInfo);
3705 3706 3707
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
3708
    VIR_FREE(taskInfoErrorMessage);
3709 3710 3711 3712

    return result;
}

3713 3714 3715 3716 3717 3718
static int
esxDomainSetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int nparams)
{
    return esxDomainSetSchedulerParametersFlags(domain, params, nparams, 0);
}
3719

E
Eric Blake 已提交
3720
/* The subset of migration flags we are able to support.  */
3721 3722 3723 3724
#define ESX_MIGRATION_FLAGS \
    (VIR_MIGRATE_PERSIST_DEST | \
     VIR_MIGRATE_UNDEFINE_SOURCE | \
     VIR_MIGRATE_LIVE | \
E
Eric Blake 已提交
3725
     VIR_MIGRATE_PAUSED)
3726 3727 3728 3729 3730

static int
esxDomainMigratePrepare(virConnectPtr dconn,
                        char **cookie ATTRIBUTE_UNUSED,
                        int *cookielen ATTRIBUTE_UNUSED,
3731 3732
                        const char *uri_in ATTRIBUTE_UNUSED,
                        char **uri_out,
E
Eric Blake 已提交
3733
                        unsigned long flags,
3734 3735 3736
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
3737
    esxPrivate *priv = dconn->privateData;
3738

E
Eric Blake 已提交
3739 3740
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

3741
    if (!uri_in) {
3742 3743 3744
        if (virAsprintf(uri_out, "vpxmigr://%s/%s/%s",
                        priv->vCenter->ipAddress,
                        priv->vCenter->computeResource->resourcePool->value,
3745
                        priv->vCenter->hostSystem->_reference->value) < 0)
3746
            return -1;
3747 3748
    }

3749
    return 0;
3750 3751 3752 3753 3754 3755 3756 3757 3758
}



static int
esxDomainMigratePerform(virDomainPtr domain,
                        const char *cookie ATTRIBUTE_UNUSED,
                        int cookielen ATTRIBUTE_UNUSED,
                        const char *uri,
E
Eric Blake 已提交
3759
                        unsigned long flags,
3760 3761 3762
                        const char *dname,
                        unsigned long bandwidth ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
3763
    int result = -1;
M
Matthias Bolte 已提交
3764
    esxPrivate *priv = domain->conn->privateData;
M
Martin Kletzander 已提交
3765
    virURIPtr parsedUri = NULL;
3766 3767 3768
    char *saveptr;
    char *path_resourcePool;
    char *path_hostSystem;
3769
    esxVI_ObjectContent *virtualMachine = NULL;
3770 3771
    esxVI_ManagedObjectReference resourcePool;
    esxVI_ManagedObjectReference hostSystem;
3772 3773 3774
    esxVI_Event *eventList = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3775
    char *taskInfoErrorMessage = NULL;
3776

E
Eric Blake 已提交
3777 3778
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

3779
    if (!priv->vCenter) {
3780 3781
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration not possible without a vCenter"));
M
Matthias Bolte 已提交
3782
        return -1;
3783 3784
    }

3785
    if (dname) {
3786 3787
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Renaming domains on migration not supported"));
M
Matthias Bolte 已提交
3788
        return -1;
3789 3790
    }

3791
    if (esxVI_EnsureSession(priv->vCenter) < 0)
M
Matthias Bolte 已提交
3792
        return -1;
3793

3794
    /* Parse migration URI */
3795
    if (!(parsedUri = virURIParse(uri)))
M
Matthias Bolte 已提交
3796
        return -1;
3797

3798
    if (!parsedUri->scheme || STRCASENEQ(parsedUri->scheme, "vpxmigr")) {
3799 3800
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Only vpxmigr:// migration URIs are supported"));
M
Matthias Bolte 已提交
3801
        goto cleanup;
3802 3803
    }

3804
    if (STRCASENEQ(priv->vCenter->ipAddress, parsedUri->server)) {
3805 3806 3807
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration source and destination have to refer to "
                         "the same vCenter"));
3808 3809 3810 3811 3812 3813
        goto cleanup;
    }

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

3814
    if (!path_resourcePool || !path_hostSystem) {
3815 3816
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration URI has to specify resource pool and host system"));
M
Matthias Bolte 已提交
3817
        goto cleanup;
3818 3819
    }

3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832
    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,
3833
           priv->parsedUri->autoAnswer) < 0) {
M
Matthias Bolte 已提交
3834
        goto cleanup;
3835 3836 3837
    }

    /* Validate the purposed migration */
3838
    if (esxVI_ValidateMigration(priv->vCenter, virtualMachine->obj,
3839 3840
                                esxVI_VirtualMachinePowerState_Undefined, NULL,
                                &resourcePool, &hostSystem, &eventList) < 0) {
M
Matthias Bolte 已提交
3841
        goto cleanup;
3842 3843
    }

3844
    if (eventList) {
3845 3846 3847 3848
        /*
         * FIXME: Need to report the complete list of events. Limit reporting
         *        to the first event for now.
         */
3849
        if (eventList->fullFormattedMessage) {
3850 3851 3852
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not migrate domain, validation reported a "
                             "problem: %s"), eventList->fullFormattedMessage);
3853
        } else {
3854 3855 3856
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Could not migrate domain, validation reported a "
                             "problem"));
3857 3858
        }

M
Matthias Bolte 已提交
3859
        goto cleanup;
3860 3861 3862
    }

    /* Perform the purposed migration */
3863 3864
    if (esxVI_MigrateVM_Task(priv->vCenter, virtualMachine->obj,
                             &resourcePool, &hostSystem,
3865 3866 3867
                             esxVI_VirtualMachineMovePriority_DefaultPriority,
                             esxVI_VirtualMachinePowerState_Undefined,
                             &task) < 0 ||
3868
        esxVI_WaitForTaskCompletion(priv->vCenter, task, domain->uuid,
3869
                                    esxVI_Occurrence_RequiredItem,
3870
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3871
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3872
        goto cleanup;
3873 3874 3875
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3876 3877 3878 3879
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not migrate domain, migration task finished with "
                         "an error: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3880
        goto cleanup;
3881 3882
    }

M
Matthias Bolte 已提交
3883 3884
    result = 0;

3885
 cleanup:
3886
    virURIFree(parsedUri);
3887 3888 3889
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Event_Free(&eventList);
    esxVI_ManagedObjectReference_Free(&task);
3890
    VIR_FREE(taskInfoErrorMessage);
3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901

    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 已提交
3902
                       unsigned long flags)
3903
{
E
Eric Blake 已提交
3904 3905
    virCheckFlags(ESX_MIGRATION_FLAGS, NULL);

3906 3907 3908 3909 3910
    return esxDomainLookupByName(dconn, dname);
}



M
Matthias Bolte 已提交
3911 3912 3913 3914
static unsigned long long
esxNodeGetFreeMemory(virConnectPtr conn)
{
    unsigned long long result = 0;
3915
    unsigned long long usageBytes = 0;
M
Matthias Bolte 已提交
3916
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
3917
    esxVI_String *propertyNameList = NULL;
3918 3919 3920
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_Int *memoryUsage = NULL;
    esxVI_Long *memorySize = NULL;
M
Matthias Bolte 已提交
3921

3922
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
3923
        return 0;
M
Matthias Bolte 已提交
3924

3925 3926 3927 3928 3929 3930 3931 3932 3933 3934
    /* 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 已提交
3935
        goto cleanup;
M
Matthias Bolte 已提交
3936 3937
    }

3938
    usageBytes = (unsigned long long)(memoryUsage->value) * 1048576;
3939
    result = memorySize->value - usageBytes;
M
Matthias Bolte 已提交
3940

3941
 cleanup:
M
Matthias Bolte 已提交
3942
    esxVI_String_Free(&propertyNameList);
3943 3944 3945
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_Int_Free(&memoryUsage);
    esxVI_Long_Free(&memorySize);
M
Matthias Bolte 已提交
3946 3947 3948 3949 3950 3951

    return result;
}



3952
static int
3953
esxConnectIsEncrypted(virConnectPtr conn)
3954
{
M
Matthias Bolte 已提交
3955
    esxPrivate *priv = conn->privateData;
3956

3957
    return STRCASEEQ(priv->parsedUri->transport, "https");
3958 3959 3960 3961 3962
}



static int
3963
esxConnectIsSecure(virConnectPtr conn)
3964
{
M
Matthias Bolte 已提交
3965
    esxPrivate *priv = conn->privateData;
3966

3967
    return STRCASEEQ(priv->parsedUri->transport, "https");
3968 3969 3970 3971
}



3972
static int
3973
esxConnectIsAlive(virConnectPtr conn)
3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988
{
    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;
}



3989 3990 3991
static int
esxDomainIsActive(virDomainPtr domain)
{
M
Matthias Bolte 已提交
3992
    int result = -1;
M
Matthias Bolte 已提交
3993
    esxPrivate *priv = domain->conn->privateData;
3994 3995 3996 3997
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

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

4001
    if (esxVI_String_AppendValueToList(&propertyNameList,
4002
                                       "runtime.powerState") < 0 ||
4003
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
4004
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
4005
                                         esxVI_Occurrence_RequiredItem) < 0 ||
4006
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
4007
        goto cleanup;
4008 4009 4010 4011 4012 4013 4014 4015
    }

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

4016
 cleanup:
4017 4018 4019 4020 4021 4022 4023 4024 4025
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
4026
esxDomainIsPersistent(virDomainPtr domain)
4027
{
4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043
    /* 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;

4044
 cleanup:
4045 4046 4047
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
4048 4049
}

M
Matthias Bolte 已提交
4050 4051


4052 4053 4054
static int
esxDomainIsUpdated(virDomainPtr domain ATTRIBUTE_UNUSED)
{
4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070
    /* 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;

4071
 cleanup:
4072 4073 4074
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
4075
}
4076

M
Matthias Bolte 已提交
4077 4078


4079 4080
static virDomainSnapshotPtr
esxDomainSnapshotCreateXML(virDomainPtr domain, const char *xmlDesc,
4081
                           unsigned int flags)
4082 4083 4084 4085 4086 4087 4088 4089
{
    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;
4090
    char *taskInfoErrorMessage = NULL;
4091
    virDomainSnapshotPtr snapshot = NULL;
4092 4093
    bool diskOnly = (flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY) != 0;
    bool quiesce = (flags & VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE) != 0;
4094

4095 4096 4097 4098 4099
    /* 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);
4100

4101
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4102
        return NULL;
4103

4104
    def = virDomainSnapshotDefParseString(xmlDesc, priv->caps,
4105
                                          priv->xmlopt, 0);
4106

4107
    if (!def)
M
Matthias Bolte 已提交
4108
        return NULL;
4109

4110
    if (def->ndisks) {
4111 4112
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("disk snapshots not supported yet"));
4113 4114 4115
        return NULL;
    }

4116
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
4117
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4118
           priv->parsedUri->autoAnswer) < 0 ||
4119
        esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4120 4121
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, def->name,
4122
                                    &snapshotTree, NULL,
4123
                                    esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4124
        goto cleanup;
4125 4126
    }

4127
    if (snapshotTree) {
4128 4129
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Snapshot '%s' already exists"), def->name);
M
Matthias Bolte 已提交
4130
        goto cleanup;
4131 4132
    }

4133
    if (esxVI_CreateSnapshot_Task(priv->primary, virtualMachine->obj,
4134
                                  def->name, def->description,
4135 4136 4137
                                  diskOnly ? esxVI_Boolean_False : esxVI_Boolean_True,
                                  quiesce ? esxVI_Boolean_True : esxVI_Boolean_False,
                                  &task) < 0 ||
4138
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
4139
                                    esxVI_Occurrence_RequiredItem,
4140
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4141
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4142
        goto cleanup;
4143 4144 4145
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4146 4147
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not create snapshot: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4148
        goto cleanup;
4149 4150 4151 4152
    }

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

4153
 cleanup:
4154 4155 4156 4157
    virDomainSnapshotDefFree(def);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4158
    VIR_FREE(taskInfoErrorMessage);
4159 4160 4161 4162 4163 4164 4165

    return snapshot;
}



static char *
4166 4167
esxDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                            unsigned int flags)
4168 4169 4170 4171 4172 4173 4174 4175 4176
{
    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;

4177 4178
    virCheckFlags(0, NULL);

4179
    memset(&def, 0, sizeof(def));
4180

4181
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4182
        return NULL;
4183

4184
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4185 4186 4187 4188
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4189
        goto cleanup;
4190 4191 4192 4193
    }

    def.name = snapshot->name;
    def.description = snapshotTree->description;
4194
    def.parent = snapshotTreeParent ? snapshotTreeParent->name : NULL;
4195 4196 4197

    if (esxVI_DateTime_ConvertToCalendarTime(snapshotTree->createTime,
                                             &def.creationTime) < 0) {
M
Matthias Bolte 已提交
4198
        goto cleanup;
4199 4200 4201 4202 4203 4204 4205
    }

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

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

4206
    xml = virDomainSnapshotDefFormat(uuid_string, &def, priv->caps, priv->xmlopt,
4207 4208
                                     virDomainDefFormatConvertXMLFlags(flags),
                                     0);
4209

4210
 cleanup:
4211 4212 4213 4214 4215 4216 4217 4218
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return xml;
}



static int
4219
esxDomainSnapshotNum(virDomainPtr domain, unsigned int flags)
4220
{
M
Matthias Bolte 已提交
4221
    int count;
4222 4223
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
4224
    bool recurse;
4225
    bool leaves;
4226

4227
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
4228 4229
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4230 4231

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) == 0;
4232
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4233

4234
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4235
        return -1;
4236

4237 4238 4239 4240
    /* ESX snapshots do not require libvirt to maintain any metadata.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA)
        return 0;

4241
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4242
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4243
        return -1;
4244 4245
    }

4246 4247
    count = esxVI_GetNumberOfSnapshotTrees(rootSnapshotTreeList, recurse,
                                           leaves);
4248 4249 4250

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

M
Matthias Bolte 已提交
4251
    return count;
4252 4253 4254 4255 4256 4257
}



static int
esxDomainSnapshotListNames(virDomainPtr domain, char **names, int nameslen,
4258
                           unsigned int flags)
4259
{
M
Matthias Bolte 已提交
4260
    int result;
4261 4262
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
4263
    bool recurse;
4264
    bool leaves;
4265 4266

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
4267 4268
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4269

4270
    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) == 0;
4271
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4272

4273
    if (!names || nameslen < 0) {
4274
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
4275 4276 4277
        return -1;
    }

4278
    if (nameslen == 0 || (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA))
4279 4280
        return 0;

4281
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4282
        return -1;
4283

4284
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4285
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4286
        return -1;
4287 4288
    }

4289
    result = esxVI_GetSnapshotTreeNames(rootSnapshotTreeList, names, nameslen,
4290
                                        recurse, leaves);
4291 4292 4293 4294 4295 4296 4297 4298

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



4299 4300 4301 4302 4303 4304 4305 4306
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;
4307
    bool leaves;
4308 4309

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
4310 4311
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4312 4313

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) != 0;
4314
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4315

4316
    if (esxVI_EnsureSession(priv->primary) < 0)
4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333
        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,
4334
                                           recurse, leaves);
4335

4336
 cleanup:
4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353
    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;
4354
    bool leaves;
4355 4356

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
4357 4358
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4359 4360

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) != 0;
4361
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4362

4363
    if (!names || nameslen < 0) {
4364
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
4365 4366 4367
        return -1;
    }

4368
    if (nameslen == 0)
4369 4370
        return 0;

4371
    if (esxVI_EnsureSession(priv->primary) < 0)
4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388
        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,
4389
                                        names, nameslen, recurse, leaves);
4390

4391
 cleanup:
4392 4393 4394 4395 4396 4397 4398
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



4399 4400
static virDomainSnapshotPtr
esxDomainSnapshotLookupByName(virDomainPtr domain, const char *name,
4401
                              unsigned int flags)
4402 4403 4404 4405 4406 4407
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    virDomainSnapshotPtr snapshot = NULL;

4408 4409
    virCheckFlags(0, NULL);

4410
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4411
        return NULL;
4412

4413
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4414 4415
                                         &rootSnapshotTreeList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotTreeList, name, &snapshotTree,
4416
                                    NULL,
4417 4418 4419 4420 4421 4422
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    snapshot = virGetDomainSnapshot(domain, name);

4423
 cleanup:
4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return snapshot;
}



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

4437
    virCheckFlags(0, -1);
4438

4439
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4440
        return -1;
4441

4442
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4443 4444
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4445
        return -1;
4446 4447
    }

4448
    if (currentSnapshotTree) {
M
Matthias Bolte 已提交
4449 4450
        esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);
        return 1;
4451 4452
    }

M
Matthias Bolte 已提交
4453
    return 0;
4454 4455 4456 4457
}



E
Eric Blake 已提交
4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468
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);

4469
    if (esxVI_EnsureSession(priv->primary) < 0)
E
Eric Blake 已提交
4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480
        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) {
4481 4482 4483
        virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                       _("snapshot '%s' does not have a parent"),
                       snapshotTree->name);
E
Eric Blake 已提交
4484 4485 4486 4487 4488
        goto cleanup;
    }

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

4489
 cleanup:
E
Eric Blake 已提交
4490 4491 4492 4493 4494 4495 4496
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return parent;
}



4497 4498 4499 4500 4501
static virDomainSnapshotPtr
esxDomainSnapshotCurrent(virDomainPtr domain, unsigned int flags)
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *currentSnapshotTree = NULL;
M
Matthias Bolte 已提交
4502
    virDomainSnapshotPtr snapshot = NULL;
4503

4504
    virCheckFlags(0, NULL);
4505

4506
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4507
        return NULL;
4508

4509
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4510 4511
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4512
        return NULL;
4513 4514 4515 4516 4517 4518 4519 4520 4521 4522
    }

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

    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return snapshot;
}


4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533
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);

4534
    if (esxVI_EnsureSession(priv->primary) < 0)
4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553
        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);

4554
 cleanup:
4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570
    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);

4571
    if (esxVI_EnsureSession(priv->primary) < 0)
4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584
        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;

4585
 cleanup:
4586 4587 4588 4589
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    return ret;
}

4590 4591 4592 4593

static int
esxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4594
    int result = -1;
4595 4596 4597 4598 4599
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
4600
    char *taskInfoErrorMessage = NULL;
4601

4602
    virCheckFlags(0, -1);
4603

4604
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4605
        return -1;
4606

4607
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4608 4609
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
4610
                                    &snapshotTree, NULL,
4611
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4612
        goto cleanup;
4613 4614
    }

4615
    if (esxVI_RevertToSnapshot_Task(priv->primary, snapshotTree->snapshot, NULL,
4616
                                    esxVI_Boolean_Undefined, &task) < 0 ||
4617
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4618
                                    esxVI_Occurrence_RequiredItem,
4619
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4620
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4621
        goto cleanup;
4622 4623 4624
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4625 4626 4627
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not revert to snapshot '%s': %s"), snapshot->name,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4628
        goto cleanup;
4629 4630
    }

M
Matthias Bolte 已提交
4631 4632
    result = 0;

4633
 cleanup:
4634 4635
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4636
    VIR_FREE(taskInfoErrorMessage);
4637 4638 4639 4640 4641 4642 4643 4644 4645

    return result;
}



static int
esxDomainSnapshotDelete(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4646
    int result = -1;
4647 4648 4649 4650 4651 4652
    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;
4653
    char *taskInfoErrorMessage = NULL;
4654

4655 4656
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
                  VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY, -1);
4657

4658
    if (esxVI_EnsureSession(priv->primary) < 0)
M
Matthias Bolte 已提交
4659
        return -1;
4660

4661
    if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN)
4662 4663
        removeChildren = esxVI_Boolean_True;

4664
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4665 4666
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
4667
                                    &snapshotTree, NULL,
4668
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4669
        goto cleanup;
4670 4671
    }

4672 4673 4674 4675 4676 4677 4678
    /* 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;
    }

4679
    if (esxVI_RemoveSnapshot_Task(priv->primary, snapshotTree->snapshot,
4680
                                  removeChildren, &task) < 0 ||
4681
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4682
                                    esxVI_Occurrence_RequiredItem,
4683
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4684
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4685
        goto cleanup;
4686 4687 4688
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4689 4690 4691
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not delete snapshot '%s': %s"), snapshot->name,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4692
        goto cleanup;
4693 4694
    }

M
Matthias Bolte 已提交
4695 4696
    result = 0;

4697
 cleanup:
4698 4699
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4700
    VIR_FREE(taskInfoErrorMessage);
4701 4702 4703 4704 4705 4706

    return result;
}



4707
static int
4708
esxDomainSetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
4709 4710 4711 4712 4713 4714 4715 4716
                             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;
4717
    char *taskInfoErrorMessage = NULL;
4718
    size_t i;
4719 4720

    virCheckFlags(0, -1);
4721 4722 4723 4724
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_MEMORY_MIN_GUARANTEE,
                               VIR_TYPED_PARAM_ULLONG,
                               NULL) < 0)
4725
        return -1;
4726

4727
    if (esxVI_EnsureSession(priv->primary) < 0)
4728 4729 4730 4731
        return -1;

    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4732
           priv->parsedUri->autoAnswer) < 0 ||
4733 4734 4735 4736 4737 4738
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0) {
        goto cleanup;
    }

    for (i = 0; i < nparams; ++i) {
4739
        if (STREQ(params[i].field, VIR_DOMAIN_MEMORY_MIN_GUARANTEE)) {
4740
            if (esxVI_Long_Alloc(&spec->memoryAllocation->reservation) < 0)
4741 4742 4743
                goto cleanup;

            spec->memoryAllocation->reservation->value =
4744
              VIR_DIV_UP(params[i].value.ul, 1024); /* Scale from kilobytes to megabytes */
4745 4746 4747 4748 4749 4750 4751
        }
    }

    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
4752
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4753
                                    &taskInfoErrorMessage) < 0) {
4754 4755 4756 4757
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4758 4759 4760
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not change memory parameters: %s"),
                       taskInfoErrorMessage);
4761 4762 4763 4764 4765
        goto cleanup;
    }

    result = 0;

4766
 cleanup:
4767 4768 4769
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
4770
    VIR_FREE(taskInfoErrorMessage);
4771 4772 4773 4774 4775 4776 4777

    return result;
}



static int
4778
esxDomainGetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793
                             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;
    }

4794
    if (esxVI_EnsureSession(priv->primary) < 0)
4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806
        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;
    }

4807 4808 4809 4810
    /* Scale from megabytes to kilobytes */
    if (virTypedParameterAssign(params, VIR_DOMAIN_MEMORY_MIN_GUARANTEE,
                                VIR_TYPED_PARAM_ULLONG,
                                reservation->value * 1024) < 0)
4811 4812 4813 4814 4815
        goto cleanup;

    *nparams = 1;
    result = 0;

4816
 cleanup:
4817 4818 4819 4820 4821 4822 4823
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Long_Free(&reservation);

    return result;
}

4824 4825
#define MATCH(FLAG) (flags & (FLAG))
static int
4826 4827 4828
esxConnectListAllDomains(virConnectPtr conn,
                         virDomainPtr **domains,
                         unsigned int flags)
4829 4830 4831
{
    int ret = -1;
    esxPrivate *priv = conn->privateData;
4832 4833
    bool needIdentity;
    bool needPowerState;
4834 4835 4836
    virDomainPtr dom;
    virDomainPtr *doms = NULL;
    size_t ndoms = 0;
4837
    esxVI_String *propertyNameList = NULL;
4838 4839
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
4840
    esxVI_AutoStartDefaults *autoStartDefaults = NULL;
4841 4842 4843 4844 4845 4846 4847 4848 4849 4850
    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;
4851
    esxVI_DynamicProperty *dynamicProperty = NULL;
4852 4853 4854 4855 4856 4857 4858

    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
     */
4859
    if ((MATCH(VIR_CONNECT_LIST_DOMAINS_TRANSIENT) &&
4860 4861 4862 4863 4864
         !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)
4865
            goto cleanup;
4866 4867 4868 4869 4870

        ret = 0;
        goto cleanup;
    }

4871
    if (esxVI_EnsureSession(priv->primary) < 0)
4872 4873 4874 4875 4876
        return -1;

    /* check system default autostart value */
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_AUTOSTART)) {
        if (esxVI_LookupAutoStartDefaults(priv->primary,
4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889
                                          &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) ||
4890
                   domains;
4891 4892 4893 4894 4895 4896 4897

    if (needIdentity) {
        /* Request required data for esxVI_GetVirtualMachineIdentity */
        if (esxVI_String_AppendValueListToList(&propertyNameList,
                                               "configStatus\0"
                                               "name\0"
                                               "config.uuid\0") < 0) {
4898
            goto cleanup;
4899 4900 4901 4902 4903
        }
    }

    needPowerState = MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_ACTIVE) ||
                     MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_STATE) ||
4904
                     domains;
4905

4906 4907 4908
    if (needPowerState) {
        if (esxVI_String_AppendValueToList(&propertyNameList,
                                           "runtime.powerState") < 0) {
4909
            goto cleanup;
4910
        }
4911 4912
    }

4913 4914 4915 4916 4917 4918 4919
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_SNAPSHOT)) {
        if (esxVI_String_AppendValueToList(&propertyNameList,
                                           "snapshot.rootSnapshotList") < 0) {
            goto cleanup;
        }
    }

4920
    if (esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
4921 4922 4923 4924 4925
                                       &virtualMachineList) < 0)
        goto cleanup;

    if (domains) {
        if (VIR_ALLOC_N(doms, 1) < 0)
4926
            goto cleanup;
4927 4928 4929
        ndoms = 1;
    }

4930
    for (virtualMachine = virtualMachineList; virtualMachine;
4931
         virtualMachine = virtualMachine->_next) {
4932 4933
        if (needIdentity) {
            VIR_FREE(name);
4934

4935 4936 4937 4938 4939
            if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id,
                                                &name, uuid) < 0) {
                goto cleanup;
            }
        }
4940

4941 4942 4943 4944 4945 4946
        if (needPowerState) {
            if (esxVI_GetVirtualMachinePowerState(virtualMachine,
                                                  &powerState) < 0) {
                goto cleanup;
            }
        }
4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957

        /* 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)) {
4958

4959 4960
            esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

4961 4962 4963 4964 4965 4966 4967 4968 4969 4970
            for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
                dynamicProperty = dynamicProperty->_next) {
                if (STREQ(dynamicProperty->name, "snapshot.rootSnapshotList")) {
                    if (esxVI_VirtualMachineSnapshotTree_CastListFromAnyType
                        (dynamicProperty->val, &rootSnapshotTreeList) < 0) {
                        goto cleanup;
                    }

                    break;
                }
4971 4972 4973
            }

            if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT) &&
4974
                   rootSnapshotTreeList) ||
4975
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT) &&
4976
                   !rootSnapshotTreeList)))
4977 4978 4979 4980 4981 4982 4983
                continue;
        }

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

4984
            if (autoStartDefaults->enabled == esxVI_Boolean_True) {
4985
                for (powerInfo = powerInfoList; powerInfo;
4986 4987 4988 4989
                     powerInfo = powerInfo->_next) {
                    if (STREQ(powerInfo->key->value, virtualMachine->obj->value)) {
                        if (STRCASEEQ(powerInfo->startAction, "powerOn"))
                            autostart = true;
4990

4991 4992
                        break;
                    }
4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005
                }
            }

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

5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025
            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;
        }

5026
        if (VIR_RESIZE_N(doms, ndoms, count, 2) < 0)
5027
            goto cleanup;
5028 5029

        /* Only running/suspended virtual machines have an ID != -1 */
5030 5031 5032 5033 5034
        if (powerState == esxVI_VirtualMachinePowerState_PoweredOff)
            id = -1;

        if (!(dom = virGetDomain(conn, name, uuid, id)))
            goto cleanup;
5035 5036 5037 5038 5039 5040 5041 5042 5043

        doms[count++] = dom;
    }

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

5044
 cleanup:
5045
    if (doms) {
5046
        for (id = 0; id < count; id++)
5047
            virObjectUnref(doms[id]);
5048 5049

        VIR_FREE(doms);
5050
    }
5051

5052
    VIR_FREE(name);
5053 5054
    esxVI_AutoStartDefaults_Free(&autoStartDefaults);
    esxVI_AutoStartPowerInfo_Free(&powerInfoList);
5055 5056
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
5057 5058
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

5059 5060 5061
    return ret;
}
#undef MATCH
5062

5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098
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;
}

5099

5100
static virHypervisorDriver esxHypervisorDriver = {
5101
    .name = "ESX",
5102 5103 5104 5105 5106 5107
    .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 */
5108
    .nodeGetInfo = esxNodeGetInfo, /* 0.7.0 */
5109 5110 5111 5112
    .connectGetCapabilities = esxConnectGetCapabilities, /* 0.7.1 */
    .connectListDomains = esxConnectListDomains, /* 0.7.0 */
    .connectNumOfDomains = esxConnectNumOfDomains, /* 0.7.0 */
    .connectListAllDomains = esxConnectListAllDomains, /* 0.10.2 */
5113 5114 5115 5116 5117 5118
    .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 */
5119
    .domainShutdownFlags = esxDomainShutdownFlags, /* 0.9.10 */
5120 5121
    .domainReboot = esxDomainReboot, /* 0.7.0 */
    .domainDestroy = esxDomainDestroy, /* 0.7.0 */
5122
    .domainDestroyFlags = esxDomainDestroyFlags, /* 0.9.4 */
5123 5124 5125 5126 5127 5128 5129 5130
    .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 */
5131
    .domainScreenshot = esxDomainScreenshot, /* 1.2.10 */
5132 5133 5134 5135 5136
    .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 */
5137 5138 5139 5140
    .connectDomainXMLFromNative = esxConnectDomainXMLFromNative, /* 0.7.0 */
    .connectDomainXMLToNative = esxConnectDomainXMLToNative, /* 0.7.2 */
    .connectListDefinedDomains = esxConnectListDefinedDomains, /* 0.7.0 */
    .connectNumOfDefinedDomains = esxConnectNumOfDefinedDomains, /* 0.7.0 */
5141 5142 5143
    .domainCreate = esxDomainCreate, /* 0.7.0 */
    .domainCreateWithFlags = esxDomainCreateWithFlags, /* 0.8.2 */
    .domainDefineXML = esxDomainDefineXML, /* 0.7.2 */
5144
    .domainDefineXMLFlags = esxDomainDefineXMLFlags, /* 1.2.12 */
5145
    .domainUndefine = esxDomainUndefine, /* 0.7.1 */
5146
    .domainUndefineFlags = esxDomainUndefineFlags, /* 0.9.4 */
5147 5148 5149 5150
    .domainGetAutostart = esxDomainGetAutostart, /* 0.9.0 */
    .domainSetAutostart = esxDomainSetAutostart, /* 0.9.0 */
    .domainGetSchedulerType = esxDomainGetSchedulerType, /* 0.7.0 */
    .domainGetSchedulerParameters = esxDomainGetSchedulerParameters, /* 0.7.0 */
5151
    .domainGetSchedulerParametersFlags = esxDomainGetSchedulerParametersFlags, /* 0.9.2 */
5152
    .domainSetSchedulerParameters = esxDomainSetSchedulerParameters, /* 0.7.0 */
5153
    .domainSetSchedulerParametersFlags = esxDomainSetSchedulerParametersFlags, /* 0.9.2 */
5154 5155 5156 5157
    .domainMigratePrepare = esxDomainMigratePrepare, /* 0.7.0 */
    .domainMigratePerform = esxDomainMigratePerform, /* 0.7.0 */
    .domainMigrateFinish = esxDomainMigrateFinish, /* 0.7.0 */
    .nodeGetFreeMemory = esxNodeGetFreeMemory, /* 0.7.2 */
5158 5159
    .connectIsEncrypted = esxConnectIsEncrypted, /* 0.7.3 */
    .connectIsSecure = esxConnectIsSecure, /* 0.7.3 */
5160 5161 5162 5163 5164 5165 5166
    .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 */
5167 5168
    .domainSnapshotNumChildren = esxDomainSnapshotNumChildren, /* 0.9.7 */
    .domainSnapshotListChildrenNames = esxDomainSnapshotListChildrenNames, /* 0.9.7 */
5169 5170
    .domainSnapshotLookupByName = esxDomainSnapshotLookupByName, /* 0.8.0 */
    .domainHasCurrentSnapshot = esxDomainHasCurrentSnapshot, /* 0.8.0 */
E
Eric Blake 已提交
5171
    .domainSnapshotGetParent = esxDomainSnapshotGetParent, /* 0.9.7 */
5172 5173
    .domainSnapshotCurrent = esxDomainSnapshotCurrent, /* 0.8.0 */
    .domainRevertToSnapshot = esxDomainRevertToSnapshot, /* 0.8.0 */
5174 5175
    .domainSnapshotIsCurrent = esxDomainSnapshotIsCurrent, /* 0.9.13 */
    .domainSnapshotHasMetadata = esxDomainSnapshotHasMetadata, /* 0.9.13 */
5176
    .domainSnapshotDelete = esxDomainSnapshotDelete, /* 0.8.0 */
5177
    .connectIsAlive = esxConnectIsAlive, /* 0.9.8 */
5178
    .domainHasManagedSaveImage = esxDomainHasManagedSaveImage, /* 1.2.13 */
5179 5180 5181
};


5182
static virConnectDriver esxConnectDriver = {
5183
    .remoteOnly = true,
5184
    .uriSchemes = (const char *[]){ "vpx", "esx", "gsx", NULL },
5185 5186 5187 5188 5189
    .hypervisorDriver = &esxHypervisorDriver,
    .interfaceDriver = &esxInterfaceDriver,
    .networkDriver = &esxNetworkDriver,
    .storageDriver = &esxStorageDriver,
};
5190 5191 5192 5193

int
esxRegister(void)
{
5194 5195
    return virRegisterConnectDriver(&esxConnectDriver,
                                    false);
5196
}