esx_driver.c 168.5 KB
Newer Older
1
/*
2
 * esx_driver.c: core driver functions for managing VMware ESX hosts
3
 *
4
 * Copyright (C) 2010-2014 Red Hat, Inc.
5
 * Copyright (C) 2009-2013 Matthias Bolte <matthias.bolte@googlemail.com>
6 7 8 9 10 11 12 13 14 15 16 17 18
 * Copyright (C) 2009 Maximilian Wilhelm <max@rfc2324.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
19
 * License along with this library.  If not, see
O
Osier Yang 已提交
20
 * <http://www.gnu.org/licenses/>.
21 22 23 24 25 26 27
 *
 */

#include <config.h>

#include "internal.h"
#include "domain_conf.h"
28
#include "snapshot_conf.h"
29
#include "virauth.h"
30
#include "viralloc.h"
31
#include "virfile.h"
32
#include "virlog.h"
33
#include "viruuid.h"
34
#include "vmx.h"
35
#include "virtypedparam.h"
36
#include "esx_driver.h"
37 38 39 40 41
#include "esx_interface_driver.h"
#include "esx_network_driver.h"
#include "esx_storage_driver.h"
#include "esx_device_monitor.h"
#include "esx_secret_driver.h"
M
Matthias Bolte 已提交
42
#include "esx_nwfilter_driver.h"
43
#include "esx_private.h"
44 45 46
#include "esx_vi.h"
#include "esx_vi_methods.h"
#include "esx_util.h"
47
#include "virstring.h"
48
#include "viruri.h"
49 50 51

#define VIR_FROM_THIS VIR_FROM_ESX

52 53
VIR_LOG_INIT("esx.esx_driver");

54 55
static int esxDomainGetMaxVcpus(virDomainPtr domain);

56 57 58 59
typedef struct _esxVMX_Data esxVMX_Data;

struct _esxVMX_Data {
    esxVI_Context *ctx;
60
    char *datastorePathWithoutFileName;
61 62 63 64
};



65 66 67
static void
esxFreePrivate(esxPrivate **priv)
{
68
    if (!priv || !(*priv)) {
69 70 71 72 73 74
        return;
    }

    esxVI_Context_Free(&(*priv)->host);
    esxVI_Context_Free(&(*priv)->vCenter);
    esxUtil_FreeParsedUri(&(*priv)->parsedUri);
75
    virObjectUnref((*priv)->caps);
76
    virObjectUnref((*priv)->xmlopt);
77 78 79 80 81
    VIR_FREE(*priv);
}



82
/*
83 84
 * Parse a file name from a .vmx file and convert it to datastore path format
 * if possbile. A .vmx file can contain file names in various formats:
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
 *
 * - 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
 *
106 107 108 109 110 111 112 113
 * - 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.
 *
114 115 116 117 118 119 120
 * 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
121
 * function via the opaque parameter by the caller of virVMXParseConfig.
122 123 124 125 126 127 128 129 130
 *
 * 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.
 */
131
static char *
132
esxParseVMXFileName(const char *fileName, void *opaque)
133
{
134
    char *result = NULL;
135
    esxVMX_Data *data = opaque;
136
    esxVI_String *propertyNameList = NULL;
137
    esxVI_ObjectContent *datastoreList = NULL;
138
    esxVI_ObjectContent *datastore = NULL;
139 140 141 142 143 144 145 146
    esxVI_DatastoreHostMount *hostMount = NULL;
    char *datastoreName;
    char *tmp;
    char *saveptr;
    char *strippedFileName = NULL;
    char *copyOfFileName = NULL;
    char *directoryAndFileName;

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

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

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

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

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

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

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

189
            tmp = strippedFileName;
190

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

197 198
                ++tmp;
            }
199

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

204 205
            break;
        }
206

207
        /* Fallback to direct datastore name match */
208
        if (!result && STRPREFIX(fileName, "/vmfs/volumes/")) {
209
            if (VIR_STRDUP(copyOfFileName, fileName) < 0) {
210 211
                goto cleanup;
            }
212

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

223
            esxVI_ObjectContent_Free(&datastoreList);
224

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

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

238
            if (virAsprintf(&result, "[%s] %s", datastoreName,
239
                            directoryAndFileName) < 0)
240
                goto cleanup;
241 242
        }

243
        /* If it's an absolute path outside of a datastore just use it as is */
244
        if (!result && *fileName == '/') {
245
            /* FIXME: need to deal with Windows paths here too */
246
            if (VIR_STRDUP(result, fileName) < 0) {
247 248 249 250
                goto cleanup;
            }
        }

251
        if (!result) {
252 253
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not handle file name '%s'"), fileName);
254
            goto cleanup;
255
        }
256
    }
257

258
 cleanup:
259 260 261 262 263
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&datastoreList);
    esxVI_DatastoreHostMount_Free(&hostMount);
    VIR_FREE(strippedFileName);
    VIR_FREE(copyOfFileName);
264

265
    return result;
266 267 268 269
}



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

298 299 300 301 302 303
    if (*fileName == '[') {
        /* Parse datastore path and lookup datastore */
        if (esxUtil_ParseDatastorePath(fileName, &datastoreName, NULL,
                                       &directoryAndFileName) < 0) {
            goto cleanup;
        }
304

305 306 307
        if (esxVI_LookupDatastoreByName(data->ctx, datastoreName, NULL, &datastore,
                                        esxVI_Occurrence_RequiredItem) < 0 ||
            esxVI_LookupDatastoreHostMount(data->ctx, datastore->obj,
308 309
                                           &hostMount,
                                           esxVI_Occurrence_RequiredItem) < 0) {
310 311
            goto cleanup;
        }
312

313
        /* Detect separator type */
314
        if (strchr(hostMount->mountInfo->path, '\\')) {
315 316
            separator = '\\';
        }
317

318 319
        /* Strip trailing separators */
        length = strlen(hostMount->mountInfo->path);
320

321 322 323
        while (length > 0 && hostMount->mountInfo->path[length - 1] == separator) {
            --length;
        }
324

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

328 329
        if (separator != '/') {
            tmp = directoryAndFileName;
330

331 332 333 334
            while (*tmp != '\0') {
                if (*tmp == '/') {
                    *tmp = separator;
                }
335

336 337
                ++tmp;
            }
338
        }
339

340 341
        virBufferAddChar(&buffer, separator);
        virBufferAdd(&buffer, directoryAndFileName, -1);
342

343 344 345 346 347 348 349 350
        if (virBufferError(&buffer)) {
            virReportOOMError();
            goto cleanup;
        }

        result = virBufferContentAndReset(&buffer);
    } else if (*fileName == '/') {
        /* FIXME: need to deal with Windows paths here too */
351
        if (VIR_STRDUP(result, fileName) < 0) {
352 353 354
            goto cleanup;
        }
    } else {
355 356
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not handle file name '%s'"), fileName);
357 358 359 360 361 362 363
        goto cleanup;
    }

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

    success = true;

364
 cleanup:
365
    if (! success) {
366
        virBufferFreeAndReset(&buffer);
367
        VIR_FREE(result);
368 369 370
    }

    VIR_FREE(datastoreName);
371
    VIR_FREE(directoryAndFileName);
372 373
    esxVI_ObjectContent_Free(&datastore);
    esxVI_DatastoreHostMount_Free(&hostMount);
374

375
    return result;
376 377 378 379 380 381 382 383 384 385
}



static int
esxAutodetectSCSIControllerModel(virDomainDiskDefPtr def, int *model,
                                 void *opaque)
{
    int result = -1;
    esxVMX_Data *data = opaque;
386
    esxVI_FileInfo *fileInfo = NULL;
387
    esxVI_VmDiskFileInfo *vmDiskFileInfo = NULL;
388
    const char *src = virDomainDiskGetSource(def);
389 390 391

    if (def->device != VIR_DOMAIN_DISK_DEVICE_DISK ||
        def->bus != VIR_DOMAIN_DISK_BUS_SCSI ||
E
Eric Blake 已提交
392
        virDomainDiskGetType(def) != VIR_STORAGE_TYPE_FILE ||
393
        !src || !STRPREFIX(src, "[")) {
394 395 396 397 398 399 400
        /*
         * This isn't a file-based SCSI disk device with a datastore related
         * source path => do nothing.
         */
        return 0;
    }

401
    if (esxVI_LookupFileInfoByDatastorePath(data->ctx, src,
402
                                            false, &fileInfo,
403
                                            esxVI_Occurrence_RequiredItem) < 0) {
404 405 406
        goto cleanup;
    }

407
    vmDiskFileInfo = esxVI_VmDiskFileInfo_DynamicCast(fileInfo);
408

409
    if (!vmDiskFileInfo || !vmDiskFileInfo->controllerType) {
410
        virReportError(VIR_ERR_INTERNAL_ERROR,
411
                       _("Could not lookup controller model for '%s'"), src);
412 413 414 415 416
        goto cleanup;
    }

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

    result = 0;

436
 cleanup:
437
    esxVI_FileInfo_Free(&fileInfo);
438 439 440 441

    return result;
}

442 443


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

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

459
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
460
        return esxVI_Boolean_Undefined;
461 462
    }

463
    if (esxVI_String_AppendValueToList(&propertyNameList,
464
                                       "hardware.cpuFeature") < 0 ||
465 466
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
467
        goto cleanup;
468 469
    }

470
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
471 472 473
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuFeature")) {
            if (esxVI_HostCpuIdInfo_CastListFromAnyType
474
                  (dynamicProperty->val, &hostCpuIdInfoList) < 0) {
M
Matthias Bolte 已提交
475
                goto cleanup;
476 477
            }

478
            for (hostCpuIdInfo = hostCpuIdInfoList; hostCpuIdInfo;
479 480
                 hostCpuIdInfo = hostCpuIdInfo->_next) {
                if (hostCpuIdInfo->level->value == -2147483647) { /* 0x80000001 */
481 482
                    if (esxVI_ParseHostCpuIdInfo(&parsedHostCpuIdInfo,
                                                 hostCpuIdInfo) < 0) {
M
Matthias Bolte 已提交
483
                        goto cleanup;
484 485
                    }

486
                    edxLongModeBit = parsedHostCpuIdInfo.edx[29];
487 488 489 490 491 492

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

                    break;
                }
            }

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

511
 cleanup:
M
Matthias Bolte 已提交
512 513 514 515
    /*
     * 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.
     */
516 517 518 519 520 521 522 523 524
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_HostCpuIdInfo_Free(&hostCpuIdInfoList);

    return priv->supportsLongMode;
}



525 526 527 528 529 530
static int
esxLookupHostSystemBiosUuid(esxPrivate *priv, unsigned char *uuid)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
531
    char *uuid_string = NULL;
532

533
    if (esxVI_EnsureSession(priv->primary) < 0) {
534 535 536 537 538
        return -1;
    }

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

546 547 548
    if (strlen(uuid_string) > 0) {
        if (virUUIDParse(uuid_string, uuid) < 0) {
            VIR_WARN("Could not parse host UUID from string '%s'", uuid_string);
549

550 551
            /* HostSystem has an invalid UUID, ignore it */
            memset(uuid, 0, VIR_UUID_BUFLEN);
552
        }
553 554 555
    } else {
        /* HostSystem has an empty UUID */
        memset(uuid, 0, VIR_UUID_BUFLEN);
556 557 558 559
    }

    result = 0;

560
 cleanup:
561 562 563 564 565 566 567
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}


568
static virCapsPtr
569
esxCapsInit(esxPrivate *priv)
570
{
571
    esxVI_Boolean supportsLongMode = esxSupportsLongMode(priv);
572 573 574
    virCapsPtr caps = NULL;
    virCapsGuestPtr guest = NULL;

575 576 577 578 579
    if (supportsLongMode == esxVI_Boolean_Undefined) {
        return NULL;
    }

    if (supportsLongMode == esxVI_Boolean_True) {
580
        caps = virCapabilitiesNew(VIR_ARCH_X86_64, 1, 1);
581
    } else {
582
        caps = virCapabilitiesNew(VIR_ARCH_I686, 1, 1);
583
    }
584

585
    if (!caps)
586 587
        return NULL;

588
    virCapabilitiesAddHostMigrateTransport(caps, "vpxmigr");
589

590

591 592 593 594
    if (esxLookupHostSystemBiosUuid(priv, caps->host.host_uuid) < 0) {
        goto failure;
    }

595
    /* i686 */
596 597 598
    guest = virCapabilitiesAddGuest(caps, "hvm",
                                    VIR_ARCH_I686,
                                    NULL, NULL, 0,
599
                                    NULL);
600

601
    if (!guest) {
602 603 604
        goto failure;
    }

605
    if (!virCapabilitiesAddGuestDomain(guest, "vmware", NULL, NULL, 0, NULL)) {
606 607 608
        goto failure;
    }

609 610
    /* x86_64 */
    if (supportsLongMode == esxVI_Boolean_True) {
611 612 613
        guest = virCapabilitiesAddGuest(caps, "hvm",
                                        VIR_ARCH_X86_64,
                                        NULL, NULL,
614 615
                                        0, NULL);

616
        if (!guest) {
617 618 619
            goto failure;
        }

620
        if (!virCapabilitiesAddGuestDomain(guest, "vmware", NULL, NULL, 0, NULL)) {
621 622 623 624
            goto failure;
        }
    }

625 626
    return caps;

627
 failure:
628
    virObjectUnref(caps);
629 630 631 632 633 634

    return NULL;
}



635
static int
636 637
esxConnectToHost(esxPrivate *priv,
                 virConnectPtr conn,
638
                 virConnectAuthPtr auth,
639 640 641 642 643
                 char **vCenterIpAddress)
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
M
Matthias Bolte 已提交
644
    char *unescapedPassword = NULL;
645 646 647 648 649
    char *password = NULL;
    char *url = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_Boolean inMaintenanceMode = esxVI_Boolean_Undefined;
650 651 652
    esxVI_ProductVersion expectedProductVersion = STRCASEEQ(conn->uri->scheme, "esx")
        ? esxVI_ProductVersion_ESX
        : esxVI_ProductVersion_GSX;
653

654
    if (!vCenterIpAddress || *vCenterIpAddress) {
655
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
656 657 658
        return -1;
    }

659
    if (esxUtil_ResolveHostname(conn->uri->server, ipAddress, NI_MAXHOST) < 0) {
660 661 662
        return -1;
    }

663
    if (conn->uri->user) {
664
        if (VIR_STRDUP(username, conn->uri->user) < 0)
665 666
            goto cleanup;
    } else {
667
        username = virAuthGetUsername(conn, auth, "esx", "root", conn->uri->server);
668

669
        if (!username) {
670
            virReportError(VIR_ERR_AUTH_FAILED, "%s", _("Username request failed"));
671 672 673 674
            goto cleanup;
        }
    }

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

677
    if (!unescapedPassword) {
678
        virReportError(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
679 680 681
        goto cleanup;
    }

M
Matthias Bolte 已提交
682 683
    password = esxUtil_EscapeForXml(unescapedPassword);

684
    if (!password) {
M
Matthias Bolte 已提交
685 686 687
        goto cleanup;
    }

688
    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->parsedUri->transport,
689
                    conn->uri->server, conn->uri->port) < 0)
690 691 692 693
        goto cleanup;

    if (esxVI_Context_Alloc(&priv->host) < 0 ||
        esxVI_Context_Connect(priv->host, url, ipAddress, username, password,
694
                              priv->parsedUri) < 0 ||
695
        esxVI_Context_LookupManagedObjects(priv->host) < 0) {
696 697 698 699 700
        goto cleanup;
    }

    if (expectedProductVersion == esxVI_ProductVersion_ESX) {
        if (priv->host->productVersion != esxVI_ProductVersion_ESX35 &&
M
Matthias Bolte 已提交
701 702
            priv->host->productVersion != esxVI_ProductVersion_ESX40 &&
            priv->host->productVersion != esxVI_ProductVersion_ESX41 &&
P
Patrice LACHANCE 已提交
703 704
            priv->host->productVersion != esxVI_ProductVersion_ESX4x &&
            priv->host->productVersion != esxVI_ProductVersion_ESX50 &&
M
Martin Kletzander 已提交
705
            priv->host->productVersion != esxVI_ProductVersion_ESX51 &&
P
Patrice LACHANCE 已提交
706
            priv->host->productVersion != esxVI_ProductVersion_ESX5x) {
707 708 709
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("%s is neither an ESX 3.5, 4.x nor 5.x host"),
                           conn->uri->server);
710 711 712 713
            goto cleanup;
        }
    } else { /* GSX */
        if (priv->host->productVersion != esxVI_ProductVersion_GSX20) {
714 715
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("%s isn't a GSX 2.0 host"), conn->uri->server);
716 717 718 719 720 721 722 723
            goto cleanup;
        }
    }

    /* Query the host for maintenance mode and vCenter IP address */
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "runtime.inMaintenanceMode\0"
                                           "summary.managementServerIp\0") < 0 ||
724 725
        esxVI_LookupHostSystemProperties(priv->host, propertyNameList,
                                         &hostSystem) < 0 ||
726 727 728 729 730 731 732 733 734 735 736
        esxVI_GetBoolean(hostSystem, "runtime.inMaintenanceMode",
                         &inMaintenanceMode,
                         esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_GetStringValue(hostSystem, "summary.managementServerIp",
                             vCenterIpAddress,
                             esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
    }

    /* Warn if host is in maintenance mode */
    if (inMaintenanceMode == esxVI_Boolean_True) {
737
        VIR_WARN("The server is in maintenance mode");
738 739
    }

740 741
    if (VIR_STRDUP(*vCenterIpAddress, *vCenterIpAddress) < 0)
        goto cleanup;
742 743 744

    result = 0;

745
 cleanup:
746
    VIR_FREE(username);
M
Matthias Bolte 已提交
747 748
    VIR_FREE(unescapedPassword);
    VIR_FREE(password);
749 750 751 752 753 754 755 756 757 758
    VIR_FREE(url);
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



static int
759 760
esxConnectToVCenter(esxPrivate *priv,
                    virConnectPtr conn,
761 762
                    virConnectAuthPtr auth,
                    const char *hostname,
763
                    const char *hostSystemIpAddress)
764 765 766 767
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
M
Matthias Bolte 已提交
768
    char *unescapedPassword = NULL;
769 770 771
    char *password = NULL;
    char *url = NULL;

772 773
    if (!hostSystemIpAddress &&
        (!priv->parsedUri->path || STREQ(priv->parsedUri->path, "/"))) {
774 775
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Path has to specify the datacenter and compute resource"));
776 777 778
        return -1;
    }

779 780 781 782
    if (esxUtil_ResolveHostname(hostname, ipAddress, NI_MAXHOST) < 0) {
        return -1;
    }

783
    if (conn->uri->user) {
784
        if (VIR_STRDUP(username, conn->uri->user) < 0) {
785 786 787
            goto cleanup;
        }
    } else {
788
        username = virAuthGetUsername(conn, auth, "esx", "administrator", hostname);
789

790
        if (!username) {
791
            virReportError(VIR_ERR_AUTH_FAILED, "%s", _("Username request failed"));
792 793 794 795
            goto cleanup;
        }
    }

796
    unescapedPassword = virAuthGetPassword(conn, auth, "esx", username, hostname);
797

798
    if (!unescapedPassword) {
799
        virReportError(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
800 801 802
        goto cleanup;
    }

M
Matthias Bolte 已提交
803 804
    password = esxUtil_EscapeForXml(unescapedPassword);

805
    if (!password) {
M
Matthias Bolte 已提交
806 807 808
        goto cleanup;
    }

809
    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->parsedUri->transport,
810
                    hostname, conn->uri->port) < 0)
811 812 813 814
        goto cleanup;

    if (esxVI_Context_Alloc(&priv->vCenter) < 0 ||
        esxVI_Context_Connect(priv->vCenter, url, ipAddress, username,
815
                              password, priv->parsedUri) < 0) {
816 817 818 819
        goto cleanup;
    }

    if (priv->vCenter->productVersion != esxVI_ProductVersion_VPX25 &&
M
Matthias Bolte 已提交
820 821
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX40 &&
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX41 &&
P
Patrice LACHANCE 已提交
822 823
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX4x &&
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX50 &&
M
Martin Kletzander 已提交
824
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX51 &&
P
Patrice LACHANCE 已提交
825
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX5x) {
826 827 828
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("%s is neither a vCenter 2.5, 4.x nor 5.x server"),
                       hostname);
829 830 831
        goto cleanup;
    }

832
    if (hostSystemIpAddress) {
833 834
        if (esxVI_Context_LookupManagedObjectsByHostSystemIp
              (priv->vCenter, hostSystemIpAddress) < 0) {
835 836 837
            goto cleanup;
        }
    } else {
838 839
        if (esxVI_Context_LookupManagedObjectsByPath(priv->vCenter,
                                                     priv->parsedUri->path) < 0) {
840 841 842 843
            goto cleanup;
        }
    }

844 845
    result = 0;

846
 cleanup:
847
    VIR_FREE(username);
M
Matthias Bolte 已提交
848 849
    VIR_FREE(unescapedPassword);
    VIR_FREE(password);
850 851 852 853 854 855 856
    VIR_FREE(url);

    return result;
}



857
/*
858 859
 * URI format: {vpx|esx|gsx}://[<username>@]<hostname>[:<port>]/[<path>][?<query parameter>...]
 *             <path> = [<folder>/...]<datacenter>/[<folder>/...]<computeresource>[/<hostsystem>]
860
 *
861 862
 * If no port is specified the default port is set dependent on the scheme and
 * transport parameter:
863 864
 * - vpx+http  80
 * - vpx+https 443
865
 * - esx+http  80
866
 * - esx+https 443
867 868 869
 * - gsx+http  8222
 * - gsx+https 8333
 *
870 871 872
 * 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
873 874
 * can be omitted. As datacenters and computeresources can be organized in
 * folders those have to be included in <path>.
875
 *
876 877
 * Optional query parameters:
 * - transport={http|https}
878
 * - vcenter={<vcenter>|*}             only useful for an esx:// connection
879 880
 * - no_verify={0|1}
 * - auto_answer={0|1}
M
Matthias Bolte 已提交
881
 * - proxy=[{http|socks|socks4|socks4a|socks5}://]<hostname>[:<port>]
882
 *
883 884 885
 * If no transport parameter is specified https is used.
 *
 * The vcenter parameter is only necessary for migration, because the vCenter
886
 * server is in charge to initiate a migration between two ESX hosts. The
887
 * vcenter parameter can be set to an explicitly hostname or to *. If set to *,
888 889
 * 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.
890 891
 *
 * If the no_verify parameter is set to 1, this disables libcurl client checks
892
 * of the server's certificate. The default value is 0.
893 894 895
 *
 * 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
896
 * questions will be reported as errors. The default value is 0.
M
Matthias Bolte 已提交
897 898 899 900
 *
 * 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.
901 902
 */
static virDrvOpenStatus
903 904
esxConnectOpen(virConnectPtr conn, virConnectAuthPtr auth,
               unsigned int flags)
905
{
M
Matthias Bolte 已提交
906
    virDrvOpenStatus result = VIR_DRV_OPEN_ERROR;
907
    char *plus;
908
    esxPrivate *priv = NULL;
909
    char *potentialVCenterIpAddress = NULL;
M
Matthias Bolte 已提交
910
    char vCenterIpAddress[NI_MAXHOST] = "";
911

E
Eric Blake 已提交
912 913
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

914
    /* Decline if the URI is NULL or the scheme is NULL */
915
    if (!conn->uri || !conn->uri->scheme) {
916 917 918
        return VIR_DRV_OPEN_DECLINED;
    }

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

922
    if (!plus) {
923 924 925 926 927 928 929 930 931 932 933 934 935
        if (STRCASENEQ(conn->uri->scheme, "vpx") &&
            STRCASENEQ(conn->uri->scheme, "esx") &&
            STRCASENEQ(conn->uri->scheme, "gsx")) {
            return VIR_DRV_OPEN_DECLINED;
        }
    } else {
        if (plus - conn->uri->scheme != 3 ||
            (STRCASENEQLEN(conn->uri->scheme, "vpx", 3) &&
             STRCASENEQLEN(conn->uri->scheme, "esx", 3) &&
             STRCASENEQLEN(conn->uri->scheme, "gsx", 3))) {
            return VIR_DRV_OPEN_DECLINED;
        }

936 937 938
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Transport '%s' in URI scheme is not supported, try again "
                         "without the transport part"), plus + 1);
939 940 941
        return VIR_DRV_OPEN_ERROR;
    }

942
    if (STRCASENEQ(conn->uri->scheme, "vpx") &&
943
        conn->uri->path && STRNEQ(conn->uri->path, "/")) {
944 945 946 947
        VIR_WARN("Ignoring unexpected path '%s' for non-vpx scheme '%s'",
                 conn->uri->path, conn->uri->scheme);
    }

948
    /* Require server part */
949
    if (!conn->uri->server) {
950 951
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("URI is missing the server part"));
952 953 954 955
        return VIR_DRV_OPEN_ERROR;
    }

    /* Require auth */
956
    if (!auth || !auth->cb) {
957 958
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Missing or invalid auth pointer"));
959
        return VIR_DRV_OPEN_ERROR;
960 961 962
    }

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

966
    if (esxUtil_ParseUri(&priv->parsedUri, conn->uri) < 0) {
967 968 969
        goto cleanup;
    }

M
Matthias Bolte 已提交
970 971
    priv->maxVcpus = -1;
    priv->supportsVMotion = esxVI_Boolean_Undefined;
972
    priv->supportsLongMode = esxVI_Boolean_Undefined;
973 974
    priv->usedCpuTimeCounterId = -1;

M
Matthias Bolte 已提交
975 976 977 978 979 980 981
    /*
     * 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) {
982 983
        if (STRCASEEQ(conn->uri->scheme, "vpx") ||
            STRCASEEQ(conn->uri->scheme, "esx")) {
984
            if (STRCASEEQ(priv->parsedUri->transport, "https")) {
M
Matthias Bolte 已提交
985 986 987 988 989
                conn->uri->port = 443;
            } else {
                conn->uri->port = 80;
            }
        } else { /* GSX */
990
            if (STRCASEEQ(priv->parsedUri->transport, "https")) {
M
Matthias Bolte 已提交
991 992 993 994
                conn->uri->port = 8333;
            } else {
                conn->uri->port = 8222;
            }
995
        }
M
Matthias Bolte 已提交
996
    }
997

998 999 1000
    if (STRCASEEQ(conn->uri->scheme, "esx") ||
        STRCASEEQ(conn->uri->scheme, "gsx")) {
        /* Connect to host */
1001
        if (esxConnectToHost(priv, conn, auth,
1002
                             &potentialVCenterIpAddress) < 0) {
M
Matthias Bolte 已提交
1003
            goto cleanup;
1004
        }
1005

1006
        /* Connect to vCenter */
1007
        if (priv->parsedUri->vCenter) {
1008
            if (STREQ(priv->parsedUri->vCenter, "*")) {
1009
                if (!potentialVCenterIpAddress) {
1010 1011
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("This host is not managed by a vCenter"));
M
Matthias Bolte 已提交
1012
                    goto cleanup;
1013 1014
                }

1015 1016
                if (!virStrcpyStatic(vCenterIpAddress,
                                     potentialVCenterIpAddress)) {
1017 1018 1019
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("vCenter IP address %s too big for destination"),
                                   potentialVCenterIpAddress);
1020 1021 1022
                    goto cleanup;
                }
            } else {
1023
                if (esxUtil_ResolveHostname(priv->parsedUri->vCenter,
1024 1025 1026
                                            vCenterIpAddress, NI_MAXHOST) < 0) {
                    goto cleanup;
                }
1027

1028
                if (potentialVCenterIpAddress &&
1029
                    STRNEQ(vCenterIpAddress, potentialVCenterIpAddress)) {
1030 1031 1032 1033 1034 1035
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("This host is managed by a vCenter with IP "
                                     "address %s, but a mismachting vCenter '%s' "
                                     "(%s) has been specified"),
                                   potentialVCenterIpAddress, priv->parsedUri->vCenter,
                                   vCenterIpAddress);
M
Matthias Bolte 已提交
1036
                    goto cleanup;
1037 1038
                }
            }
1039

1040
            if (esxConnectToVCenter(priv, conn, auth,
1041
                                    vCenterIpAddress,
1042
                                    priv->host->ipAddress) < 0) {
1043 1044
                goto cleanup;
            }
1045 1046
        }

1047 1048 1049
        priv->primary = priv->host;
    } else { /* VPX */
        /* Connect to vCenter */
1050
        if (esxConnectToVCenter(priv, conn, auth,
1051 1052
                                conn->uri->server,
                                NULL) < 0) {
M
Matthias Bolte 已提交
1053
            goto cleanup;
1054 1055
        }

1056
        priv->primary = priv->vCenter;
1057 1058
    }

M
Matthias Bolte 已提交
1059
    /* Setup capabilities */
1060
    priv->caps = esxCapsInit(priv);
1061

1062
    if (!priv->caps) {
M
Matthias Bolte 已提交
1063
        goto cleanup;
1064 1065
    }

1066
    if (!(priv->xmlopt = virVMXDomainXMLConfInit()))
1067 1068
        goto cleanup;

1069 1070
    conn->privateData = priv;
    priv = NULL;
M
Matthias Bolte 已提交
1071
    result = VIR_DRV_OPEN_SUCCESS;
1072

1073
 cleanup:
1074
    esxFreePrivate(&priv);
1075
    VIR_FREE(potentialVCenterIpAddress);
1076

M
Matthias Bolte 已提交
1077
    return result;
1078 1079 1080 1081 1082
}



static int
1083
esxConnectClose(virConnectPtr conn)
1084
{
M
Matthias Bolte 已提交
1085
    esxPrivate *priv = conn->privateData;
E
Eric Blake 已提交
1086
    int result = 0;
1087

1088
    if (priv->host) {
1089 1090 1091 1092 1093
        if (esxVI_EnsureSession(priv->host) < 0 ||
            esxVI_Logout(priv->host) < 0) {
            result = -1;
        }
    }
1094

1095
    if (priv->vCenter) {
E
Eric Blake 已提交
1096 1097 1098 1099
        if (esxVI_EnsureSession(priv->vCenter) < 0 ||
            esxVI_Logout(priv->vCenter) < 0) {
            result = -1;
        }
1100 1101
    }

1102
    esxFreePrivate(&priv);
1103 1104 1105

    conn->privateData = NULL;

E
Eric Blake 已提交
1106
    return result;
1107 1108 1109 1110 1111
}



static esxVI_Boolean
1112
esxSupportsVMotion(esxPrivate *priv)
1113 1114 1115 1116
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;

M
Matthias Bolte 已提交
1117 1118
    if (priv->supportsVMotion != esxVI_Boolean_Undefined) {
        return priv->supportsVMotion;
1119 1120
    }

1121
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1122
        return esxVI_Boolean_Undefined;
1123 1124
    }

1125
    if (esxVI_String_AppendValueToList(&propertyNameList,
1126
                                       "capability.vmotionSupported") < 0 ||
1127
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
1128 1129
                                         &hostSystem) < 0 ||
        esxVI_GetBoolean(hostSystem, "capability.vmotionSupported",
1130 1131 1132
                         &priv->supportsVMotion,
                         esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
1133 1134
    }

1135
 cleanup:
M
Matthias Bolte 已提交
1136 1137 1138 1139
    /*
     * 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.
     */
1140 1141 1142
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
1143
    return priv->supportsVMotion;
1144 1145 1146 1147 1148
}



static int
1149
esxConnectSupportsFeature(virConnectPtr conn, int feature)
1150
{
M
Matthias Bolte 已提交
1151
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1152
    esxVI_Boolean supportsVMotion = esxVI_Boolean_Undefined;
1153 1154 1155

    switch (feature) {
      case VIR_DRV_FEATURE_MIGRATION_V1:
1156
        supportsVMotion = esxSupportsVMotion(priv);
1157

M
Matthias Bolte 已提交
1158
        if (supportsVMotion == esxVI_Boolean_Undefined) {
1159 1160 1161
            return -1;
        }

M
Matthias Bolte 已提交
1162
        /* Migration is only possible via a vCenter and if VMotion is enabled */
1163
        return priv->vCenter &&
M
Matthias Bolte 已提交
1164
               supportsVMotion == esxVI_Boolean_True ? 1 : 0;
1165 1166 1167 1168 1169 1170 1171 1172 1173

      default:
        return 0;
    }
}



static const char *
1174
esxConnectGetType(virConnectPtr conn ATTRIBUTE_UNUSED)
1175 1176 1177 1178 1179 1180 1181
{
    return "ESX";
}



static int
1182
esxConnectGetVersion(virConnectPtr conn, unsigned long *version)
1183
{
M
Matthias Bolte 已提交
1184
    esxPrivate *priv = conn->privateData;
1185

1186
    if (virParseVersionString(priv->primary->service->about->version,
1187
                              version, false) < 0) {
1188 1189 1190
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not parse version number from '%s'"),
                       priv->primary->service->about->version);
1191

1192
        return -1;
1193 1194 1195 1196 1197 1198 1199 1200
    }

    return 0;
}



static char *
1201
esxConnectGetHostname(virConnectPtr conn)
1202
{
M
Matthias Bolte 已提交
1203
    esxPrivate *priv = conn->privateData;
1204 1205 1206 1207 1208 1209 1210
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    const char *hostName = NULL;
    const char *domainName = NULL;
    char *complete = NULL;

1211
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1212
        return NULL;
1213 1214 1215
    }

    if (esxVI_String_AppendValueListToList
1216
          (&propertyNameList,
1217 1218
           "config.network.dnsConfig.hostName\0"
           "config.network.dnsConfig.domainName\0") < 0 ||
1219 1220
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1221
        goto cleanup;
1222 1223
    }

1224
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
1225 1226 1227
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name,
                  "config.network.dnsConfig.hostName")) {
1228
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1229
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1230
                goto cleanup;
1231 1232 1233 1234 1235
            }

            hostName = dynamicProperty->val->string;
        } else if (STREQ(dynamicProperty->name,
                         "config.network.dnsConfig.domainName")) {
1236
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1237
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1238
                goto cleanup;
1239 1240 1241 1242 1243 1244 1245 1246
            }

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

1247
    if (!hostName || strlen(hostName) < 1) {
1248 1249
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing or empty 'hostName' property"));
M
Matthias Bolte 已提交
1250
        goto cleanup;
1251 1252
    }

1253
    if (!domainName || strlen(domainName) < 1) {
1254
        if (VIR_STRDUP(complete, hostName) < 0)
M
Matthias Bolte 已提交
1255
            goto cleanup;
1256
    } else {
1257
        if (virAsprintf(&complete, "%s.%s", hostName, domainName) < 0)
M
Matthias Bolte 已提交
1258
            goto cleanup;
1259 1260
    }

1261
 cleanup:
M
Matthias Bolte 已提交
1262 1263
    /*
     * If we goto cleanup in case of an error then complete is still NULL,
1264
     * either VIR_STRDUP returned -1 or virAsprintf failed. When virAsprintf
M
Matthias Bolte 已提交
1265 1266
     * fails it guarantees setting complete to NULL
     */
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return complete;
}



static int
esxNodeGetInfo(virConnectPtr conn, virNodeInfoPtr nodeinfo)
{
M
Matthias Bolte 已提交
1278
    int result = -1;
M
Matthias Bolte 已提交
1279
    esxPrivate *priv = conn->privateData;
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
    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;

1291
    memset(nodeinfo, 0, sizeof(*nodeinfo));
1292

1293
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1294
        return -1;
1295 1296
    }

1297
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1298 1299 1300 1301 1302 1303 1304
                                           "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 ||
1305 1306
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1307
        goto cleanup;
1308 1309
    }

1310
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
1311 1312
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuInfo.hz")) {
1313
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1314
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1315
                goto cleanup;
1316 1317 1318 1319 1320
            }

            cpuInfo_hz = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuCores")) {
1321
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1322
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1323
                goto cleanup;
1324 1325 1326 1327 1328
            }

            cpuInfo_numCpuCores = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuPackages")) {
1329
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1330
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1331
                goto cleanup;
1332 1333 1334 1335 1336
            }

            cpuInfo_numCpuPackages = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuThreads")) {
1337
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1338
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1339
                goto cleanup;
1340 1341 1342 1343
            }

            cpuInfo_numCpuThreads = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name, "hardware.memorySize")) {
1344
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1345
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1346
                goto cleanup;
1347 1348 1349 1350 1351
            }

            memorySize = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.numaInfo.numNodes")) {
1352
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1353
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1354
                goto cleanup;
1355 1356 1357 1358 1359
            }

            numaInfo_numNodes = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "summary.hardware.cpuModel")) {
1360
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1361
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1362
                goto cleanup;
1363 1364 1365 1366 1367 1368
            }

            ptr = dynamicProperty->val->string;

            /* Strip the string to fit more relevant information in 32 chars */
            while (*ptr != '\0') {
M
Matthias Bolte 已提交
1369 1370
                if (STRPREFIX(ptr, "  ")) {
                    memmove(ptr, ptr + 1, strlen(ptr + 1) + 1);
1371
                    continue;
1372
                } else if (STRPREFIX(ptr, "(R)") || STRPREFIX(ptr, "(C)")) {
M
Matthias Bolte 已提交
1373
                    memmove(ptr, ptr + 3, strlen(ptr + 3) + 1);
1374
                    continue;
1375 1376 1377
                } else if (STRPREFIX(ptr, "(TM)")) {
                    memmove(ptr, ptr + 4, strlen(ptr + 4) + 1);
                    continue;
1378 1379 1380 1381 1382
                }

                ++ptr;
            }

1383 1384 1385
            if (!virStrncpy(nodeinfo->model, dynamicProperty->val->string,
                            sizeof(nodeinfo->model) - 1,
                            sizeof(nodeinfo->model))) {
1386 1387 1388
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("CPU Model %s too long for destination"),
                               dynamicProperty->val->string);
M
Matthias Bolte 已提交
1389
                goto cleanup;
C
Chris Lalancette 已提交
1390
            }
1391 1392 1393 1394 1395 1396 1397
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    nodeinfo->memory = memorySize / 1024; /* Scale from bytes to kilobytes */
    nodeinfo->cpus = cpuInfo_numCpuCores;
1398
    nodeinfo->mhz = cpuInfo_hz / (1000 * 1000); /* Scale from hz to mhz */
1399 1400 1401 1402 1403 1404 1405 1406 1407
    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 已提交
1408 1409
    result = 0;

1410
 cleanup:
1411 1412 1413 1414 1415 1416 1417 1418
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



1419
static char *
1420
esxConnectGetCapabilities(virConnectPtr conn)
1421
{
M
Matthias Bolte 已提交
1422
    esxPrivate *priv = conn->privateData;
1423

1424
    return virCapabilitiesFormatXML(priv->caps);
1425 1426 1427 1428
}



1429
static int
1430
esxConnectListDomains(virConnectPtr conn, int *ids, int maxids)
1431
{
M
Matthias Bolte 已提交
1432
    bool success = false;
M
Matthias Bolte 已提交
1433
    esxPrivate *priv = conn->privateData;
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;

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

1444
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1445
        return -1;
1446 1447
    }

1448
    if (esxVI_String_AppendValueToList(&propertyNameList,
1449
                                       "runtime.powerState") < 0 ||
1450 1451
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1452
        goto cleanup;
1453 1454
    }

1455
    for (virtualMachine = virtualMachineList; virtualMachine;
1456
         virtualMachine = virtualMachine->_next) {
1457
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1458
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1459
            goto cleanup;
1460 1461 1462 1463 1464 1465 1466 1467 1468
        }

        if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

        if (esxUtil_ParseVirtualMachineIDString(virtualMachine->obj->value,
                                                &ids[count]) < 0 ||
            ids[count] <= 0) {
1469 1470 1471
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to parse positive integer from '%s'"),
                           virtualMachine->obj->value);
M
Matthias Bolte 已提交
1472
            goto cleanup;
1473 1474 1475 1476 1477 1478 1479 1480 1481
        }

        count++;

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

M
Matthias Bolte 已提交
1482 1483
    success = true;

1484
 cleanup:
1485 1486 1487
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
1488
    return success ? count : -1;
1489 1490 1491 1492 1493
}



static int
1494
esxConnectNumOfDomains(virConnectPtr conn)
1495
{
M
Matthias Bolte 已提交
1496
    esxPrivate *priv = conn->privateData;
1497

1498
    if (esxVI_EnsureSession(priv->primary) < 0) {
1499 1500 1501
        return -1;
    }

1502
    return esxVI_LookupNumberOfDomainsByPowerState
1503
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, false);
1504 1505 1506 1507 1508 1509 1510
}



static virDomainPtr
esxDomainLookupByID(virConnectPtr conn, int id)
{
M
Matthias Bolte 已提交
1511
    esxPrivate *priv = conn->privateData;
1512 1513 1514 1515
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
M
Matthias Bolte 已提交
1516 1517 1518
    int id_candidate = -1;
    char *name_candidate = NULL;
    unsigned char uuid_candidate[VIR_UUID_BUFLEN];
1519 1520
    virDomainPtr domain = NULL;

1521
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1522
        return NULL;
1523 1524
    }

1525
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1526
                                           "configStatus\0"
1527 1528
                                           "name\0"
                                           "runtime.powerState\0"
1529
                                           "config.uuid\0") < 0 ||
1530 1531
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1532
        goto cleanup;
1533 1534
    }

1535
    for (virtualMachine = virtualMachineList; virtualMachine;
1536
         virtualMachine = virtualMachine->_next) {
1537
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1538
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1539
            goto cleanup;
1540 1541 1542 1543 1544 1545 1546
        }

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

M
Matthias Bolte 已提交
1547
        VIR_FREE(name_candidate);
1548

1549
        if (esxVI_GetVirtualMachineIdentity(virtualMachine,
M
Matthias Bolte 已提交
1550 1551
                                            &id_candidate, &name_candidate,
                                            uuid_candidate) < 0) {
M
Matthias Bolte 已提交
1552
            goto cleanup;
1553 1554
        }

M
Matthias Bolte 已提交
1555
        if (id != id_candidate) {
1556 1557 1558
            continue;
        }

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

1561
        if (!domain) {
M
Matthias Bolte 已提交
1562
            goto cleanup;
1563 1564 1565 1566 1567 1568 1569
        }

        domain->id = id;

        break;
    }

1570
    if (!domain) {
1571
        virReportError(VIR_ERR_NO_DOMAIN, _("No domain with ID %d"), id);
1572 1573
    }

1574
 cleanup:
1575 1576
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
M
Matthias Bolte 已提交
1577
    VIR_FREE(name_candidate);
1578 1579 1580 1581 1582 1583 1584 1585 1586

    return domain;
}



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

1595
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1596
        return NULL;
1597 1598
    }

1599
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1600
                                           "name\0"
1601
                                           "runtime.powerState\0") < 0 ||
1602
        esxVI_LookupVirtualMachineByUuid(priv->primary, uuid, propertyNameList,
1603
                                         &virtualMachine,
M
Matthias Bolte 已提交
1604
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1605 1606
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, &name, NULL) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1607
        goto cleanup;
1608 1609
    }

1610
    domain = virGetDomain(conn, name, uuid);
1611

1612
    if (!domain) {
M
Matthias Bolte 已提交
1613
        goto cleanup;
1614
    }
1615

1616 1617 1618 1619 1620
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1621 1622
    }

1623
 cleanup:
1624
    esxVI_String_Free(&propertyNameList);
1625 1626
    esxVI_ObjectContent_Free(&virtualMachine);
    VIR_FREE(name);
1627 1628 1629 1630 1631 1632 1633 1634 1635

    return domain;
}



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

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

1648
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1649
                                           "configStatus\0"
1650
                                           "runtime.powerState\0"
1651
                                           "config.uuid\0") < 0 ||
1652
        esxVI_LookupVirtualMachineByName(priv->primary, name, propertyNameList,
1653 1654
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
1655
        goto cleanup;
1656 1657
    }

1658
    if (!virtualMachine) {
1659
        virReportError(VIR_ERR_NO_DOMAIN, _("No domain with name '%s'"), name);
M
Matthias Bolte 已提交
1660
        goto cleanup;
1661
    }
1662

M
Matthias Bolte 已提交
1663 1664 1665
    if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, uuid) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
1666
    }
1667

1668
    domain = virGetDomain(conn, name, uuid);
1669

1670
    if (!domain) {
M
Matthias Bolte 已提交
1671
        goto cleanup;
1672 1673
    }

1674 1675 1676 1677 1678
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1679 1680
    }

1681
 cleanup:
1682
    esxVI_String_Free(&propertyNameList);
1683
    esxVI_ObjectContent_Free(&virtualMachine);
1684 1685 1686 1687 1688 1689 1690 1691 1692

    return domain;
}



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

1702
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1703
        return -1;
1704 1705
    }

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

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1716 1717
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1718
        goto cleanup;
1719 1720
    }

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

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

M
Matthias Bolte 已提交
1735 1736
    result = 0;

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

    return result;
}



static int
esxDomainResume(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1751
    int result = -1;
M
Matthias Bolte 已提交
1752
    esxPrivate *priv = domain->conn->privateData;
1753 1754 1755 1756 1757
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1758
    char *taskInfoErrorMessage = NULL;
1759

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

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

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

1778
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
1779
                             &task) < 0 ||
1780
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1781
                                    esxVI_Occurrence_RequiredItem,
1782
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1783
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1784
        goto cleanup;
1785 1786 1787
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1788 1789
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not resume domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
1790
        goto cleanup;
1791 1792
    }

M
Matthias Bolte 已提交
1793 1794
    result = 0;

1795
 cleanup:
1796 1797 1798
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1799
    VIR_FREE(taskInfoErrorMessage);
1800 1801 1802 1803 1804 1805 1806

    return result;
}



static int
1807
esxDomainShutdownFlags(virDomainPtr domain, unsigned int flags)
1808
{
M
Matthias Bolte 已提交
1809
    int result = -1;
M
Matthias Bolte 已提交
1810
    esxPrivate *priv = domain->conn->privateData;
1811 1812 1813 1814
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1815 1816
    virCheckFlags(0, -1);

1817
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1818
        return -1;
1819 1820
    }

1821
    if (esxVI_String_AppendValueToList(&propertyNameList,
1822
                                       "runtime.powerState") < 0 ||
1823
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1824
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1825
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1826
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1827
        goto cleanup;
1828 1829 1830
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1831 1832
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1833
        goto cleanup;
1834 1835
    }

1836
    if (esxVI_ShutdownGuest(priv->primary, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1837
        goto cleanup;
1838 1839
    }

M
Matthias Bolte 已提交
1840 1841
    result = 0;

1842
 cleanup:
1843 1844 1845 1846 1847 1848 1849
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}


1850 1851 1852 1853 1854 1855
static int
esxDomainShutdown(virDomainPtr domain)
{
    return esxDomainShutdownFlags(domain, 0);
}

1856 1857

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

E
Eric Blake 已提交
1866 1867
    virCheckFlags(0, -1);

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

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

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

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

M
Matthias Bolte 已提交
1891 1892
    result = 0;

1893
 cleanup:
1894 1895 1896 1897 1898 1899 1900 1901 1902
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
1903 1904
esxDomainDestroyFlags(virDomainPtr domain,
                      unsigned int flags)
1905
{
M
Matthias Bolte 已提交
1906
    int result = -1;
M
Matthias Bolte 已提交
1907
    esxPrivate *priv = domain->conn->privateData;
1908
    esxVI_Context *ctx = NULL;
1909 1910 1911 1912 1913
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1914
    char *taskInfoErrorMessage = NULL;
1915

1916 1917
    virCheckFlags(0, -1);

1918
    if (priv->vCenter) {
1919 1920 1921 1922 1923
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

1924
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
1925
        return -1;
1926 1927
    }

1928
    if (esxVI_String_AppendValueToList(&propertyNameList,
1929
                                       "runtime.powerState") < 0 ||
1930
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1931
          (ctx, domain->uuid, propertyNameList, &virtualMachine,
1932
           priv->parsedUri->autoAnswer) < 0 ||
1933
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1934
        goto cleanup;
1935 1936 1937
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1938 1939
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1940
        goto cleanup;
1941 1942
    }

1943
    if (esxVI_PowerOffVM_Task(ctx, virtualMachine->obj, &task) < 0 ||
1944 1945
        esxVI_WaitForTaskCompletion(ctx, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
1946
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1947
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1948
        goto cleanup;
1949 1950 1951
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1952 1953
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not destroy domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
1954
        goto cleanup;
1955 1956
    }

1957
    domain->id = -1;
M
Matthias Bolte 已提交
1958 1959
    result = 0;

1960
 cleanup:
1961 1962 1963
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1964
    VIR_FREE(taskInfoErrorMessage);
1965 1966 1967 1968 1969

    return result;
}


1970 1971 1972 1973 1974 1975
static int
esxDomainDestroy(virDomainPtr dom)
{
    return esxDomainDestroyFlags(dom, 0);
}

1976 1977

static char *
1978
esxDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED)
1979
{
1980
    char *osType;
1981

1982
    ignore_value(VIR_STRDUP(osType, "hvm"));
1983
    return osType;
1984 1985 1986 1987
}



1988
static unsigned long long
1989 1990
esxDomainGetMaxMemory(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1991
    esxPrivate *priv = domain->conn->privateData;
1992 1993 1994 1995 1996
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    unsigned long memoryMB = 0;

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

2001
    if (esxVI_String_AppendValueToList(&propertyNameList,
2002
                                       "config.hardware.memoryMB") < 0 ||
2003
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2004
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2005
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2006
        goto cleanup;
2007 2008
    }

2009
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
2010 2011
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2012
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2013
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2014
                goto cleanup;
2015 2016 2017
            }

            if (dynamicProperty->val->int32 < 0) {
2018 2019 2020
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Got invalid memory size %d"),
                               dynamicProperty->val->int32);
2021 2022 2023 2024 2025 2026 2027 2028 2029 2030
            } else {
                memoryMB = dynamicProperty->val->int32;
            }

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

2031
 cleanup:
2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042
    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 已提交
2043
    int result = -1;
M
Matthias Bolte 已提交
2044
    esxPrivate *priv = domain->conn->privateData;
2045
    esxVI_String *propertyNameList = NULL;
2046
    esxVI_ObjectContent *virtualMachine = NULL;
2047
    esxVI_VirtualMachinePowerState powerState;
2048 2049 2050
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2051
    char *taskInfoErrorMessage = NULL;
2052

2053
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2054
        return -1;
2055 2056
    }

2057 2058 2059 2060
    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "runtime.powerState") < 0 ||
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
2061
           priv->parsedUri->autoAnswer) < 0 ||
2062 2063 2064 2065 2066
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2067 2068
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered off"));
2069 2070 2071 2072
        goto cleanup;
    }

    if (esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
2073
        esxVI_Long_Alloc(&spec->memoryMB) < 0) {
M
Matthias Bolte 已提交
2074
        goto cleanup;
2075 2076
    }

2077
    /* max-memory must be a multiple of 4096 kilobyte */
2078
    spec->memoryMB->value =
2079
      VIR_DIV_UP(memory, 4096) * 4; /* Scale from kilobytes to megabytes */
2080

2081
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2082
                              &task) < 0 ||
2083
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2084
                                    esxVI_Occurrence_RequiredItem,
2085
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2086
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2087
        goto cleanup;
2088 2089 2090
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2091 2092 2093
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set max-memory to %lu kilobytes: %s"), memory,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2094
        goto cleanup;
2095 2096
    }

M
Matthias Bolte 已提交
2097 2098
    result = 0;

2099
 cleanup:
2100
    esxVI_String_Free(&propertyNameList);
2101 2102 2103
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2104
    VIR_FREE(taskInfoErrorMessage);
2105 2106 2107 2108 2109 2110 2111 2112 2113

    return result;
}



static int
esxDomainSetMemory(virDomainPtr domain, unsigned long memory)
{
M
Matthias Bolte 已提交
2114
    int result = -1;
M
Matthias Bolte 已提交
2115
    esxPrivate *priv = domain->conn->privateData;
2116 2117 2118 2119
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2120
    char *taskInfoErrorMessage = NULL;
2121

2122
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2123
        return -1;
2124 2125
    }

2126
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2127
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2128
           priv->parsedUri->autoAnswer) < 0 ||
2129 2130 2131
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0 ||
        esxVI_Long_Alloc(&spec->memoryAllocation->limit) < 0) {
M
Matthias Bolte 已提交
2132
        goto cleanup;
2133 2134 2135
    }

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

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

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2148 2149 2150
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set memory to %lu kilobytes: %s"), memory,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2151
        goto cleanup;
2152 2153
    }

M
Matthias Bolte 已提交
2154 2155
    result = 0;

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

    return result;
}



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

2176 2177 2178
static int
esxDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info)
{
M
Matthias Bolte 已提交
2179
    int result = -1;
M
Matthias Bolte 已提交
2180
    esxPrivate *priv = domain->conn->privateData;
2181 2182 2183 2184 2185
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int64_t memory_limit = -1;
2186
#if ESX_QUERY_FOR_USED_CPU_TIME
2187 2188 2189 2190 2191 2192 2193
    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;
2194 2195
    esxVI_PerfEntityMetricBase *perfEntityMetricBase = NULL;
    esxVI_PerfEntityMetricBase *perfEntityMetricBaseList = NULL;
2196 2197 2198
    esxVI_PerfEntityMetric *perfEntityMetric = NULL;
    esxVI_PerfMetricIntSeries *perfMetricIntSeries = NULL;
    esxVI_Long *value = NULL;
2199
#endif
2200

2201
    memset(info, 0, sizeof(*info));
M
Matthias Bolte 已提交
2202

2203
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2204
        return -1;
2205 2206
    }

2207
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2208 2209 2210 2211
                                           "runtime.powerState\0"
                                           "config.hardware.memoryMB\0"
                                           "config.hardware.numCPU\0"
                                           "config.memoryAllocation.limit\0") < 0 ||
2212
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2213
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2214
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2215
        goto cleanup;
2216 2217 2218 2219
    }

    info->state = VIR_DOMAIN_NOSTATE;

2220
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
2221 2222 2223
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.powerState")) {
            if (esxVI_VirtualMachinePowerState_CastFromAnyType
2224
                  (dynamicProperty->val, &powerState) < 0) {
M
Matthias Bolte 已提交
2225
                goto cleanup;
2226 2227
            }

2228 2229
            info->state = esxVI_VirtualMachinePowerState_ConvertToLibvirt
                            (powerState);
2230
        } else if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2231
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2232
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2233
                goto cleanup;
2234 2235 2236 2237
            }

            info->maxMem = dynamicProperty->val->int32 * 1024; /* Scale from megabyte to kilobyte */
        } else if (STREQ(dynamicProperty->name, "config.hardware.numCPU")) {
2238
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2239
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2240
                goto cleanup;
2241 2242 2243 2244 2245
            }

            info->nrVirtCpu = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "config.memoryAllocation.limit")) {
2246
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2247
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
2248
                goto cleanup;
2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263
            }

            memory_limit = dynamicProperty->val->int64;

            if (memory_limit > 0) {
                memory_limit *= 1024; /* Scale from megabyte to kilobyte */
            }
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    /* memory_limit < 0 means no memory limit is set */
    info->memory = memory_limit < 0 ? info->maxMem : memory_limit;

2264
#if ESX_QUERY_FOR_USED_CPU_TIME
2265
    /* Verify the cached 'used CPU time' performance counter ID */
2266
    /* FIXME: Currently no host for a vpx:// connection */
2267
    if (priv->host) {
2268 2269 2270 2271
        if (info->state == VIR_DOMAIN_RUNNING && priv->usedCpuTimeCounterId >= 0) {
            if (esxVI_Int_Alloc(&counterId) < 0) {
                goto cleanup;
            }
2272

2273
            counterId->value = priv->usedCpuTimeCounterId;
2274

2275 2276 2277
            if (esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                goto cleanup;
            }
2278

2279 2280 2281 2282
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfo) < 0) {
                goto cleanup;
            }
2283

2284 2285 2286 2287 2288
            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);
2289

2290 2291 2292 2293 2294
                priv->usedCpuTimeCounterId = -1;
            }

            esxVI_Int_Free(&counterIdList);
            esxVI_PerfCounterInfo_Free(&perfCounterInfo);
2295 2296
        }

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

2308
            for (perfMetricId = perfMetricIdList; perfMetricId;
2309 2310 2311
                 perfMetricId = perfMetricId->_next) {
                VIR_DEBUG("perfMetricId counterId %d, instance '%s'",
                          perfMetricId->counterId->value, perfMetricId->instance);
2312

2313
                counterId = NULL;
2314

2315 2316 2317 2318 2319
                if (esxVI_Int_DeepCopy(&counterId, perfMetricId->counterId) < 0 ||
                    esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                    goto cleanup;
                }
            }
2320

2321 2322
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfoList) < 0) {
M
Matthias Bolte 已提交
2323
                goto cleanup;
2324 2325
            }

2326
            for (perfCounterInfo = perfCounterInfoList; perfCounterInfo;
2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342
                 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;
                }
2343 2344
            }

2345
            if (priv->usedCpuTimeCounterId < 0) {
2346
                VIR_WARN("Could not find 'used CPU time' performance counter");
2347
            }
2348 2349
        }

2350 2351 2352 2353 2354 2355
        /*
         * 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);
2356

2357 2358 2359 2360 2361 2362
            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;
            }
2363

2364 2365 2366 2367 2368 2369 2370 2371 2372 2373
            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;
            }
2374

2375
            for (perfEntityMetricBase = perfEntityMetricBaseList;
2376
                 perfEntityMetricBase;
2377
                 perfEntityMetricBase = perfEntityMetricBase->_next) {
2378
                VIR_DEBUG("perfEntityMetric ...");
2379

2380 2381
                perfEntityMetric =
                  esxVI_PerfEntityMetric_DynamicCast(perfEntityMetricBase);
2382

2383
                if (!perfEntityMetric) {
2384 2385 2386
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("QueryPerf returned object with unexpected type '%s'"),
                                   esxVI_Type_ToString(perfEntityMetricBase->_type));
2387
                    goto cleanup;
2388
                }
2389

2390 2391
                perfMetricIntSeries =
                  esxVI_PerfMetricIntSeries_DynamicCast(perfEntityMetric->value);
2392

2393
                if (!perfMetricIntSeries) {
2394 2395 2396
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("QueryPerf returned object with unexpected type '%s'"),
                                   esxVI_Type_ToString(perfEntityMetric->value->_type));
2397
                    goto cleanup;
2398
                }
2399

2400
                for (; perfMetricIntSeries;
2401
                     perfMetricIntSeries = perfMetricIntSeries->_next) {
2402
                    VIR_DEBUG("perfMetricIntSeries ...");
2403

2404
                    for (value = perfMetricIntSeries->value;
2405
                         value;
2406 2407 2408
                         value = value->_next) {
                        VIR_DEBUG("value %lld", (long long int)value->value);
                    }
2409 2410 2411
                }
            }

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

2414
            /*
E
Eric Blake 已提交
2415
             * FIXME: Cannot map between relative used-cpu-time and absolute
2416 2417 2418
             *        info->cpuTime
             */
        }
2419
    }
2420
#endif
2421

M
Matthias Bolte 已提交
2422 2423
    result = 0;

2424
 cleanup:
2425
#if ESX_QUERY_FOR_USED_CPU_TIME
2426 2427 2428 2429
    /*
     * Remove values owned by data structures to prevent them from being freed
     * by the call to esxVI_PerfQuerySpec_Free().
     */
2430
    if (querySpec) {
2431 2432 2433
        querySpec->entity = NULL;
        querySpec->format = NULL;

2434
        if (querySpec->metricId) {
2435 2436 2437
            querySpec->metricId->instance = NULL;
        }
    }
2438
#endif
2439

2440 2441
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2442
#if ESX_QUERY_FOR_USED_CPU_TIME
2443 2444 2445 2446
    esxVI_PerfMetricId_Free(&perfMetricIdList);
    esxVI_Int_Free(&counterIdList);
    esxVI_PerfCounterInfo_Free(&perfCounterInfoList);
    esxVI_PerfQuerySpec_Free(&querySpec);
2447
    esxVI_PerfEntityMetricBase_Free(&perfEntityMetricBaseList);
2448
#endif
2449 2450 2451 2452 2453 2454

    return result;
}



2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488
static int
esxDomainGetState(virDomainPtr domain,
                  int *state,
                  int *reason,
                  unsigned int flags)
{
    int result = -1;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;

    virCheckFlags(0, -1);

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

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "runtime.powerState") < 0 ||
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
                                         propertyNameList, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
    }

    *state = esxVI_VirtualMachinePowerState_ConvertToLibvirt(powerState);

    if (reason)
        *reason = 0;

    result = 0;

2489
 cleanup:
2490 2491 2492 2493 2494 2495 2496 2497
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
}



2498
static int
2499 2500
esxDomainSetVcpusFlags(virDomainPtr domain, unsigned int nvcpus,
                       unsigned int flags)
2501
{
M
Matthias Bolte 已提交
2502
    int result = -1;
M
Matthias Bolte 已提交
2503
    esxPrivate *priv = domain->conn->privateData;
M
Matthias Bolte 已提交
2504
    int maxVcpus;
2505 2506 2507 2508
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2509
    char *taskInfoErrorMessage = NULL;
2510

2511
    if (flags != VIR_DOMAIN_AFFECT_LIVE) {
2512
        virReportError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
2513 2514 2515
        return -1;
    }

2516
    if (nvcpus < 1) {
2517 2518
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Requested number of virtual CPUs must at least be 1"));
M
Matthias Bolte 已提交
2519
        return -1;
2520 2521
    }

2522
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2523
        return -1;
2524 2525
    }

M
Matthias Bolte 已提交
2526
    maxVcpus = esxDomainGetMaxVcpus(domain);
2527

M
Matthias Bolte 已提交
2528
    if (maxVcpus < 0) {
M
Matthias Bolte 已提交
2529
        return -1;
2530 2531
    }

M
Matthias Bolte 已提交
2532
    if (nvcpus > maxVcpus) {
2533 2534 2535 2536
        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 已提交
2537
        return -1;
2538 2539
    }

2540
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2541
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2542
           priv->parsedUri->autoAnswer) < 0 ||
2543 2544
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Int_Alloc(&spec->numCPUs) < 0) {
M
Matthias Bolte 已提交
2545
        goto cleanup;
2546 2547 2548 2549
    }

    spec->numCPUs->value = nvcpus;

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

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2560 2561 2562
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set number of virtual CPUs to %d: %s"), nvcpus,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2563
        goto cleanup;
2564 2565
    }

M
Matthias Bolte 已提交
2566 2567
    result = 0;

2568
 cleanup:
2569 2570 2571
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2572
    VIR_FREE(taskInfoErrorMessage);
2573 2574 2575 2576 2577

    return result;
}


M
Matthias Bolte 已提交
2578

2579 2580 2581
static int
esxDomainSetVcpus(virDomainPtr domain, unsigned int nvcpus)
{
2582
    return esxDomainSetVcpusFlags(domain, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
2583 2584
}

2585

M
Matthias Bolte 已提交
2586

2587
static int
2588
esxDomainGetVcpusFlags(virDomainPtr domain, unsigned int flags)
2589
{
M
Matthias Bolte 已提交
2590
    esxPrivate *priv = domain->conn->privateData;
2591 2592 2593 2594
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

2595
    if (flags != (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_VCPU_MAXIMUM)) {
2596
        virReportError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
2597 2598 2599
        return -1;
    }

M
Matthias Bolte 已提交
2600 2601
    if (priv->maxVcpus > 0) {
        return priv->maxVcpus;
2602 2603
    }

M
Matthias Bolte 已提交
2604 2605
    priv->maxVcpus = -1;

2606
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2607
        return -1;
2608 2609
    }

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

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

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

2632
 cleanup:
2633 2634 2635
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
2636
    return priv->maxVcpus;
2637 2638
}

M
Matthias Bolte 已提交
2639 2640


2641 2642 2643
static int
esxDomainGetMaxVcpus(virDomainPtr domain)
{
2644
    return esxDomainGetVcpusFlags(domain, (VIR_DOMAIN_AFFECT_LIVE |
2645 2646
                                           VIR_DOMAIN_VCPU_MAXIMUM));
}
2647

M
Matthias Bolte 已提交
2648 2649


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

E
Eric Blake 已提交
2670 2671
    /* Flags checked by virDomainDefFormat */

2672
    memset(&data, 0, sizeof(data));
2673

2674
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2675
        return NULL;
2676 2677
    }

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

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

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

    if (virBufferError(&buffer)) {
2705
        virReportOOMError();
M
Matthias Bolte 已提交
2706
        goto cleanup;
2707 2708
    }

2709 2710
    url = virBufferContentAndReset(&buffer);

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

2715
    data.ctx = priv->primary;
2716

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

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

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

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

2739
        xml = virDomainDefFormat(def, flags);
2740 2741
    }

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

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

    return xml;
}



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

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

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

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

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

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

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

2793
    if (def) {
2794
        xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
2795 2796 2797 2798 2799 2800 2801 2802 2803
    }

    virDomainDefFree(def);

    return xml;
}



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

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

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

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

2826 2827 2828 2829 2830 2831 2832
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        return NULL;
    }

2833
    def = virDomainDefParseString(domainXml, priv->caps, priv->xmlopt,
2834 2835
                                  1 << VIR_DOMAIN_VIRT_VMWARE,
                                  VIR_DOMAIN_XML_INACTIVE);
M
Matthias Bolte 已提交
2836

2837
    if (!def) {
M
Matthias Bolte 已提交
2838 2839 2840
        return NULL;
    }

2841
    data.ctx = priv->primary;
2842
    data.datastorePathWithoutFileName = NULL;
2843 2844 2845 2846 2847 2848

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

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

    virDomainDefFree(def);

    return vmx;
}



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

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

2874
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2875
        return -1;
2876 2877
    }

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

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

        if (powerState == esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

2897
        names[count] = NULL;
2898

2899 2900 2901
        if (esxVI_GetVirtualMachineIdentity(virtualMachine, NULL, &names[count],
                                            NULL) < 0) {
            goto cleanup;
2902 2903
        }

2904 2905
        ++count;

2906 2907 2908 2909 2910
        if (count >= maxnames) {
            break;
        }
    }

M
Matthias Bolte 已提交
2911
    success = true;
2912

2913
 cleanup:
M
Matthias Bolte 已提交
2914 2915 2916 2917
    if (! success) {
        for (i = 0; i < count; ++i) {
            VIR_FREE(names[i]);
        }
2918

M
Matthias Bolte 已提交
2919
        count = -1;
2920 2921
    }

M
Matthias Bolte 已提交
2922 2923
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
2924

M
Matthias Bolte 已提交
2925
    return count;
2926 2927 2928 2929 2930
}



static int
2931
esxConnectNumOfDefinedDomains(virConnectPtr conn)
2932
{
M
Matthias Bolte 已提交
2933
    esxPrivate *priv = conn->privateData;
2934

2935
    if (esxVI_EnsureSession(priv->primary) < 0) {
2936 2937 2938
        return -1;
    }

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



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

2958 2959
    virCheckFlags(0, -1);

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

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

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

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

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

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

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

    return result;
}

3007 3008


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

3015 3016


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

3044
    memset(&data, 0, sizeof(data));
3045

3046
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3047
        return NULL;
M
Matthias Bolte 已提交
3048 3049 3050
    }

    /* Parse domain XML */
3051 3052
    def = virDomainDefParseString(xml, priv->caps, priv->xmlopt,
                                  1 << VIR_DOMAIN_VIRT_VMWARE,
M
Matthias Bolte 已提交
3053 3054
                                  VIR_DOMAIN_XML_INACTIVE);

3055
    if (!def) {
M
Matthias Bolte 已提交
3056
        return NULL;
M
Matthias Bolte 已提交
3057 3058 3059
    }

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

3066
    if (!virtualMachine &&
3067 3068 3069 3070 3071 3072
        esxVI_LookupVirtualMachineByName(priv->primary, def->name, NULL,
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
    }

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

    /* Build VMX from domain XML */
3082 3083 3084 3085 3086 3087 3088
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        goto cleanup;
    }

3089
    data.ctx = priv->primary;
3090
    data.datastorePathWithoutFileName = NULL;
3091 3092 3093 3094 3095 3096

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

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

3099
    if (!vmx) {
M
Matthias Bolte 已提交
3100
        goto cleanup;
M
Matthias Bolte 已提交
3101 3102
    }

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

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

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

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

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

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

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

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

3160 3161
    escapedName = esxUtil_EscapeDatastoreItem(def->name);

3162
    if (!escapedName) {
3163 3164 3165 3166
        goto cleanup;
    }

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

    if (virBufferError(&buffer)) {
3173
        virReportOOMError();
M
Matthias Bolte 已提交
3174
        goto cleanup;
M
Matthias Bolte 已提交
3175 3176 3177 3178
    }

    url = virBufferContentAndReset(&buffer);

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

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

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

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

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

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

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

3220
    if (domain) {
M
Matthias Bolte 已提交
3221 3222 3223 3224 3225
        domain->id = -1;
    }

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

3226
 cleanup:
3227
    if (!url) {
M
Matthias Bolte 已提交
3228 3229 3230
        virBufferFreeAndReset(&buffer);
    }

M
Matthias Bolte 已提交
3231 3232 3233 3234
    virDomainDefFree(def);
    VIR_FREE(vmx);
    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
3235
    VIR_FREE(escapedName);
M
Matthias Bolte 已提交
3236 3237 3238 3239 3240 3241 3242
    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);
3243
    VIR_FREE(taskInfoErrorMessage);
M
Matthias Bolte 已提交
3244 3245 3246 3247 3248 3249

    return domain;
}



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

3261 3262 3263 3264
    /* No managed save, so we explicitly reject
     * VIR_DOMAIN_UNDEFINE_MANAGED_SAVE.  No snapshot metadata for
     * ESX, so we can trivially ignore that flag.  */
    virCheckFlags(VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA, -1);
3265

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

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

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

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

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

M
Matthias Bolte 已提交
3296 3297
    result = 0;

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

    return result;
}


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

3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344
static int
esxDomainGetAutostart(virDomainPtr domain, int *autostart)
{
    int result = -1;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_AutoStartDefaults *defaults = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_AutoStartPowerInfo *powerInfo = NULL;
    esxVI_AutoStartPowerInfo *powerInfoList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;

    *autostart = 0;

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

    /* Check general autostart config */
    if (esxVI_LookupAutoStartDefaults(priv->primary, &defaults) < 0) {
        goto cleanup;
    }

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

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

3345
    if (!powerInfoList) {
3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356
        /* 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;
    }

3357
    for (powerInfo = powerInfoList; powerInfo;
3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369
         powerInfo = powerInfo->_next) {
        if (STREQ(powerInfo->key->value, virtualMachine->obj->value)) {
            if (STRCASEEQ(powerInfo->startAction, "powerOn")) {
                *autostart = 1;
            }

            break;
        }
    }

    result = 0;

3370
 cleanup:
3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426
    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;

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

    if (esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
                                         NULL, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_HostAutoStartManagerConfig_Alloc(&spec) < 0) {
        goto cleanup;
    }

    if (autostart) {
        /*
         * There is a general autostart option that affects the autostart
         * behavior of all domains. If it's disabled then no domain does
         * autostart. If it's enabled then the autostart behavior depends on
         * the per-domain autostart config.
         */
        if (esxVI_LookupAutoStartDefaults(priv->primary, &defaults) < 0) {
            goto cleanup;
        }

        if (defaults->enabled != esxVI_Boolean_True) {
            /*
             * Autostart is disabled in general. Check if no other domain is
             * in the list of autostarted domains, so it's safe to enable the
             * general autostart option without affecting the autostart
             * behavior of other domains.
             */
            if (esxVI_LookupAutoStartPowerInfoList(priv->primary,
                                                   &powerInfoList) < 0) {
                goto cleanup;
            }

3427
            for (powerInfo = powerInfoList; powerInfo;
3428 3429
                 powerInfo = powerInfo->_next) {
                if (STRNEQ(powerInfo->key->value, virtualMachine->obj->value)) {
3430 3431 3432
                    virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                                   _("Cannot enable general autostart option "
                                     "without affecting other domains"));
3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448
                    goto cleanup;
                }
            }

            /* Enable autostart in general */
            if (esxVI_AutoStartDefaults_Alloc(&spec->defaults) < 0) {
                goto cleanup;
            }

            spec->defaults->enabled = esxVI_Boolean_True;
        }
    }

    if (esxVI_AutoStartPowerInfo_Alloc(&newPowerInfo) < 0 ||
        esxVI_Int_Alloc(&newPowerInfo->startOrder) < 0 ||
        esxVI_Int_Alloc(&newPowerInfo->startDelay) < 0 ||
3449
        esxVI_Int_Alloc(&newPowerInfo->stopDelay) < 0) {
3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460
        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";

3461 3462 3463 3464 3465
    if (esxVI_AutoStartPowerInfo_AppendToList(&spec->powerInfo,
                                              newPowerInfo) < 0) {
        goto cleanup;
    }

3466
    newPowerInfo = NULL;
3467

3468 3469 3470 3471 3472 3473 3474 3475 3476
    if (esxVI_ReconfigureAutostart
          (priv->primary,
           priv->primary->hostSystem->configManager->autoStartManager,
           spec) < 0) {
        goto cleanup;
    }

    result = 0;

3477
 cleanup:
3478
    if (newPowerInfo) {
3479 3480 3481 3482 3483 3484 3485 3486 3487 3488
        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);

3489
    esxVI_AutoStartPowerInfo_Free(&newPowerInfo);
3490

3491 3492 3493 3494 3495
    return result;
}



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

3531
    if (VIR_STRDUP(type, "allocation") < 0)
3532
        return NULL;
3533

3534
    if (nparams) {
3535 3536
        *nparams = 3; /* reservation, limit, shares */
    }
3537 3538 3539 3540 3541 3542 3543

    return type;
}



static int
3544 3545 3546
esxDomainGetSchedulerParametersFlags(virDomainPtr domain,
                                     virTypedParameterPtr params, int *nparams,
                                     unsigned int flags)
3547
{
M
Matthias Bolte 已提交
3548
    int result = -1;
M
Matthias Bolte 已提交
3549
    esxPrivate *priv = domain->conn->privateData;
3550 3551 3552 3553 3554
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    unsigned int mask = 0;
3555
    size_t i = 0;
3556

3557 3558
    virCheckFlags(0, -1);

3559
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3560
        return -1;
3561 3562
    }

3563
    if (esxVI_String_AppendValueListToList(&propertyNameList,
3564 3565 3566
                                           "config.cpuAllocation.reservation\0"
                                           "config.cpuAllocation.limit\0"
                                           "config.cpuAllocation.shares\0") < 0 ||
3567
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
3568
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3569
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3570
        goto cleanup;
3571 3572 3573
    }

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

            switch (sharesInfo->level) {
              case esxVI_SharesLevel_Custom:
                params[i].value.i = sharesInfo->shares->value;
                break;

              case esxVI_SharesLevel_Low:
                params[i].value.i = -1;
                break;

              case esxVI_SharesLevel_Normal:
                params[i].value.i = -2;
                break;

              case esxVI_SharesLevel_High:
                params[i].value.i = -3;
                break;

              default:
3633 3634 3635
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Shares level has unknown value %d"),
                               (int)sharesInfo->level);
3636
                esxVI_SharesInfo_Free(&sharesInfo);
M
Matthias Bolte 已提交
3637
                goto cleanup;
3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649
            }

            esxVI_SharesInfo_Free(&sharesInfo);

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

    *nparams = i;
M
Matthias Bolte 已提交
3650
    result = 0;
3651

3652
 cleanup:
3653 3654 3655 3656 3657 3658
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
}

3659 3660 3661 3662 3663 3664
static int
esxDomainGetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int *nparams)
{
    return esxDomainGetSchedulerParametersFlags(domain, params, nparams, 0);
}
3665 3666 3667


static int
3668 3669 3670
esxDomainSetSchedulerParametersFlags(virDomainPtr domain,
                                     virTypedParameterPtr params, int nparams,
                                     unsigned int flags)
3671
{
M
Matthias Bolte 已提交
3672
    int result = -1;
M
Matthias Bolte 已提交
3673
    esxPrivate *priv = domain->conn->privateData;
3674 3675 3676 3677 3678
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3679
    char *taskInfoErrorMessage = NULL;
3680
    size_t i;
3681

3682
    virCheckFlags(0, -1);
3683 3684 3685 3686 3687 3688 3689 3690
    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)
3691
        return -1;
3692

3693
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3694
        return -1;
3695 3696
    }

3697
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3698
          (priv->primary, domain->uuid, NULL, &virtualMachine,
3699
           priv->parsedUri->autoAnswer) < 0 ||
3700 3701
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->cpuAllocation) < 0) {
M
Matthias Bolte 已提交
3702
        goto cleanup;
3703 3704 3705
    }

    for (i = 0; i < nparams; ++i) {
3706
        if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_RESERVATION)) {
3707
            if (esxVI_Long_Alloc(&spec->cpuAllocation->reservation) < 0) {
M
Matthias Bolte 已提交
3708
                goto cleanup;
3709 3710 3711
            }

            if (params[i].value.l < 0) {
3712 3713 3714
                virReportError(VIR_ERR_INVALID_ARG,
                               _("Could not set reservation to %lld MHz, expecting "
                                 "positive value"), params[i].value.l);
M
Matthias Bolte 已提交
3715
                goto cleanup;
3716 3717 3718
            }

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

            if (params[i].value.l < -1) {
3725 3726 3727 3728
                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 已提交
3729
                goto cleanup;
3730 3731 3732
            }

            spec->cpuAllocation->limit->value = params[i].value.l;
3733
        } else if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_SHARES)) {
3734 3735
            if (esxVI_SharesInfo_Alloc(&sharesInfo) < 0 ||
                esxVI_Int_Alloc(&sharesInfo->shares) < 0) {
M
Matthias Bolte 已提交
3736
                goto cleanup;
3737 3738 3739
            }

            spec->cpuAllocation->shares = sharesInfo;
3740
            sharesInfo = NULL;
3741

3742
            if (params[i].value.i >= 0) {
3743
                spec->cpuAllocation->shares->level = esxVI_SharesLevel_Custom;
3744
                spec->cpuAllocation->shares->shares->value = params[i].value.i;
3745
            } else {
3746
                switch (params[i].value.i) {
3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764
                  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:
3765 3766 3767 3768
                    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 已提交
3769
                    goto cleanup;
3770 3771 3772 3773 3774
                }
            }
        }
    }

3775
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
3776
                              &task) < 0 ||
3777
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3778
                                    esxVI_Occurrence_RequiredItem,
3779
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3780
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3781
        goto cleanup;
3782 3783 3784
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3785 3786 3787
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not change scheduler parameters: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3788
        goto cleanup;
3789 3790
    }

M
Matthias Bolte 已提交
3791 3792
    result = 0;

3793
 cleanup:
3794
    esxVI_SharesInfo_Free(&sharesInfo);
3795 3796 3797
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
3798
    VIR_FREE(taskInfoErrorMessage);
3799 3800 3801 3802

    return result;
}

3803 3804 3805 3806 3807 3808
static int
esxDomainSetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int nparams)
{
    return esxDomainSetSchedulerParametersFlags(domain, params, nparams, 0);
}
3809

E
Eric Blake 已提交
3810 3811 3812 3813 3814 3815
/* The subset of migration flags we are able to support.  */
#define ESX_MIGRATION_FLAGS                     \
    (VIR_MIGRATE_PERSIST_DEST |                 \
     VIR_MIGRATE_UNDEFINE_SOURCE |              \
     VIR_MIGRATE_LIVE |                         \
     VIR_MIGRATE_PAUSED)
3816 3817 3818 3819 3820

static int
esxDomainMigratePrepare(virConnectPtr dconn,
                        char **cookie ATTRIBUTE_UNUSED,
                        int *cookielen ATTRIBUTE_UNUSED,
3821 3822
                        const char *uri_in ATTRIBUTE_UNUSED,
                        char **uri_out,
E
Eric Blake 已提交
3823
                        unsigned long flags,
3824 3825 3826
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
3827
    esxPrivate *priv = dconn->privateData;
3828

E
Eric Blake 已提交
3829 3830
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

3831
    if (!uri_in) {
3832 3833 3834
        if (virAsprintf(uri_out, "vpxmigr://%s/%s/%s",
                        priv->vCenter->ipAddress,
                        priv->vCenter->computeResource->resourcePool->value,
3835
                        priv->vCenter->hostSystem->_reference->value) < 0)
3836
            return -1;
3837 3838
    }

3839
    return 0;
3840 3841 3842 3843 3844 3845 3846 3847 3848
}



static int
esxDomainMigratePerform(virDomainPtr domain,
                        const char *cookie ATTRIBUTE_UNUSED,
                        int cookielen ATTRIBUTE_UNUSED,
                        const char *uri,
E
Eric Blake 已提交
3849
                        unsigned long flags,
3850 3851 3852
                        const char *dname,
                        unsigned long bandwidth ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
3853
    int result = -1;
M
Matthias Bolte 已提交
3854
    esxPrivate *priv = domain->conn->privateData;
M
Martin Kletzander 已提交
3855
    virURIPtr parsedUri = NULL;
3856 3857 3858
    char *saveptr;
    char *path_resourcePool;
    char *path_hostSystem;
3859
    esxVI_ObjectContent *virtualMachine = NULL;
3860 3861
    esxVI_ManagedObjectReference resourcePool;
    esxVI_ManagedObjectReference hostSystem;
3862 3863 3864
    esxVI_Event *eventList = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3865
    char *taskInfoErrorMessage = NULL;
3866

E
Eric Blake 已提交
3867 3868
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

3869
    if (!priv->vCenter) {
3870 3871
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration not possible without a vCenter"));
M
Matthias Bolte 已提交
3872
        return -1;
3873 3874
    }

3875
    if (dname) {
3876 3877
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Renaming domains on migration not supported"));
M
Matthias Bolte 已提交
3878
        return -1;
3879 3880
    }

3881
    if (esxVI_EnsureSession(priv->vCenter) < 0) {
M
Matthias Bolte 已提交
3882
        return -1;
3883 3884
    }

3885
    /* Parse migration URI */
3886
    if (!(parsedUri = virURIParse(uri)))
M
Matthias Bolte 已提交
3887
        return -1;
3888

3889
    if (!parsedUri->scheme || STRCASENEQ(parsedUri->scheme, "vpxmigr")) {
3890 3891
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Only vpxmigr:// migration URIs are supported"));
M
Matthias Bolte 已提交
3892
        goto cleanup;
3893 3894
    }

3895
    if (STRCASENEQ(priv->vCenter->ipAddress, parsedUri->server)) {
3896 3897 3898
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration source and destination have to refer to "
                         "the same vCenter"));
3899 3900 3901 3902 3903 3904
        goto cleanup;
    }

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

3905
    if (!path_resourcePool || !path_hostSystem) {
3906 3907
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration URI has to specify resource pool and host system"));
M
Matthias Bolte 已提交
3908
        goto cleanup;
3909 3910
    }

3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923
    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,
3924
           priv->parsedUri->autoAnswer) < 0) {
M
Matthias Bolte 已提交
3925
        goto cleanup;
3926 3927 3928
    }

    /* Validate the purposed migration */
3929
    if (esxVI_ValidateMigration(priv->vCenter, virtualMachine->obj,
3930 3931
                                esxVI_VirtualMachinePowerState_Undefined, NULL,
                                &resourcePool, &hostSystem, &eventList) < 0) {
M
Matthias Bolte 已提交
3932
        goto cleanup;
3933 3934
    }

3935
    if (eventList) {
3936 3937 3938 3939
        /*
         * FIXME: Need to report the complete list of events. Limit reporting
         *        to the first event for now.
         */
3940
        if (eventList->fullFormattedMessage) {
3941 3942 3943
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not migrate domain, validation reported a "
                             "problem: %s"), eventList->fullFormattedMessage);
3944
        } else {
3945 3946 3947
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Could not migrate domain, validation reported a "
                             "problem"));
3948 3949
        }

M
Matthias Bolte 已提交
3950
        goto cleanup;
3951 3952 3953
    }

    /* Perform the purposed migration */
3954 3955
    if (esxVI_MigrateVM_Task(priv->vCenter, virtualMachine->obj,
                             &resourcePool, &hostSystem,
3956 3957 3958
                             esxVI_VirtualMachineMovePriority_DefaultPriority,
                             esxVI_VirtualMachinePowerState_Undefined,
                             &task) < 0 ||
3959
        esxVI_WaitForTaskCompletion(priv->vCenter, task, domain->uuid,
3960
                                    esxVI_Occurrence_RequiredItem,
3961
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3962
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3963
        goto cleanup;
3964 3965 3966
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3967 3968 3969 3970
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not migrate domain, migration task finished with "
                         "an error: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3971
        goto cleanup;
3972 3973
    }

M
Matthias Bolte 已提交
3974 3975
    result = 0;

3976
 cleanup:
3977
    virURIFree(parsedUri);
3978 3979 3980
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Event_Free(&eventList);
    esxVI_ManagedObjectReference_Free(&task);
3981
    VIR_FREE(taskInfoErrorMessage);
3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992

    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 已提交
3993
                       unsigned long flags)
3994
{
E
Eric Blake 已提交
3995 3996
    virCheckFlags(ESX_MIGRATION_FLAGS, NULL);

3997 3998 3999 4000 4001
    return esxDomainLookupByName(dconn, dname);
}



M
Matthias Bolte 已提交
4002 4003 4004 4005
static unsigned long long
esxNodeGetFreeMemory(virConnectPtr conn)
{
    unsigned long long result = 0;
M
Matthias Bolte 已提交
4006
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
4007 4008 4009 4010 4011
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *resourcePool = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ResourcePoolResourceUsage *resourcePoolResourceUsage = NULL;

4012
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4013
        return 0;
M
Matthias Bolte 已提交
4014 4015 4016
    }

    /* Get memory usage of resource pool */
4017
    if (esxVI_String_AppendValueToList(&propertyNameList,
M
Matthias Bolte 已提交
4018
                                       "runtime.memory") < 0 ||
4019 4020
        esxVI_LookupObjectContentByType(priv->primary,
                                        priv->primary->computeResource->resourcePool,
4021
                                        "ResourcePool", propertyNameList,
4022 4023
                                        &resourcePool,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4024
        goto cleanup;
M
Matthias Bolte 已提交
4025 4026
    }

4027
    for (dynamicProperty = resourcePool->propSet; dynamicProperty;
M
Matthias Bolte 已提交
4028 4029 4030
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.memory")) {
            if (esxVI_ResourcePoolResourceUsage_CastFromAnyType
4031
                  (dynamicProperty->val, &resourcePoolResourceUsage) < 0) {
M
Matthias Bolte 已提交
4032
                goto cleanup;
M
Matthias Bolte 已提交
4033 4034 4035 4036 4037 4038 4039 4040
            }

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

4041
    if (!resourcePoolResourceUsage) {
4042 4043
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not retrieve memory usage of resource pool"));
M
Matthias Bolte 已提交
4044
        goto cleanup;
M
Matthias Bolte 已提交
4045 4046 4047 4048
    }

    result = resourcePoolResourceUsage->unreservedForVm->value;

4049
 cleanup:
M
Matthias Bolte 已提交
4050 4051 4052 4053 4054 4055 4056 4057 4058
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&resourcePool);
    esxVI_ResourcePoolResourceUsage_Free(&resourcePoolResourceUsage);

    return result;
}



4059
static int
4060
esxConnectIsEncrypted(virConnectPtr conn)
4061
{
M
Matthias Bolte 已提交
4062
    esxPrivate *priv = conn->privateData;
4063

4064
    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
4065 4066 4067 4068 4069 4070 4071 4072 4073
        return 1;
    } else {
        return 0;
    }
}



static int
4074
esxConnectIsSecure(virConnectPtr conn)
4075
{
M
Matthias Bolte 已提交
4076
    esxPrivate *priv = conn->privateData;
4077

4078
    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
4079 4080 4081 4082 4083 4084 4085 4086
        return 1;
    } else {
        return 0;
    }
}



4087
static int
4088
esxConnectIsAlive(virConnectPtr conn)
4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103
{
    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;
}



4104 4105 4106
static int
esxDomainIsActive(virDomainPtr domain)
{
M
Matthias Bolte 已提交
4107
    int result = -1;
M
Matthias Bolte 已提交
4108
    esxPrivate *priv = domain->conn->privateData;
4109 4110 4111 4112
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

4113
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4114
        return -1;
4115 4116
    }

4117
    if (esxVI_String_AppendValueToList(&propertyNameList,
4118
                                       "runtime.powerState") < 0 ||
4119
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
4120
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
4121
                                         esxVI_Occurrence_RequiredItem) < 0 ||
4122
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
4123
        goto cleanup;
4124 4125 4126 4127 4128 4129 4130 4131
    }

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

4132
 cleanup:
4133 4134 4135 4136 4137 4138 4139 4140 4141
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
4142
esxDomainIsPersistent(virDomainPtr domain)
4143
{
4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159
    /* 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;

4160
 cleanup:
4161 4162 4163
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
4164 4165
}

M
Matthias Bolte 已提交
4166 4167


4168 4169 4170
static int
esxDomainIsUpdated(virDomainPtr domain ATTRIBUTE_UNUSED)
{
4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186
    /* 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;

4187
 cleanup:
4188 4189 4190
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
4191
}
4192

M
Matthias Bolte 已提交
4193 4194


4195 4196
static virDomainSnapshotPtr
esxDomainSnapshotCreateXML(virDomainPtr domain, const char *xmlDesc,
4197
                           unsigned int flags)
4198 4199 4200 4201 4202 4203 4204 4205
{
    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;
4206
    char *taskInfoErrorMessage = NULL;
4207
    virDomainSnapshotPtr snapshot = NULL;
4208 4209
    bool diskOnly = (flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY) != 0;
    bool quiesce = (flags & VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE) != 0;
4210

4211 4212 4213 4214 4215
    /* 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);
4216

4217
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4218
        return NULL;
4219 4220
    }

4221
    def = virDomainSnapshotDefParseString(xmlDesc, priv->caps,
4222
                                          priv->xmlopt, 0, 0);
4223

4224
    if (!def) {
M
Matthias Bolte 已提交
4225
        return NULL;
4226 4227
    }

4228
    if (def->ndisks) {
4229 4230
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("disk snapshots not supported yet"));
4231 4232 4233
        return NULL;
    }

4234
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
4235
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4236
           priv->parsedUri->autoAnswer) < 0 ||
4237
        esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4238 4239
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, def->name,
4240
                                    &snapshotTree, NULL,
4241
                                    esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4242
        goto cleanup;
4243 4244
    }

4245
    if (snapshotTree) {
4246 4247
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Snapshot '%s' already exists"), def->name);
M
Matthias Bolte 已提交
4248
        goto cleanup;
4249 4250
    }

4251
    if (esxVI_CreateSnapshot_Task(priv->primary, virtualMachine->obj,
4252
                                  def->name, def->description,
4253 4254 4255
                                  diskOnly ? esxVI_Boolean_False : esxVI_Boolean_True,
                                  quiesce ? esxVI_Boolean_True : esxVI_Boolean_False,
                                  &task) < 0 ||
4256
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
4257
                                    esxVI_Occurrence_RequiredItem,
4258
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4259
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4260
        goto cleanup;
4261 4262 4263
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4264 4265
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not create snapshot: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4266
        goto cleanup;
4267 4268 4269 4270
    }

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

4271
 cleanup:
4272 4273 4274 4275
    virDomainSnapshotDefFree(def);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4276
    VIR_FREE(taskInfoErrorMessage);
4277 4278 4279 4280 4281 4282 4283

    return snapshot;
}



static char *
4284 4285
esxDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                            unsigned int flags)
4286 4287 4288 4289 4290 4291 4292 4293 4294
{
    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;

4295 4296
    virCheckFlags(0, NULL);

4297
    memset(&def, 0, sizeof(def));
4298

4299
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4300
        return NULL;
4301 4302
    }

4303
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4304 4305 4306 4307
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4308
        goto cleanup;
4309 4310 4311 4312
    }

    def.name = snapshot->name;
    def.description = snapshotTree->description;
4313
    def.parent = snapshotTreeParent ? snapshotTreeParent->name : NULL;
4314 4315 4316

    if (esxVI_DateTime_ConvertToCalendarTime(snapshotTree->createTime,
                                             &def.creationTime) < 0) {
M
Matthias Bolte 已提交
4317
        goto cleanup;
4318 4319 4320 4321 4322 4323 4324
    }

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

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

4325
    xml = virDomainSnapshotDefFormat(uuid_string, &def, flags, 0);
4326

4327
 cleanup:
4328 4329 4330 4331 4332 4333 4334 4335
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return xml;
}



static int
4336
esxDomainSnapshotNum(virDomainPtr domain, unsigned int flags)
4337
{
M
Matthias Bolte 已提交
4338
    int count;
4339 4340
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
4341
    bool recurse;
4342
    bool leaves;
4343

4344
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
4345 4346
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4347 4348

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) == 0;
4349
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4350

4351
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4352
        return -1;
4353 4354
    }

4355 4356 4357 4358
    /* ESX snapshots do not require libvirt to maintain any metadata.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA)
        return 0;

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

4364 4365
    count = esxVI_GetNumberOfSnapshotTrees(rootSnapshotTreeList, recurse,
                                           leaves);
4366 4367 4368

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

M
Matthias Bolte 已提交
4369
    return count;
4370 4371 4372 4373 4374 4375
}



static int
esxDomainSnapshotListNames(virDomainPtr domain, char **names, int nameslen,
4376
                           unsigned int flags)
4377
{
M
Matthias Bolte 已提交
4378
    int result;
4379 4380
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
4381
    bool recurse;
4382
    bool leaves;
4383 4384

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

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

4391
    if (!names || nameslen < 0) {
4392
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
4393 4394 4395
        return -1;
    }

4396
    if (nameslen == 0 || (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA)) {
4397 4398 4399
        return 0;
    }

4400
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4401
        return -1;
4402 4403
    }

4404
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4405
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4406
        return -1;
4407 4408
    }

4409
    result = esxVI_GetSnapshotTreeNames(rootSnapshotTreeList, names, nameslen,
4410
                                        recurse, leaves);
4411 4412 4413 4414 4415 4416 4417 4418

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



4419 4420 4421 4422 4423 4424 4425 4426
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;
4427
    bool leaves;
4428 4429

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
4430 4431
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4432 4433

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) != 0;
4434
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454

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

    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
                                         &rootSnapshotTreeList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotTreeList, snapshot->name,
                                    &snapshotTree, NULL,
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    /* ESX snapshots do not require libvirt to maintain any metadata.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA) {
        count = 0;
        goto cleanup;
    }

    count = esxVI_GetNumberOfSnapshotTrees(snapshotTree->childSnapshotList,
4455
                                           recurse, leaves);
4456

4457
 cleanup:
4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474
    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;
4475
    bool leaves;
4476 4477

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
4478 4479
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4480 4481

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) != 0;
4482
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4483

4484
    if (!names || nameslen < 0) {
4485
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511
        return -1;
    }

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

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

    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
                                         &rootSnapshotTreeList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotTreeList, snapshot->name,
                                    &snapshotTree, NULL,
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    /* ESX snapshots do not require libvirt to maintain any metadata.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA) {
        result = 0;
        goto cleanup;
    }

    result = esxVI_GetSnapshotTreeNames(snapshotTree->childSnapshotList,
4512
                                        names, nameslen, recurse, leaves);
4513

4514
 cleanup:
4515 4516 4517 4518 4519 4520 4521
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



4522 4523
static virDomainSnapshotPtr
esxDomainSnapshotLookupByName(virDomainPtr domain, const char *name,
4524
                              unsigned int flags)
4525 4526 4527 4528 4529 4530
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    virDomainSnapshotPtr snapshot = NULL;

4531 4532
    virCheckFlags(0, NULL);

4533
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4534
        return NULL;
4535 4536
    }

4537
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4538 4539
                                         &rootSnapshotTreeList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotTreeList, name, &snapshotTree,
4540
                                    NULL,
4541 4542 4543 4544 4545 4546
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    snapshot = virGetDomainSnapshot(domain, name);

4547
 cleanup:
4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return snapshot;
}



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

4561
    virCheckFlags(0, -1);
4562

4563
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4564
        return -1;
4565 4566
    }

4567
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4568 4569
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4570
        return -1;
4571 4572
    }

4573
    if (currentSnapshotTree) {
M
Matthias Bolte 已提交
4574 4575
        esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);
        return 1;
4576 4577
    }

M
Matthias Bolte 已提交
4578
    return 0;
4579 4580 4581 4582
}



E
Eric Blake 已提交
4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606
static virDomainSnapshotPtr
esxDomainSnapshotGetParent(virDomainSnapshotPtr snapshot, unsigned int flags)
{
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    virDomainSnapshotPtr parent = NULL;

    virCheckFlags(0, NULL);

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

    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    if (!snapshotTreeParent) {
4607 4608 4609
        virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                       _("snapshot '%s' does not have a parent"),
                       snapshotTree->name);
E
Eric Blake 已提交
4610 4611 4612 4613 4614
        goto cleanup;
    }

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

4615
 cleanup:
E
Eric Blake 已提交
4616 4617 4618 4619 4620 4621 4622
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return parent;
}



4623 4624 4625 4626 4627
static virDomainSnapshotPtr
esxDomainSnapshotCurrent(virDomainPtr domain, unsigned int flags)
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *currentSnapshotTree = NULL;
M
Matthias Bolte 已提交
4628
    virDomainSnapshotPtr snapshot = NULL;
4629

4630
    virCheckFlags(0, NULL);
4631

4632
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4633
        return NULL;
4634 4635
    }

4636
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4637 4638
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4639
        return NULL;
4640 4641 4642 4643 4644 4645 4646 4647 4648 4649
    }

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

    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return snapshot;
}


4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681
static int
esxDomainSnapshotIsCurrent(virDomainSnapshotPtr snapshot, unsigned int flags)
{
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *currentSnapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

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

    /* Check that snapshot exists.  */
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, NULL,
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    if (esxVI_LookupCurrentSnapshotTree(priv->primary, snapshot->domain->uuid,
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    ret = STREQ(snapshot->name, currentSnapshotTree->name);

4682
 cleanup:
4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713
    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    return ret;
}


static int
esxDomainSnapshotHasMetadata(virDomainSnapshotPtr snapshot, unsigned int flags)
{
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

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

    /* Check that snapshot exists.  If so, there is no metadata.  */
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, NULL,
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    ret = 0;

4714
 cleanup:
4715 4716 4717 4718
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    return ret;
}

4719 4720 4721 4722

static int
esxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4723
    int result = -1;
4724 4725 4726 4727 4728
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
4729
    char *taskInfoErrorMessage = NULL;
4730

4731
    virCheckFlags(0, -1);
4732

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

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

4745
    if (esxVI_RevertToSnapshot_Task(priv->primary, snapshotTree->snapshot, NULL,
4746
                                    esxVI_Boolean_Undefined, &task) < 0 ||
4747
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4748
                                    esxVI_Occurrence_RequiredItem,
4749
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4750
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4751
        goto cleanup;
4752 4753 4754
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4755 4756 4757
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not revert to snapshot '%s': %s"), snapshot->name,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4758
        goto cleanup;
4759 4760
    }

M
Matthias Bolte 已提交
4761 4762
    result = 0;

4763
 cleanup:
4764 4765
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4766
    VIR_FREE(taskInfoErrorMessage);
4767 4768 4769 4770 4771 4772 4773 4774 4775

    return result;
}



static int
esxDomainSnapshotDelete(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4776
    int result = -1;
4777 4778 4779 4780 4781 4782
    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;
4783
    char *taskInfoErrorMessage = NULL;
4784

4785 4786
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
                  VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY, -1);
4787

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

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

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

4804 4805 4806 4807 4808 4809 4810
    /* 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;
    }

4811
    if (esxVI_RemoveSnapshot_Task(priv->primary, snapshotTree->snapshot,
4812
                                  removeChildren, &task) < 0 ||
4813
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4814
                                    esxVI_Occurrence_RequiredItem,
4815
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4816
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4817
        goto cleanup;
4818 4819 4820
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4821 4822 4823
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not delete snapshot '%s': %s"), snapshot->name,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4824
        goto cleanup;
4825 4826
    }

M
Matthias Bolte 已提交
4827 4828
    result = 0;

4829
 cleanup:
4830 4831
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4832
    VIR_FREE(taskInfoErrorMessage);
4833 4834 4835 4836 4837 4838

    return result;
}



4839
static int
4840
esxDomainSetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
4841 4842 4843 4844 4845 4846 4847 4848
                             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;
4849
    char *taskInfoErrorMessage = NULL;
4850
    size_t i;
4851 4852

    virCheckFlags(0, -1);
4853 4854 4855 4856
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_MEMORY_MIN_GUARANTEE,
                               VIR_TYPED_PARAM_ULLONG,
                               NULL) < 0)
4857
        return -1;
4858 4859 4860 4861 4862 4863 4864

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

    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4865
           priv->parsedUri->autoAnswer) < 0 ||
4866 4867 4868 4869 4870 4871
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0) {
        goto cleanup;
    }

    for (i = 0; i < nparams; ++i) {
4872
        if (STREQ(params[i].field, VIR_DOMAIN_MEMORY_MIN_GUARANTEE)) {
4873 4874 4875 4876 4877
            if (esxVI_Long_Alloc(&spec->memoryAllocation->reservation) < 0) {
                goto cleanup;
            }

            spec->memoryAllocation->reservation->value =
4878
              VIR_DIV_UP(params[i].value.ul, 1024); /* Scale from kilobytes to megabytes */
4879 4880 4881 4882 4883 4884 4885
        }
    }

    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
4886
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4887
                                    &taskInfoErrorMessage) < 0) {
4888 4889 4890 4891
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4892 4893 4894
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not change memory parameters: %s"),
                       taskInfoErrorMessage);
4895 4896 4897 4898 4899
        goto cleanup;
    }

    result = 0;

4900
 cleanup:
4901 4902 4903
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
4904
    VIR_FREE(taskInfoErrorMessage);
4905 4906 4907 4908 4909 4910 4911

    return result;
}



static int
4912
esxDomainGetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941
                             int *nparams, unsigned int flags)
{
    int result = -1;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_Long *reservation = NULL;

    virCheckFlags(0, -1);

    if (*nparams == 0) {
        *nparams = 1; /* min_guarantee */
        return 0;
    }

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

    if (esxVI_String_AppendValueToList
          (&propertyNameList, "config.memoryAllocation.reservation") < 0 ||
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
                                         propertyNameList, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_GetLong(virtualMachine, "config.memoryAllocation.reservation",
                      &reservation, esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

4942 4943 4944 4945
    /* Scale from megabytes to kilobytes */
    if (virTypedParameterAssign(params, VIR_DOMAIN_MEMORY_MIN_GUARANTEE,
                                VIR_TYPED_PARAM_ULLONG,
                                reservation->value * 1024) < 0)
4946 4947 4948 4949 4950
        goto cleanup;

    *nparams = 1;
    result = 0;

4951
 cleanup:
4952 4953 4954 4955 4956 4957 4958
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Long_Free(&reservation);

    return result;
}

4959 4960
#define MATCH(FLAG) (flags & (FLAG))
static int
4961 4962 4963
esxConnectListAllDomains(virConnectPtr conn,
                         virDomainPtr **domains,
                         unsigned int flags)
4964 4965 4966
{
    int ret = -1;
    esxPrivate *priv = conn->privateData;
4967 4968
    bool needIdentity;
    bool needPowerState;
4969 4970 4971
    virDomainPtr dom;
    virDomainPtr *doms = NULL;
    size_t ndoms = 0;
4972
    esxVI_String *propertyNameList = NULL;
4973 4974
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
4975
    esxVI_AutoStartDefaults *autoStartDefaults = NULL;
4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992
    esxVI_VirtualMachinePowerState powerState;
    esxVI_AutoStartPowerInfo *powerInfoList = NULL;
    esxVI_AutoStartPowerInfo *powerInfo = NULL;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    char *name = NULL;
    int id;
    unsigned char uuid[VIR_UUID_BUFLEN];
    int count = 0;
    bool autostart;
    int state;

    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);

    /* check for flags that would produce empty output lists:
     * - persistence: all esx machines are persistent
     * - managed save: esx doesn't support managed save
     */
4993
    if ((MATCH(VIR_CONNECT_LIST_DOMAINS_TRANSIENT) &&
4994 4995 4996 4997 4998
         !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)
4999
            goto cleanup;
5000 5001 5002 5003 5004

        ret = 0;
        goto cleanup;
    }

5005
    if (esxVI_EnsureSession(priv->primary) < 0)
5006 5007 5008 5009 5010
        return -1;

    /* check system default autostart value */
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_AUTOSTART)) {
        if (esxVI_LookupAutoStartDefaults(priv->primary,
5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023
                                          &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) ||
5024
                   domains;
5025 5026 5027 5028 5029 5030 5031

    if (needIdentity) {
        /* Request required data for esxVI_GetVirtualMachineIdentity */
        if (esxVI_String_AppendValueListToList(&propertyNameList,
                                               "configStatus\0"
                                               "name\0"
                                               "config.uuid\0") < 0) {
5032
            goto cleanup;
5033 5034 5035 5036 5037
        }
    }

    needPowerState = MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_ACTIVE) ||
                     MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_STATE) ||
5038
                     domains;
5039

5040 5041 5042
    if (needPowerState) {
        if (esxVI_String_AppendValueToList(&propertyNameList,
                                           "runtime.powerState") < 0) {
5043
            goto cleanup;
5044
        }
5045 5046
    }

5047
    if (esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
5048 5049 5050 5051 5052
                                       &virtualMachineList) < 0)
        goto cleanup;

    if (domains) {
        if (VIR_ALLOC_N(doms, 1) < 0)
5053
            goto cleanup;
5054 5055 5056
        ndoms = 1;
    }

5057
    for (virtualMachine = virtualMachineList; virtualMachine;
5058
         virtualMachine = virtualMachine->_next) {
5059 5060
        if (needIdentity) {
            VIR_FREE(name);
5061

5062 5063 5064 5065 5066
            if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id,
                                                &name, uuid) < 0) {
                goto cleanup;
            }
        }
5067

5068 5069 5070 5071 5072 5073
        if (needPowerState) {
            if (esxVI_GetVirtualMachinePowerState(virtualMachine,
                                                  &powerState) < 0) {
                goto cleanup;
            }
        }
5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084

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

5087 5088 5089 5090 5091 5092
            if (esxVI_LookupRootSnapshotTreeList(priv->primary, uuid,
                                                 &rootSnapshotTreeList) < 0) {
                goto cleanup;
            }

            if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT) &&
5093
                   rootSnapshotTreeList) ||
5094
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT) &&
5095
                   !rootSnapshotTreeList)))
5096 5097 5098 5099 5100 5101 5102
                continue;
        }

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

5103
            if (autoStartDefaults->enabled == esxVI_Boolean_True) {
5104
                for (powerInfo = powerInfoList; powerInfo;
5105 5106 5107 5108
                     powerInfo = powerInfo->_next) {
                    if (STREQ(powerInfo->key->value, virtualMachine->obj->value)) {
                        if (STRCASEEQ(powerInfo->startAction, "powerOn"))
                            autostart = true;
5109

5110 5111
                        break;
                    }
5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124
                }
            }

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

5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144
            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;
        }

5145
        if (VIR_RESIZE_N(doms, ndoms, count, 2) < 0)
5146
            goto cleanup;
5147

5148 5149 5150
        if (!(dom = virGetDomain(conn, name, uuid)))
            goto cleanup;

5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164
        /* Only running/suspended virtual machines have an ID != -1 */
        if (powerState != esxVI_VirtualMachinePowerState_PoweredOff)
            dom->id = id;
        else
            dom->id = -1;

        doms[count++] = dom;
    }

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

5165
 cleanup:
5166 5167
    if (doms) {
        for (id = 0; id < count; id++) {
5168
            virDomainFree(doms[id]);
5169
        }
5170 5171

        VIR_FREE(doms);
5172
    }
5173

5174
    VIR_FREE(name);
5175 5176
    esxVI_AutoStartDefaults_Free(&autoStartDefaults);
    esxVI_AutoStartPowerInfo_Free(&powerInfoList);
5177 5178
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
5179 5180
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

5181 5182 5183
    return ret;
}
#undef MATCH
5184 5185


5186
static virDriver esxDriver = {
5187 5188
    .no = VIR_DRV_ESX,
    .name = "ESX",
5189 5190 5191 5192 5193 5194
    .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 */
5195
    .nodeGetInfo = esxNodeGetInfo, /* 0.7.0 */
5196 5197 5198 5199
    .connectGetCapabilities = esxConnectGetCapabilities, /* 0.7.1 */
    .connectListDomains = esxConnectListDomains, /* 0.7.0 */
    .connectNumOfDomains = esxConnectNumOfDomains, /* 0.7.0 */
    .connectListAllDomains = esxConnectListAllDomains, /* 0.10.2 */
5200 5201 5202 5203 5204 5205
    .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 */
5206
    .domainShutdownFlags = esxDomainShutdownFlags, /* 0.9.10 */
5207 5208
    .domainReboot = esxDomainReboot, /* 0.7.0 */
    .domainDestroy = esxDomainDestroy, /* 0.7.0 */
5209
    .domainDestroyFlags = esxDomainDestroyFlags, /* 0.9.4 */
5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222
    .domainGetOSType = esxDomainGetOSType, /* 0.7.0 */
    .domainGetMaxMemory = esxDomainGetMaxMemory, /* 0.7.0 */
    .domainSetMaxMemory = esxDomainSetMaxMemory, /* 0.7.0 */
    .domainSetMemory = esxDomainSetMemory, /* 0.7.0 */
    .domainSetMemoryParameters = esxDomainSetMemoryParameters, /* 0.8.6 */
    .domainGetMemoryParameters = esxDomainGetMemoryParameters, /* 0.8.6 */
    .domainGetInfo = esxDomainGetInfo, /* 0.7.0 */
    .domainGetState = esxDomainGetState, /* 0.9.2 */
    .domainSetVcpus = esxDomainSetVcpus, /* 0.7.0 */
    .domainSetVcpusFlags = esxDomainSetVcpusFlags, /* 0.8.5 */
    .domainGetVcpusFlags = esxDomainGetVcpusFlags, /* 0.8.5 */
    .domainGetMaxVcpus = esxDomainGetMaxVcpus, /* 0.7.0 */
    .domainGetXMLDesc = esxDomainGetXMLDesc, /* 0.7.0 */
5223 5224 5225 5226
    .connectDomainXMLFromNative = esxConnectDomainXMLFromNative, /* 0.7.0 */
    .connectDomainXMLToNative = esxConnectDomainXMLToNative, /* 0.7.2 */
    .connectListDefinedDomains = esxConnectListDefinedDomains, /* 0.7.0 */
    .connectNumOfDefinedDomains = esxConnectNumOfDefinedDomains, /* 0.7.0 */
5227 5228 5229 5230
    .domainCreate = esxDomainCreate, /* 0.7.0 */
    .domainCreateWithFlags = esxDomainCreateWithFlags, /* 0.8.2 */
    .domainDefineXML = esxDomainDefineXML, /* 0.7.2 */
    .domainUndefine = esxDomainUndefine, /* 0.7.1 */
5231
    .domainUndefineFlags = esxDomainUndefineFlags, /* 0.9.4 */
5232 5233 5234 5235
    .domainGetAutostart = esxDomainGetAutostart, /* 0.9.0 */
    .domainSetAutostart = esxDomainSetAutostart, /* 0.9.0 */
    .domainGetSchedulerType = esxDomainGetSchedulerType, /* 0.7.0 */
    .domainGetSchedulerParameters = esxDomainGetSchedulerParameters, /* 0.7.0 */
5236
    .domainGetSchedulerParametersFlags = esxDomainGetSchedulerParametersFlags, /* 0.9.2 */
5237
    .domainSetSchedulerParameters = esxDomainSetSchedulerParameters, /* 0.7.0 */
5238
    .domainSetSchedulerParametersFlags = esxDomainSetSchedulerParametersFlags, /* 0.9.2 */
5239 5240 5241 5242
    .domainMigratePrepare = esxDomainMigratePrepare, /* 0.7.0 */
    .domainMigratePerform = esxDomainMigratePerform, /* 0.7.0 */
    .domainMigrateFinish = esxDomainMigrateFinish, /* 0.7.0 */
    .nodeGetFreeMemory = esxNodeGetFreeMemory, /* 0.7.2 */
5243 5244
    .connectIsEncrypted = esxConnectIsEncrypted, /* 0.7.3 */
    .connectIsSecure = esxConnectIsSecure, /* 0.7.3 */
5245 5246 5247 5248 5249 5250 5251
    .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 */
5252 5253
    .domainSnapshotNumChildren = esxDomainSnapshotNumChildren, /* 0.9.7 */
    .domainSnapshotListChildrenNames = esxDomainSnapshotListChildrenNames, /* 0.9.7 */
5254 5255
    .domainSnapshotLookupByName = esxDomainSnapshotLookupByName, /* 0.8.0 */
    .domainHasCurrentSnapshot = esxDomainHasCurrentSnapshot, /* 0.8.0 */
E
Eric Blake 已提交
5256
    .domainSnapshotGetParent = esxDomainSnapshotGetParent, /* 0.9.7 */
5257 5258
    .domainSnapshotCurrent = esxDomainSnapshotCurrent, /* 0.8.0 */
    .domainRevertToSnapshot = esxDomainRevertToSnapshot, /* 0.8.0 */
5259 5260
    .domainSnapshotIsCurrent = esxDomainSnapshotIsCurrent, /* 0.9.13 */
    .domainSnapshotHasMetadata = esxDomainSnapshotHasMetadata, /* 0.9.13 */
5261
    .domainSnapshotDelete = esxDomainSnapshotDelete, /* 0.8.0 */
5262
    .connectIsAlive = esxConnectIsAlive, /* 0.9.8 */
5263 5264 5265 5266 5267 5268 5269
};



int
esxRegister(void)
{
5270 5271 5272 5273 5274
    if (virRegisterDriver(&esxDriver) < 0 ||
        esxInterfaceRegister() < 0 ||
        esxNetworkRegister() < 0 ||
        esxStorageRegister() < 0 ||
        esxDeviceRegister() < 0 ||
M
Matthias Bolte 已提交
5275 5276
        esxSecretRegister() < 0 ||
        esxNWFilterRegister() < 0) {
5277 5278
        return -1;
    }
5279 5280 5281

    return 0;
}