esx_driver.c 168.6 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 ||
392 393
        virDomainDiskGetType(def) != VIR_DOMAIN_DISK_TYPE_FILE ||
        !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 it 0.
893 894 895 896
 *
 * 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
 * questions will be reported as errors. The default value it 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;
M
Matthias Bolte 已提交
1423
    char *xml = virCapabilitiesFormatXML(priv->caps);
1424

1425
    if (!xml) {
1426
        virReportOOMError();
1427 1428 1429 1430 1431 1432 1433 1434
        return NULL;
    }

    return xml;
}



1435
static int
1436
esxConnectListDomains(virConnectPtr conn, int *ids, int maxids)
1437
{
M
Matthias Bolte 已提交
1438
    bool success = false;
M
Matthias Bolte 已提交
1439
    esxPrivate *priv = conn->privateData;
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;

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

1450
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1451
        return -1;
1452 1453
    }

1454
    if (esxVI_String_AppendValueToList(&propertyNameList,
1455
                                       "runtime.powerState") < 0 ||
1456 1457
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1458
        goto cleanup;
1459 1460
    }

1461
    for (virtualMachine = virtualMachineList; virtualMachine;
1462
         virtualMachine = virtualMachine->_next) {
1463
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1464
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1465
            goto cleanup;
1466 1467 1468 1469 1470 1471 1472 1473 1474
        }

        if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

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

        count++;

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

M
Matthias Bolte 已提交
1488 1489
    success = true;

1490
 cleanup:
1491 1492 1493
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
1494
    return success ? count : -1;
1495 1496 1497 1498 1499
}



static int
1500
esxConnectNumOfDomains(virConnectPtr conn)
1501
{
M
Matthias Bolte 已提交
1502
    esxPrivate *priv = conn->privateData;
1503

1504
    if (esxVI_EnsureSession(priv->primary) < 0) {
1505 1506 1507
        return -1;
    }

1508
    return esxVI_LookupNumberOfDomainsByPowerState
1509
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, false);
1510 1511 1512 1513 1514 1515 1516
}



static virDomainPtr
esxDomainLookupByID(virConnectPtr conn, int id)
{
M
Matthias Bolte 已提交
1517
    esxPrivate *priv = conn->privateData;
1518 1519 1520 1521
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
M
Matthias Bolte 已提交
1522 1523 1524
    int id_candidate = -1;
    char *name_candidate = NULL;
    unsigned char uuid_candidate[VIR_UUID_BUFLEN];
1525 1526
    virDomainPtr domain = NULL;

1527
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1528
        return NULL;
1529 1530
    }

1531
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1532
                                           "configStatus\0"
1533 1534
                                           "name\0"
                                           "runtime.powerState\0"
1535
                                           "config.uuid\0") < 0 ||
1536 1537
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1538
        goto cleanup;
1539 1540
    }

1541
    for (virtualMachine = virtualMachineList; virtualMachine;
1542
         virtualMachine = virtualMachine->_next) {
1543
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1544
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1545
            goto cleanup;
1546 1547 1548 1549 1550 1551 1552
        }

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

M
Matthias Bolte 已提交
1553
        VIR_FREE(name_candidate);
1554

1555
        if (esxVI_GetVirtualMachineIdentity(virtualMachine,
M
Matthias Bolte 已提交
1556 1557
                                            &id_candidate, &name_candidate,
                                            uuid_candidate) < 0) {
M
Matthias Bolte 已提交
1558
            goto cleanup;
1559 1560
        }

M
Matthias Bolte 已提交
1561
        if (id != id_candidate) {
1562 1563 1564
            continue;
        }

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

1567
        if (!domain) {
M
Matthias Bolte 已提交
1568
            goto cleanup;
1569 1570 1571 1572 1573 1574 1575
        }

        domain->id = id;

        break;
    }

1576
    if (!domain) {
1577
        virReportError(VIR_ERR_NO_DOMAIN, _("No domain with ID %d"), id);
1578 1579
    }

1580
 cleanup:
1581 1582
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
M
Matthias Bolte 已提交
1583
    VIR_FREE(name_candidate);
1584 1585 1586 1587 1588 1589 1590 1591 1592

    return domain;
}



static virDomainPtr
esxDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
M
Matthias Bolte 已提交
1593
    esxPrivate *priv = conn->privateData;
1594 1595 1596
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1597 1598
    int id = -1;
    char *name = NULL;
1599 1600
    virDomainPtr domain = NULL;

1601
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1602
        return NULL;
1603 1604
    }

1605
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1606
                                           "name\0"
1607
                                           "runtime.powerState\0") < 0 ||
1608
        esxVI_LookupVirtualMachineByUuid(priv->primary, uuid, propertyNameList,
1609
                                         &virtualMachine,
M
Matthias Bolte 已提交
1610
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1611 1612
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, &name, NULL) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1613
        goto cleanup;
1614 1615
    }

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

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

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

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

    return domain;
}



static virDomainPtr
esxDomainLookupByName(virConnectPtr conn, const char *name)
{
M
Matthias Bolte 已提交
1642
    esxPrivate *priv = conn->privateData;
1643 1644 1645
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1646 1647
    int id = -1;
    unsigned char uuid[VIR_UUID_BUFLEN];
1648 1649
    virDomainPtr domain = NULL;

1650
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1651
        return NULL;
1652 1653
    }

1654
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1655
                                           "configStatus\0"
1656
                                           "runtime.powerState\0"
1657
                                           "config.uuid\0") < 0 ||
1658
        esxVI_LookupVirtualMachineByName(priv->primary, name, propertyNameList,
1659 1660
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
1661
        goto cleanup;
1662 1663
    }

1664
    if (!virtualMachine) {
1665
        virReportError(VIR_ERR_NO_DOMAIN, _("No domain with name '%s'"), name);
M
Matthias Bolte 已提交
1666
        goto cleanup;
1667
    }
1668

M
Matthias Bolte 已提交
1669 1670 1671
    if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, uuid) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
1672
    }
1673

1674
    domain = virGetDomain(conn, name, uuid);
1675

1676
    if (!domain) {
M
Matthias Bolte 已提交
1677
        goto cleanup;
1678 1679
    }

1680 1681 1682 1683 1684
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1685 1686
    }

1687
 cleanup:
1688
    esxVI_String_Free(&propertyNameList);
1689
    esxVI_ObjectContent_Free(&virtualMachine);
1690 1691 1692 1693 1694 1695 1696 1697 1698

    return domain;
}



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

1708
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1709
        return -1;
1710 1711
    }

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

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1722 1723
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1724
        goto cleanup;
1725 1726
    }

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

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

M
Matthias Bolte 已提交
1741 1742
    result = 0;

1743
 cleanup:
1744 1745 1746
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1747
    VIR_FREE(taskInfoErrorMessage);
1748 1749 1750 1751 1752 1753 1754 1755 1756

    return result;
}



static int
esxDomainResume(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1757
    int result = -1;
M
Matthias Bolte 已提交
1758
    esxPrivate *priv = domain->conn->privateData;
1759 1760 1761 1762 1763
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1764
    char *taskInfoErrorMessage = NULL;
1765

1766
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1767
        return -1;
1768 1769
    }

1770
    if (esxVI_String_AppendValueToList(&propertyNameList,
1771
                                       "runtime.powerState") < 0 ||
1772
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1773
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1774
           priv->parsedUri->autoAnswer) < 0 ||
1775
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1776
        goto cleanup;
1777 1778 1779
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended) {
1780
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not suspended"));
M
Matthias Bolte 已提交
1781
        goto cleanup;
1782 1783
    }

1784
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
1785
                             &task) < 0 ||
1786
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1787
                                    esxVI_Occurrence_RequiredItem,
1788
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1789
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1790
        goto cleanup;
1791 1792 1793
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1794 1795
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not resume domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
1796
        goto cleanup;
1797 1798
    }

M
Matthias Bolte 已提交
1799 1800
    result = 0;

1801
 cleanup:
1802 1803 1804
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1805
    VIR_FREE(taskInfoErrorMessage);
1806 1807 1808 1809 1810 1811 1812

    return result;
}



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

1821 1822
    virCheckFlags(0, -1);

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

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

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

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

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

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

    return result;
}


1856 1857 1858 1859 1860 1861
static int
esxDomainShutdown(virDomainPtr domain)
{
    return esxDomainShutdownFlags(domain, 0);
}

1862 1863

static int
E
Eric Blake 已提交
1864
esxDomainReboot(virDomainPtr domain, unsigned int flags)
1865
{
M
Matthias Bolte 已提交
1866
    int result = -1;
M
Matthias Bolte 已提交
1867
    esxPrivate *priv = domain->conn->privateData;
1868 1869 1870 1871
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

E
Eric Blake 已提交
1872 1873
    virCheckFlags(0, -1);

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

1878
    if (esxVI_String_AppendValueToList(&propertyNameList,
1879
                                       "runtime.powerState") < 0 ||
1880
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1881
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1882
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1883
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1884
        goto cleanup;
1885 1886 1887
    }

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

1893
    if (esxVI_RebootGuest(priv->primary, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1894
        goto cleanup;
1895 1896
    }

M
Matthias Bolte 已提交
1897 1898
    result = 0;

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

    return result;
}



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

1922 1923
    virCheckFlags(0, -1);

1924
    if (priv->vCenter) {
1925 1926 1927 1928 1929
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

1930
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
1931
        return -1;
1932 1933
    }

1934
    if (esxVI_String_AppendValueToList(&propertyNameList,
1935
                                       "runtime.powerState") < 0 ||
1936
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1937
          (ctx, domain->uuid, propertyNameList, &virtualMachine,
1938
           priv->parsedUri->autoAnswer) < 0 ||
1939
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1940
        goto cleanup;
1941 1942 1943
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1944 1945
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1946
        goto cleanup;
1947 1948
    }

1949
    if (esxVI_PowerOffVM_Task(ctx, virtualMachine->obj, &task) < 0 ||
1950 1951
        esxVI_WaitForTaskCompletion(ctx, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
1952
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1953
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1954
        goto cleanup;
1955 1956 1957
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1958 1959
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not destroy domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
1960
        goto cleanup;
1961 1962
    }

1963
    domain->id = -1;
M
Matthias Bolte 已提交
1964 1965
    result = 0;

1966
 cleanup:
1967 1968 1969
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1970
    VIR_FREE(taskInfoErrorMessage);
1971 1972 1973 1974 1975

    return result;
}


1976 1977 1978 1979 1980 1981
static int
esxDomainDestroy(virDomainPtr dom)
{
    return esxDomainDestroyFlags(dom, 0);
}

1982 1983

static char *
1984
esxDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED)
1985
{
1986
    char *osType;
1987

1988
    ignore_value(VIR_STRDUP(osType, "hvm"));
1989
    return osType;
1990 1991 1992 1993
}



1994
static unsigned long long
1995 1996
esxDomainGetMaxMemory(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1997
    esxPrivate *priv = domain->conn->privateData;
1998 1999 2000 2001 2002
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    unsigned long memoryMB = 0;

2003
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2004
        return 0;
2005 2006
    }

2007
    if (esxVI_String_AppendValueToList(&propertyNameList,
2008
                                       "config.hardware.memoryMB") < 0 ||
2009
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2010
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2011
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2012
        goto cleanup;
2013 2014
    }

2015
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
2016 2017
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2018
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2019
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2020
                goto cleanup;
2021 2022 2023
            }

            if (dynamicProperty->val->int32 < 0) {
2024 2025 2026
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Got invalid memory size %d"),
                               dynamicProperty->val->int32);
2027 2028 2029 2030 2031 2032 2033 2034 2035 2036
            } else {
                memoryMB = dynamicProperty->val->int32;
            }

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

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

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

2063 2064 2065 2066
    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "runtime.powerState") < 0 ||
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
2067
           priv->parsedUri->autoAnswer) < 0 ||
2068 2069 2070 2071 2072
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2073 2074
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered off"));
2075 2076 2077 2078
        goto cleanup;
    }

    if (esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
2079
        esxVI_Long_Alloc(&spec->memoryMB) < 0) {
M
Matthias Bolte 已提交
2080
        goto cleanup;
2081 2082
    }

2083
    /* max-memory must be a multiple of 4096 kilobyte */
2084
    spec->memoryMB->value =
2085
      VIR_DIV_UP(memory, 4096) * 4; /* Scale from kilobytes to megabytes */
2086

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

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

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

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

    return result;
}



static int
esxDomainSetMemory(virDomainPtr domain, unsigned long memory)
{
M
Matthias Bolte 已提交
2120
    int result = -1;
M
Matthias Bolte 已提交
2121
    esxPrivate *priv = domain->conn->privateData;
2122 2123 2124 2125
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2126
    char *taskInfoErrorMessage = NULL;
2127

2128
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2129
        return -1;
2130 2131
    }

2132
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2133
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2134
           priv->parsedUri->autoAnswer) < 0 ||
2135 2136 2137
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0 ||
        esxVI_Long_Alloc(&spec->memoryAllocation->limit) < 0) {
M
Matthias Bolte 已提交
2138
        goto cleanup;
2139 2140 2141
    }

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

2144
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2145
                              &task) < 0 ||
2146
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2147
                                    esxVI_Occurrence_RequiredItem,
2148
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2149
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2150
        goto cleanup;
2151 2152 2153
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2154 2155 2156
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set memory to %lu kilobytes: %s"), memory,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2157
        goto cleanup;
2158 2159
    }

M
Matthias Bolte 已提交
2160 2161
    result = 0;

2162
 cleanup:
2163 2164 2165
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2166
    VIR_FREE(taskInfoErrorMessage);
2167 2168 2169 2170 2171 2172

    return result;
}



2173 2174 2175 2176 2177 2178 2179 2180 2181
/*
 * 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

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

2207
    memset(info, 0, sizeof(*info));
M
Matthias Bolte 已提交
2208

2209
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2210
        return -1;
2211 2212
    }

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

    info->state = VIR_DOMAIN_NOSTATE;

2226
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
2227 2228 2229
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.powerState")) {
            if (esxVI_VirtualMachinePowerState_CastFromAnyType
2230
                  (dynamicProperty->val, &powerState) < 0) {
M
Matthias Bolte 已提交
2231
                goto cleanup;
2232 2233
            }

2234 2235
            info->state = esxVI_VirtualMachinePowerState_ConvertToLibvirt
                            (powerState);
2236
        } else if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2237
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2238
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2239
                goto cleanup;
2240 2241 2242 2243
            }

            info->maxMem = dynamicProperty->val->int32 * 1024; /* Scale from megabyte to kilobyte */
        } else if (STREQ(dynamicProperty->name, "config.hardware.numCPU")) {
2244
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2245
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2246
                goto cleanup;
2247 2248 2249 2250 2251
            }

            info->nrVirtCpu = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "config.memoryAllocation.limit")) {
2252
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2253
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
2254
                goto cleanup;
2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269
            }

            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;

2270
#if ESX_QUERY_FOR_USED_CPU_TIME
2271
    /* Verify the cached 'used CPU time' performance counter ID */
2272
    /* FIXME: Currently no host for a vpx:// connection */
2273
    if (priv->host) {
2274 2275 2276 2277
        if (info->state == VIR_DOMAIN_RUNNING && priv->usedCpuTimeCounterId >= 0) {
            if (esxVI_Int_Alloc(&counterId) < 0) {
                goto cleanup;
            }
2278

2279
            counterId->value = priv->usedCpuTimeCounterId;
2280

2281 2282 2283
            if (esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                goto cleanup;
            }
2284

2285 2286 2287 2288
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfo) < 0) {
                goto cleanup;
            }
2289

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

2296 2297 2298 2299 2300
                priv->usedCpuTimeCounterId = -1;
            }

            esxVI_Int_Free(&counterIdList);
            esxVI_PerfCounterInfo_Free(&perfCounterInfo);
2301 2302
        }

2303 2304 2305 2306 2307 2308 2309 2310 2311 2312
        /*
         * 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;
            }
2313

2314
            for (perfMetricId = perfMetricIdList; perfMetricId;
2315 2316 2317
                 perfMetricId = perfMetricId->_next) {
                VIR_DEBUG("perfMetricId counterId %d, instance '%s'",
                          perfMetricId->counterId->value, perfMetricId->instance);
2318

2319
                counterId = NULL;
2320

2321 2322 2323 2324 2325
                if (esxVI_Int_DeepCopy(&counterId, perfMetricId->counterId) < 0 ||
                    esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                    goto cleanup;
                }
            }
2326

2327 2328
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfoList) < 0) {
M
Matthias Bolte 已提交
2329
                goto cleanup;
2330 2331
            }

2332
            for (perfCounterInfo = perfCounterInfoList; perfCounterInfo;
2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348
                 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;
                }
2349 2350
            }

2351
            if (priv->usedCpuTimeCounterId < 0) {
2352
                VIR_WARN("Could not find 'used CPU time' performance counter");
2353
            }
2354 2355
        }

2356 2357 2358 2359 2360 2361
        /*
         * 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);
2362

2363 2364 2365 2366 2367 2368
            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;
            }
2369

2370 2371 2372 2373 2374 2375 2376 2377 2378 2379
            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;
            }
2380

2381
            for (perfEntityMetricBase = perfEntityMetricBaseList;
2382
                 perfEntityMetricBase;
2383
                 perfEntityMetricBase = perfEntityMetricBase->_next) {
2384
                VIR_DEBUG("perfEntityMetric ...");
2385

2386 2387
                perfEntityMetric =
                  esxVI_PerfEntityMetric_DynamicCast(perfEntityMetricBase);
2388

2389
                if (!perfEntityMetric) {
2390 2391 2392
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("QueryPerf returned object with unexpected type '%s'"),
                                   esxVI_Type_ToString(perfEntityMetricBase->_type));
2393
                    goto cleanup;
2394
                }
2395

2396 2397
                perfMetricIntSeries =
                  esxVI_PerfMetricIntSeries_DynamicCast(perfEntityMetric->value);
2398

2399
                if (!perfMetricIntSeries) {
2400 2401 2402
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("QueryPerf returned object with unexpected type '%s'"),
                                   esxVI_Type_ToString(perfEntityMetric->value->_type));
2403
                    goto cleanup;
2404
                }
2405

2406
                for (; perfMetricIntSeries;
2407
                     perfMetricIntSeries = perfMetricIntSeries->_next) {
2408
                    VIR_DEBUG("perfMetricIntSeries ...");
2409

2410
                    for (value = perfMetricIntSeries->value;
2411
                         value;
2412 2413 2414
                         value = value->_next) {
                        VIR_DEBUG("value %lld", (long long int)value->value);
                    }
2415 2416 2417
                }
            }

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

2420
            /*
E
Eric Blake 已提交
2421
             * FIXME: Cannot map between relative used-cpu-time and absolute
2422 2423 2424
             *        info->cpuTime
             */
        }
2425
    }
2426
#endif
2427

M
Matthias Bolte 已提交
2428 2429
    result = 0;

2430
 cleanup:
2431
#if ESX_QUERY_FOR_USED_CPU_TIME
2432 2433 2434 2435
    /*
     * Remove values owned by data structures to prevent them from being freed
     * by the call to esxVI_PerfQuerySpec_Free().
     */
2436
    if (querySpec) {
2437 2438 2439
        querySpec->entity = NULL;
        querySpec->format = NULL;

2440
        if (querySpec->metricId) {
2441 2442 2443
            querySpec->metricId->instance = NULL;
        }
    }
2444
#endif
2445

2446 2447
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2448
#if ESX_QUERY_FOR_USED_CPU_TIME
2449 2450 2451 2452
    esxVI_PerfMetricId_Free(&perfMetricIdList);
    esxVI_Int_Free(&counterIdList);
    esxVI_PerfCounterInfo_Free(&perfCounterInfoList);
    esxVI_PerfQuerySpec_Free(&querySpec);
2453
    esxVI_PerfEntityMetricBase_Free(&perfEntityMetricBaseList);
2454
#endif
2455 2456 2457 2458 2459 2460

    return result;
}



2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494
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;

2495
 cleanup:
2496 2497 2498 2499 2500 2501 2502 2503
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
}



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

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

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

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

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

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

M
Matthias Bolte 已提交
2538
    if (nvcpus > maxVcpus) {
2539 2540 2541 2542
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Requested number of virtual CPUs is greater than max "
                         "allowable number of virtual CPUs for the domain: %d > %d"),
                       nvcpus, maxVcpus);
M
Matthias Bolte 已提交
2543
        return -1;
2544 2545
    }

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

    spec->numCPUs->value = nvcpus;

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

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

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

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

    return result;
}


M
Matthias Bolte 已提交
2584

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

2591

M
Matthias Bolte 已提交
2592

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

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

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

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

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

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

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

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

2638
 cleanup:
2639 2640 2641
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
2642
    return priv->maxVcpus;
2643 2644
}

M
Matthias Bolte 已提交
2645 2646


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

M
Matthias Bolte 已提交
2654 2655


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

E
Eric Blake 已提交
2676 2677
    /* Flags checked by virDomainDefFormat */

2678
    memset(&data, 0, sizeof(data));
2679

2680
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2681
        return NULL;
2682 2683
    }

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

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

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

    if (virBufferError(&buffer)) {
2711
        virReportOOMError();
M
Matthias Bolte 已提交
2712
        goto cleanup;
2713 2714
    }

2715 2716
    url = virBufferContentAndReset(&buffer);

2717
    if (esxVI_CURL_Download(priv->primary->curl, url, &vmx, 0, NULL) < 0) {
M
Matthias Bolte 已提交
2718
        goto cleanup;
2719 2720
    }

2721
    data.ctx = priv->primary;
2722

2723
    if (!directoryName) {
2724
        if (virAsprintf(&data.datastorePathWithoutFileName, "[%s]",
2725
                        datastoreName) < 0)
2726 2727 2728
            goto cleanup;
    } else {
        if (virAsprintf(&data.datastorePathWithoutFileName, "[%s] %s",
2729
                        datastoreName, directoryName) < 0)
2730 2731
            goto cleanup;
    }
2732 2733 2734 2735 2736 2737

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

2738
    def = virVMXParseConfig(&ctx, priv->xmlopt, vmx);
2739

2740
    if (def) {
2741 2742 2743 2744
        if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
            def->id = id;
        }

2745
        xml = virDomainDefFormat(def, flags);
2746 2747
    }

2748
 cleanup:
2749
    if (!url) {
M
Matthias Bolte 已提交
2750 2751 2752
        virBufferFreeAndReset(&buffer);
    }

2753 2754
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2755
    VIR_FREE(datastoreName);
M
Matthias Bolte 已提交
2756
    VIR_FREE(directoryName);
2757
    VIR_FREE(directoryAndFileName);
2758
    VIR_FREE(url);
2759
    VIR_FREE(data.datastorePathWithoutFileName);
2760
    VIR_FREE(vmx);
2761
    virDomainDefFree(def);
2762 2763 2764 2765 2766 2767 2768

    return xml;
}



static char *
2769 2770 2771
esxConnectDomainXMLFromNative(virConnectPtr conn, const char *nativeFormat,
                              const char *nativeConfig,
                              unsigned int flags)
2772
{
M
Matthias Bolte 已提交
2773
    esxPrivate *priv = conn->privateData;
2774
    virVMXContext ctx;
2775
    esxVMX_Data data;
2776 2777 2778
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2779 2780
    virCheckFlags(0, NULL);

2781
    memset(&data, 0, sizeof(data));
2782

2783
    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2784 2785
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Unsupported config format '%s'"), nativeFormat);
2786
        return NULL;
2787 2788
    }

2789
    data.ctx = priv->primary;
2790
    data.datastorePathWithoutFileName = (char *)"[?] ?";
2791 2792 2793 2794 2795 2796

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

2797
    def = virVMXParseConfig(&ctx, priv->xmlopt, nativeConfig);
2798

2799
    if (def) {
2800
        xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
2801 2802 2803 2804 2805 2806 2807 2808 2809
    }

    virDomainDefFree(def);

    return xml;
}



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

E
Eric Blake 已提交
2822 2823
    virCheckFlags(0, NULL);

2824
    memset(&data, 0, sizeof(data));
2825

M
Matthias Bolte 已提交
2826
    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2827 2828
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Unsupported config format '%s'"), nativeFormat);
M
Matthias Bolte 已提交
2829 2830 2831
        return NULL;
    }

2832 2833 2834 2835 2836 2837 2838
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        return NULL;
    }

2839
    def = virDomainDefParseString(domainXml, priv->caps, priv->xmlopt,
2840 2841
                                  1 << VIR_DOMAIN_VIRT_VMWARE,
                                  VIR_DOMAIN_XML_INACTIVE);
M
Matthias Bolte 已提交
2842

2843
    if (!def) {
M
Matthias Bolte 已提交
2844 2845 2846
        return NULL;
    }

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

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

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

    virDomainDefFree(def);

    return vmx;
}



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

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

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

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

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

        if (powerState == esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

2903
        names[count] = NULL;
2904

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

2910 2911
        ++count;

2912 2913 2914 2915 2916
        if (count >= maxnames) {
            break;
        }
    }

M
Matthias Bolte 已提交
2917
    success = true;
2918

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

M
Matthias Bolte 已提交
2925
        count = -1;
2926 2927
    }

M
Matthias Bolte 已提交
2928 2929
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
2930

M
Matthias Bolte 已提交
2931
    return count;
2932 2933 2934 2935 2936
}



static int
2937
esxConnectNumOfDefinedDomains(virConnectPtr conn)
2938
{
M
Matthias Bolte 已提交
2939
    esxPrivate *priv = conn->privateData;
2940

2941
    if (esxVI_EnsureSession(priv->primary) < 0) {
2942 2943 2944
        return -1;
    }

2945
    return esxVI_LookupNumberOfDomainsByPowerState
2946
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, true);
2947 2948 2949 2950 2951
}



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

2964 2965
    virCheckFlags(0, -1);

2966
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2967
        return -1;
2968 2969
    }

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

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2981 2982
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered off"));
M
Matthias Bolte 已提交
2983
        goto cleanup;
2984 2985
    }

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

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2996 2997
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not start domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2998
        goto cleanup;
2999 3000
    }

3001
    domain->id = id;
M
Matthias Bolte 已提交
3002 3003
    result = 0;

3004
 cleanup:
3005 3006 3007
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
3008
    VIR_FREE(taskInfoErrorMessage);
3009 3010 3011 3012

    return result;
}

3013 3014


3015 3016 3017 3018 3019
static int
esxDomainCreate(virDomainPtr domain)
{
    return esxDomainCreateWithFlags(domain, 0);
}
3020

3021 3022


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

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

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

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

3061
    if (!def) {
M
Matthias Bolte 已提交
3062
        return NULL;
M
Matthias Bolte 已提交
3063 3064 3065
    }

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

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

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

    /* Build VMX from domain XML */
3088 3089 3090 3091 3092 3093 3094
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        goto cleanup;
    }

3095
    data.ctx = priv->primary;
3096
    data.datastorePathWithoutFileName = NULL;
3097 3098 3099 3100 3101 3102

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

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

3105
    if (!vmx) {
M
Matthias Bolte 已提交
3106
        goto cleanup;
M
Matthias Bolte 已提交
3107 3108
    }

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

    for (i = 0; i < def->ndisks; ++i) {
        if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK &&
3125
            virDomainDiskGetType(def->disks[i]) == VIR_DOMAIN_DISK_TYPE_FILE) {
3126 3127 3128 3129 3130
            disk = def->disks[i];
            break;
        }
    }

3131
    if (!disk) {
3132 3133 3134
        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 已提交
3135
        goto cleanup;
M
Matthias Bolte 已提交
3136 3137
    }

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

3146
    if (esxUtil_ParseDatastorePath(src, &datastoreName, &directoryName,
3147
                                   NULL) < 0) {
M
Matthias Bolte 已提交
3148
        goto cleanup;
M
Matthias Bolte 已提交
3149 3150
    }

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

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

3161
    if (directoryName) {
M
Matthias Bolte 已提交
3162 3163 3164 3165
        virBufferURIEncodeString(&buffer, directoryName);
        virBufferAddChar(&buffer, '/');
    }

3166 3167
    escapedName = esxUtil_EscapeDatastoreItem(def->name);

3168
    if (!escapedName) {
3169 3170 3171 3172
        goto cleanup;
    }

    virBufferURIEncodeString(&buffer, escapedName);
M
Matthias Bolte 已提交
3173
    virBufferAddLit(&buffer, ".vmx?dcPath=");
3174
    virBufferURIEncodeString(&buffer, priv->primary->datacenterPath);
M
Matthias Bolte 已提交
3175 3176 3177 3178
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
3179
        virReportOOMError();
M
Matthias Bolte 已提交
3180
        goto cleanup;
M
Matthias Bolte 已提交
3181 3182 3183 3184
    }

    url = virBufferContentAndReset(&buffer);

3185 3186 3187 3188 3189 3190
    /* Check, if VMX file already exists */
    /* FIXME */

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

3191
    if (esxVI_CURL_Upload(priv->primary->curl, url, vmx) < 0) {
3192 3193 3194 3195
        goto cleanup;
    }

    /* Register the domain */
3196
    if (directoryName) {
M
Matthias Bolte 已提交
3197
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s/%s.vmx", datastoreName,
3198
                        directoryName, escapedName) < 0)
M
Matthias Bolte 已提交
3199
            goto cleanup;
M
Matthias Bolte 已提交
3200 3201
    } else {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s.vmx", datastoreName,
3202
                        escapedName) < 0)
M
Matthias Bolte 已提交
3203
            goto cleanup;
M
Matthias Bolte 已提交
3204 3205
    }

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

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3219 3220
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not define domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3221
        goto cleanup;
M
Matthias Bolte 已提交
3222 3223 3224 3225
    }

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

3226
    if (domain) {
M
Matthias Bolte 已提交
3227 3228 3229 3230 3231
        domain->id = -1;
    }

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

3232
 cleanup:
3233
    if (!url) {
M
Matthias Bolte 已提交
3234 3235 3236
        virBufferFreeAndReset(&buffer);
    }

M
Matthias Bolte 已提交
3237 3238 3239 3240
    virDomainDefFree(def);
    VIR_FREE(vmx);
    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
3241
    VIR_FREE(escapedName);
M
Matthias Bolte 已提交
3242 3243 3244 3245 3246 3247 3248
    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);
3249
    VIR_FREE(taskInfoErrorMessage);
M
Matthias Bolte 已提交
3250 3251 3252 3253 3254 3255

    return domain;
}



3256
static int
3257 3258
esxDomainUndefineFlags(virDomainPtr domain,
                       unsigned int flags)
3259
{
M
Matthias Bolte 已提交
3260
    int result = -1;
M
Matthias Bolte 已提交
3261
    esxPrivate *priv = domain->conn->privateData;
3262
    esxVI_Context *ctx = NULL;
3263 3264 3265 3266
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

3267 3268 3269 3270
    /* 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);
3271

3272
    if (priv->vCenter) {
3273 3274 3275 3276 3277
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

3278
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
3279
        return -1;
3280 3281
    }

3282
    if (esxVI_String_AppendValueToList(&propertyNameList,
3283
                                       "runtime.powerState") < 0 ||
3284 3285
        esxVI_LookupVirtualMachineByUuid(ctx, domain->uuid, propertyNameList,
                                         &virtualMachine,
M
Matthias Bolte 已提交
3286
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3287
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
3288
        goto cleanup;
3289 3290 3291 3292
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended &&
        powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
3293 3294
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not suspended or powered off"));
M
Matthias Bolte 已提交
3295
        goto cleanup;
3296 3297
    }

3298
    if (esxVI_UnregisterVM(ctx, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
3299
        goto cleanup;
3300 3301
    }

M
Matthias Bolte 已提交
3302 3303
    result = 0;

3304
 cleanup:
3305 3306 3307 3308 3309 3310 3311
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}


3312 3313 3314 3315 3316
static int
esxDomainUndefine(virDomainPtr domain)
{
    return esxDomainUndefineFlags(domain, 0);
}
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 3345 3346 3347 3348 3349 3350
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;
    }

3351
    if (!powerInfoList) {
3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362
        /* 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;
    }

3363
    for (powerInfo = powerInfoList; powerInfo;
3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375
         powerInfo = powerInfo->_next) {
        if (STREQ(powerInfo->key->value, virtualMachine->obj->value)) {
            if (STRCASEEQ(powerInfo->startAction, "powerOn")) {
                *autostart = 1;
            }

            break;
        }
    }

    result = 0;

3376
 cleanup:
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 3427 3428 3429 3430 3431 3432
    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;
            }

3433
            for (powerInfo = powerInfoList; powerInfo;
3434 3435
                 powerInfo = powerInfo->_next) {
                if (STRNEQ(powerInfo->key->value, virtualMachine->obj->value)) {
3436 3437 3438
                    virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                                   _("Cannot enable general autostart option "
                                     "without affecting other domains"));
3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454
                    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 ||
3455
        esxVI_Int_Alloc(&newPowerInfo->stopDelay) < 0) {
3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466
        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";

3467 3468 3469 3470 3471
    if (esxVI_AutoStartPowerInfo_AppendToList(&spec->powerInfo,
                                              newPowerInfo) < 0) {
        goto cleanup;
    }

3472
    newPowerInfo = NULL;
3473

3474 3475 3476 3477 3478 3479 3480 3481 3482
    if (esxVI_ReconfigureAutostart
          (priv->primary,
           priv->primary->hostSystem->configManager->autoStartManager,
           spec) < 0) {
        goto cleanup;
    }

    result = 0;

3483
 cleanup:
3484
    if (newPowerInfo) {
3485 3486 3487 3488 3489 3490 3491 3492 3493 3494
        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);

3495
    esxVI_AutoStartPowerInfo_Free(&newPowerInfo);
3496

3497 3498 3499 3500 3501
    return result;
}



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

3537
    if (VIR_STRDUP(type, "allocation") < 0)
3538
        return NULL;
3539

3540
    if (nparams) {
3541 3542
        *nparams = 3; /* reservation, limit, shares */
    }
3543 3544 3545 3546 3547 3548 3549

    return type;
}



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

3563 3564
    virCheckFlags(0, -1);

3565
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3566
        return -1;
3567 3568
    }

3569
    if (esxVI_String_AppendValueListToList(&propertyNameList,
3570 3571 3572
                                           "config.cpuAllocation.reservation\0"
                                           "config.cpuAllocation.limit\0"
                                           "config.cpuAllocation.shares\0") < 0 ||
3573
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
3574
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3575
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3576
        goto cleanup;
3577 3578 3579
    }

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

            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:
3639 3640 3641
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Shares level has unknown value %d"),
                               (int)sharesInfo->level);
3642
                esxVI_SharesInfo_Free(&sharesInfo);
M
Matthias Bolte 已提交
3643
                goto cleanup;
3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655
            }

            esxVI_SharesInfo_Free(&sharesInfo);

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

    *nparams = i;
M
Matthias Bolte 已提交
3656
    result = 0;
3657

3658
 cleanup:
3659 3660 3661 3662 3663 3664
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
}

3665 3666 3667 3668 3669 3670
static int
esxDomainGetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int *nparams)
{
    return esxDomainGetSchedulerParametersFlags(domain, params, nparams, 0);
}
3671 3672 3673


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

3688
    virCheckFlags(0, -1);
3689 3690 3691 3692 3693 3694 3695 3696
    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)
3697
        return -1;
3698

3699
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3700
        return -1;
3701 3702
    }

3703
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3704
          (priv->primary, domain->uuid, NULL, &virtualMachine,
3705
           priv->parsedUri->autoAnswer) < 0 ||
3706 3707
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->cpuAllocation) < 0) {
M
Matthias Bolte 已提交
3708
        goto cleanup;
3709 3710 3711
    }

    for (i = 0; i < nparams; ++i) {
3712
        if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_RESERVATION)) {
3713
            if (esxVI_Long_Alloc(&spec->cpuAllocation->reservation) < 0) {
M
Matthias Bolte 已提交
3714
                goto cleanup;
3715 3716 3717
            }

            if (params[i].value.l < 0) {
3718 3719 3720
                virReportError(VIR_ERR_INVALID_ARG,
                               _("Could not set reservation to %lld MHz, expecting "
                                 "positive value"), params[i].value.l);
M
Matthias Bolte 已提交
3721
                goto cleanup;
3722 3723 3724
            }

            spec->cpuAllocation->reservation->value = params[i].value.l;
3725
        } else if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_LIMIT)) {
3726
            if (esxVI_Long_Alloc(&spec->cpuAllocation->limit) < 0) {
M
Matthias Bolte 已提交
3727
                goto cleanup;
3728 3729 3730
            }

            if (params[i].value.l < -1) {
3731 3732 3733 3734
                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 已提交
3735
                goto cleanup;
3736 3737 3738
            }

            spec->cpuAllocation->limit->value = params[i].value.l;
3739
        } else if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_SHARES)) {
3740 3741
            if (esxVI_SharesInfo_Alloc(&sharesInfo) < 0 ||
                esxVI_Int_Alloc(&sharesInfo->shares) < 0) {
M
Matthias Bolte 已提交
3742
                goto cleanup;
3743 3744 3745
            }

            spec->cpuAllocation->shares = sharesInfo;
3746
            sharesInfo = NULL;
3747

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

3781
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
3782
                              &task) < 0 ||
3783
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3784
                                    esxVI_Occurrence_RequiredItem,
3785
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3786
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3787
        goto cleanup;
3788 3789 3790
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3791 3792 3793
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not change scheduler parameters: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3794
        goto cleanup;
3795 3796
    }

M
Matthias Bolte 已提交
3797 3798
    result = 0;

3799
 cleanup:
3800
    esxVI_SharesInfo_Free(&sharesInfo);
3801 3802 3803
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
3804
    VIR_FREE(taskInfoErrorMessage);
3805 3806 3807 3808

    return result;
}

3809 3810 3811 3812 3813 3814
static int
esxDomainSetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int nparams)
{
    return esxDomainSetSchedulerParametersFlags(domain, params, nparams, 0);
}
3815

E
Eric Blake 已提交
3816 3817 3818 3819 3820 3821
/* 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)
3822 3823 3824 3825 3826

static int
esxDomainMigratePrepare(virConnectPtr dconn,
                        char **cookie ATTRIBUTE_UNUSED,
                        int *cookielen ATTRIBUTE_UNUSED,
3827 3828
                        const char *uri_in ATTRIBUTE_UNUSED,
                        char **uri_out,
E
Eric Blake 已提交
3829
                        unsigned long flags,
3830 3831 3832
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
3833
    esxPrivate *priv = dconn->privateData;
3834

E
Eric Blake 已提交
3835 3836
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

3837
    if (!uri_in) {
3838 3839 3840
        if (virAsprintf(uri_out, "vpxmigr://%s/%s/%s",
                        priv->vCenter->ipAddress,
                        priv->vCenter->computeResource->resourcePool->value,
3841
                        priv->vCenter->hostSystem->_reference->value) < 0)
3842
            return -1;
3843 3844
    }

3845
    return 0;
3846 3847 3848 3849 3850 3851 3852 3853 3854
}



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

E
Eric Blake 已提交
3873 3874
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

3875
    if (!priv->vCenter) {
3876 3877
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration not possible without a vCenter"));
M
Matthias Bolte 已提交
3878
        return -1;
3879 3880
    }

3881
    if (dname) {
3882 3883
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Renaming domains on migration not supported"));
M
Matthias Bolte 已提交
3884
        return -1;
3885 3886
    }

3887
    if (esxVI_EnsureSession(priv->vCenter) < 0) {
M
Matthias Bolte 已提交
3888
        return -1;
3889 3890
    }

3891
    /* Parse migration URI */
3892
    if (!(parsedUri = virURIParse(uri)))
M
Matthias Bolte 已提交
3893
        return -1;
3894

3895
    if (!parsedUri->scheme || STRCASENEQ(parsedUri->scheme, "vpxmigr")) {
3896 3897
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Only vpxmigr:// migration URIs are supported"));
M
Matthias Bolte 已提交
3898
        goto cleanup;
3899 3900
    }

3901
    if (STRCASENEQ(priv->vCenter->ipAddress, parsedUri->server)) {
3902 3903 3904
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration source and destination have to refer to "
                         "the same vCenter"));
3905 3906 3907 3908 3909 3910
        goto cleanup;
    }

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

3911
    if (!path_resourcePool || !path_hostSystem) {
3912 3913
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration URI has to specify resource pool and host system"));
M
Matthias Bolte 已提交
3914
        goto cleanup;
3915 3916
    }

3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929
    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,
3930
           priv->parsedUri->autoAnswer) < 0) {
M
Matthias Bolte 已提交
3931
        goto cleanup;
3932 3933 3934
    }

    /* Validate the purposed migration */
3935
    if (esxVI_ValidateMigration(priv->vCenter, virtualMachine->obj,
3936 3937
                                esxVI_VirtualMachinePowerState_Undefined, NULL,
                                &resourcePool, &hostSystem, &eventList) < 0) {
M
Matthias Bolte 已提交
3938
        goto cleanup;
3939 3940
    }

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

M
Matthias Bolte 已提交
3956
        goto cleanup;
3957 3958 3959
    }

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

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3973 3974 3975 3976
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not migrate domain, migration task finished with "
                         "an error: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3977
        goto cleanup;
3978 3979
    }

M
Matthias Bolte 已提交
3980 3981
    result = 0;

3982
 cleanup:
3983
    virURIFree(parsedUri);
3984 3985 3986
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Event_Free(&eventList);
    esxVI_ManagedObjectReference_Free(&task);
3987
    VIR_FREE(taskInfoErrorMessage);
3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998

    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 已提交
3999
                       unsigned long flags)
4000
{
E
Eric Blake 已提交
4001 4002
    virCheckFlags(ESX_MIGRATION_FLAGS, NULL);

4003 4004 4005 4006 4007
    return esxDomainLookupByName(dconn, dname);
}



M
Matthias Bolte 已提交
4008 4009 4010 4011
static unsigned long long
esxNodeGetFreeMemory(virConnectPtr conn)
{
    unsigned long long result = 0;
M
Matthias Bolte 已提交
4012
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
4013 4014 4015 4016 4017
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *resourcePool = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ResourcePoolResourceUsage *resourcePoolResourceUsage = NULL;

4018
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4019
        return 0;
M
Matthias Bolte 已提交
4020 4021 4022
    }

    /* Get memory usage of resource pool */
4023
    if (esxVI_String_AppendValueToList(&propertyNameList,
M
Matthias Bolte 已提交
4024
                                       "runtime.memory") < 0 ||
4025 4026
        esxVI_LookupObjectContentByType(priv->primary,
                                        priv->primary->computeResource->resourcePool,
4027
                                        "ResourcePool", propertyNameList,
4028 4029
                                        &resourcePool,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4030
        goto cleanup;
M
Matthias Bolte 已提交
4031 4032
    }

4033
    for (dynamicProperty = resourcePool->propSet; dynamicProperty;
M
Matthias Bolte 已提交
4034 4035 4036
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.memory")) {
            if (esxVI_ResourcePoolResourceUsage_CastFromAnyType
4037
                  (dynamicProperty->val, &resourcePoolResourceUsage) < 0) {
M
Matthias Bolte 已提交
4038
                goto cleanup;
M
Matthias Bolte 已提交
4039 4040 4041 4042 4043 4044 4045 4046
            }

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

4047
    if (!resourcePoolResourceUsage) {
4048 4049
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not retrieve memory usage of resource pool"));
M
Matthias Bolte 已提交
4050
        goto cleanup;
M
Matthias Bolte 已提交
4051 4052 4053 4054
    }

    result = resourcePoolResourceUsage->unreservedForVm->value;

4055
 cleanup:
M
Matthias Bolte 已提交
4056 4057 4058 4059 4060 4061 4062 4063 4064
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&resourcePool);
    esxVI_ResourcePoolResourceUsage_Free(&resourcePoolResourceUsage);

    return result;
}



4065
static int
4066
esxConnectIsEncrypted(virConnectPtr conn)
4067
{
M
Matthias Bolte 已提交
4068
    esxPrivate *priv = conn->privateData;
4069

4070
    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
4071 4072 4073 4074 4075 4076 4077 4078 4079
        return 1;
    } else {
        return 0;
    }
}



static int
4080
esxConnectIsSecure(virConnectPtr conn)
4081
{
M
Matthias Bolte 已提交
4082
    esxPrivate *priv = conn->privateData;
4083

4084
    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
4085 4086 4087 4088 4089 4090 4091 4092
        return 1;
    } else {
        return 0;
    }
}



4093
static int
4094
esxConnectIsAlive(virConnectPtr conn)
4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109
{
    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;
}



4110 4111 4112
static int
esxDomainIsActive(virDomainPtr domain)
{
M
Matthias Bolte 已提交
4113
    int result = -1;
M
Matthias Bolte 已提交
4114
    esxPrivate *priv = domain->conn->privateData;
4115 4116 4117 4118
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

4119
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4120
        return -1;
4121 4122
    }

4123
    if (esxVI_String_AppendValueToList(&propertyNameList,
4124
                                       "runtime.powerState") < 0 ||
4125
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
4126
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
4127
                                         esxVI_Occurrence_RequiredItem) < 0 ||
4128
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
4129
        goto cleanup;
4130 4131 4132 4133 4134 4135 4136 4137
    }

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

4138
 cleanup:
4139 4140 4141 4142 4143 4144 4145 4146 4147
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
4148
esxDomainIsPersistent(virDomainPtr domain)
4149
{
4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165
    /* 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;

4166
 cleanup:
4167 4168 4169
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
4170 4171
}

M
Matthias Bolte 已提交
4172 4173


4174 4175 4176
static int
esxDomainIsUpdated(virDomainPtr domain ATTRIBUTE_UNUSED)
{
4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192
    /* 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;

4193
 cleanup:
4194 4195 4196
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
4197
}
4198

M
Matthias Bolte 已提交
4199 4200


4201 4202
static virDomainSnapshotPtr
esxDomainSnapshotCreateXML(virDomainPtr domain, const char *xmlDesc,
4203
                           unsigned int flags)
4204 4205 4206 4207 4208 4209 4210 4211
{
    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;
4212
    char *taskInfoErrorMessage = NULL;
4213
    virDomainSnapshotPtr snapshot = NULL;
4214 4215
    bool diskOnly = (flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY) != 0;
    bool quiesce = (flags & VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE) != 0;
4216

4217 4218 4219 4220 4221
    /* 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);
4222

4223
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4224
        return NULL;
4225 4226
    }

4227
    def = virDomainSnapshotDefParseString(xmlDesc, priv->caps,
4228
                                          priv->xmlopt, 0, 0);
4229

4230
    if (!def) {
M
Matthias Bolte 已提交
4231
        return NULL;
4232 4233
    }

4234
    if (def->ndisks) {
4235 4236
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("disk snapshots not supported yet"));
4237 4238 4239
        return NULL;
    }

4240
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
4241
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4242
           priv->parsedUri->autoAnswer) < 0 ||
4243
        esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4244 4245
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, def->name,
4246
                                    &snapshotTree, NULL,
4247
                                    esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4248
        goto cleanup;
4249 4250
    }

4251
    if (snapshotTree) {
4252 4253
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Snapshot '%s' already exists"), def->name);
M
Matthias Bolte 已提交
4254
        goto cleanup;
4255 4256
    }

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

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4270 4271
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not create snapshot: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4272
        goto cleanup;
4273 4274 4275 4276
    }

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

4277
 cleanup:
4278 4279 4280 4281
    virDomainSnapshotDefFree(def);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4282
    VIR_FREE(taskInfoErrorMessage);
4283 4284 4285 4286 4287 4288 4289

    return snapshot;
}



static char *
4290 4291
esxDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                            unsigned int flags)
4292 4293 4294 4295 4296 4297 4298 4299 4300
{
    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;

4301 4302
    virCheckFlags(0, NULL);

4303
    memset(&def, 0, sizeof(def));
4304

4305
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4306
        return NULL;
4307 4308
    }

4309
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4310 4311 4312 4313
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4314
        goto cleanup;
4315 4316 4317 4318
    }

    def.name = snapshot->name;
    def.description = snapshotTree->description;
4319
    def.parent = snapshotTreeParent ? snapshotTreeParent->name : NULL;
4320 4321 4322

    if (esxVI_DateTime_ConvertToCalendarTime(snapshotTree->createTime,
                                             &def.creationTime) < 0) {
M
Matthias Bolte 已提交
4323
        goto cleanup;
4324 4325 4326 4327 4328 4329 4330
    }

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

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

4331
    xml = virDomainSnapshotDefFormat(uuid_string, &def, flags, 0);
4332

4333
 cleanup:
4334 4335 4336 4337 4338 4339 4340 4341
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return xml;
}



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

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

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

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

4361 4362 4363 4364
    /* ESX snapshots do not require libvirt to maintain any metadata.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA)
        return 0;

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

4370 4371
    count = esxVI_GetNumberOfSnapshotTrees(rootSnapshotTreeList, recurse,
                                           leaves);
4372 4373 4374

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

M
Matthias Bolte 已提交
4375
    return count;
4376 4377 4378 4379 4380 4381
}



static int
esxDomainSnapshotListNames(virDomainPtr domain, char **names, int nameslen,
4382
                           unsigned int flags)
4383
{
M
Matthias Bolte 已提交
4384
    int result;
4385 4386
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
4387
    bool recurse;
4388
    bool leaves;
4389 4390

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
4391 4392
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4393

4394
    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) == 0;
4395
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4396

4397
    if (!names || nameslen < 0) {
4398
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
4399 4400 4401
        return -1;
    }

4402
    if (nameslen == 0 || (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA)) {
4403 4404 4405
        return 0;
    }

4406
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4407
        return -1;
4408 4409
    }

4410
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4411
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4412
        return -1;
4413 4414
    }

4415
    result = esxVI_GetSnapshotTreeNames(rootSnapshotTreeList, names, nameslen,
4416
                                        recurse, leaves);
4417 4418 4419 4420 4421 4422 4423 4424

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



4425 4426 4427 4428 4429 4430 4431 4432
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;
4433
    bool leaves;
4434 4435

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
4436 4437
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4438 4439

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) != 0;
4440
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460

    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,
4461
                                           recurse, leaves);
4462

4463
 cleanup:
4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480
    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;
4481
    bool leaves;
4482 4483

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
4484 4485
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4486 4487

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) != 0;
4488
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4489

4490
    if (!names || nameslen < 0) {
4491
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517
        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,
4518
                                        names, nameslen, recurse, leaves);
4519

4520
 cleanup:
4521 4522 4523 4524 4525 4526 4527
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



4528 4529
static virDomainSnapshotPtr
esxDomainSnapshotLookupByName(virDomainPtr domain, const char *name,
4530
                              unsigned int flags)
4531 4532 4533 4534 4535 4536
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    virDomainSnapshotPtr snapshot = NULL;

4537 4538
    virCheckFlags(0, NULL);

4539
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4540
        return NULL;
4541 4542
    }

4543
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4544 4545
                                         &rootSnapshotTreeList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotTreeList, name, &snapshotTree,
4546
                                    NULL,
4547 4548 4549 4550 4551 4552
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    snapshot = virGetDomainSnapshot(domain, name);

4553
 cleanup:
4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return snapshot;
}



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

4567
    virCheckFlags(0, -1);
4568

4569
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4570
        return -1;
4571 4572
    }

4573
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4574 4575
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4576
        return -1;
4577 4578
    }

4579
    if (currentSnapshotTree) {
M
Matthias Bolte 已提交
4580 4581
        esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);
        return 1;
4582 4583
    }

M
Matthias Bolte 已提交
4584
    return 0;
4585 4586 4587 4588
}



E
Eric Blake 已提交
4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612
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) {
4613 4614 4615
        virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                       _("snapshot '%s' does not have a parent"),
                       snapshotTree->name);
E
Eric Blake 已提交
4616 4617 4618 4619 4620
        goto cleanup;
    }

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

4621
 cleanup:
E
Eric Blake 已提交
4622 4623 4624 4625 4626 4627 4628
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return parent;
}



4629 4630 4631 4632 4633
static virDomainSnapshotPtr
esxDomainSnapshotCurrent(virDomainPtr domain, unsigned int flags)
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *currentSnapshotTree = NULL;
M
Matthias Bolte 已提交
4634
    virDomainSnapshotPtr snapshot = NULL;
4635

4636
    virCheckFlags(0, NULL);
4637

4638
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4639
        return NULL;
4640 4641
    }

4642
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4643 4644
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4645
        return NULL;
4646 4647 4648 4649 4650 4651 4652 4653 4654 4655
    }

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

    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return snapshot;
}


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 4682 4683 4684 4685 4686 4687
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);

4688
 cleanup:
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 4714 4715 4716 4717 4718 4719
    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;

4720
 cleanup:
4721 4722 4723 4724
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    return ret;
}

4725 4726 4727 4728

static int
esxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4729
    int result = -1;
4730 4731 4732 4733 4734
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
4735
    char *taskInfoErrorMessage = NULL;
4736

4737
    virCheckFlags(0, -1);
4738

4739
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4740
        return -1;
4741 4742
    }

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

4751
    if (esxVI_RevertToSnapshot_Task(priv->primary, snapshotTree->snapshot, NULL,
4752
                                    esxVI_Boolean_Undefined, &task) < 0 ||
4753
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4754
                                    esxVI_Occurrence_RequiredItem,
4755
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4756
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4757
        goto cleanup;
4758 4759 4760
    }

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

M
Matthias Bolte 已提交
4767 4768
    result = 0;

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

    return result;
}



static int
esxDomainSnapshotDelete(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4782
    int result = -1;
4783 4784 4785 4786 4787 4788
    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;
4789
    char *taskInfoErrorMessage = NULL;
4790

4791 4792
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
                  VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY, -1);
4793

4794
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4795
        return -1;
4796 4797 4798 4799 4800 4801
    }

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

4802
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4803 4804
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
4805
                                    &snapshotTree, NULL,
4806
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4807
        goto cleanup;
4808 4809
    }

4810 4811 4812 4813 4814 4815 4816
    /* 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;
    }

4817
    if (esxVI_RemoveSnapshot_Task(priv->primary, snapshotTree->snapshot,
4818
                                  removeChildren, &task) < 0 ||
4819
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4820
                                    esxVI_Occurrence_RequiredItem,
4821
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4822
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4823
        goto cleanup;
4824 4825 4826
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4827 4828 4829
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not delete snapshot '%s': %s"), snapshot->name,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4830
        goto cleanup;
4831 4832
    }

M
Matthias Bolte 已提交
4833 4834
    result = 0;

4835
 cleanup:
4836 4837
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4838
    VIR_FREE(taskInfoErrorMessage);
4839 4840 4841 4842 4843 4844

    return result;
}



4845
static int
4846
esxDomainSetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
4847 4848 4849 4850 4851 4852 4853 4854
                             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;
4855
    char *taskInfoErrorMessage = NULL;
4856
    size_t i;
4857 4858

    virCheckFlags(0, -1);
4859 4860 4861 4862
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_MEMORY_MIN_GUARANTEE,
                               VIR_TYPED_PARAM_ULLONG,
                               NULL) < 0)
4863
        return -1;
4864 4865 4866 4867 4868 4869 4870

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

    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4871
           priv->parsedUri->autoAnswer) < 0 ||
4872 4873 4874 4875 4876 4877
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0) {
        goto cleanup;
    }

    for (i = 0; i < nparams; ++i) {
4878
        if (STREQ(params[i].field, VIR_DOMAIN_MEMORY_MIN_GUARANTEE)) {
4879 4880 4881 4882 4883
            if (esxVI_Long_Alloc(&spec->memoryAllocation->reservation) < 0) {
                goto cleanup;
            }

            spec->memoryAllocation->reservation->value =
4884
              VIR_DIV_UP(params[i].value.ul, 1024); /* Scale from kilobytes to megabytes */
4885 4886 4887 4888 4889 4890 4891
        }
    }

    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
4892
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4893
                                    &taskInfoErrorMessage) < 0) {
4894 4895 4896 4897
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4898 4899 4900
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not change memory parameters: %s"),
                       taskInfoErrorMessage);
4901 4902 4903 4904 4905
        goto cleanup;
    }

    result = 0;

4906
 cleanup:
4907 4908 4909
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
4910
    VIR_FREE(taskInfoErrorMessage);
4911 4912 4913 4914 4915 4916 4917

    return result;
}



static int
4918
esxDomainGetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947
                             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;
    }

4948 4949 4950 4951
    /* Scale from megabytes to kilobytes */
    if (virTypedParameterAssign(params, VIR_DOMAIN_MEMORY_MIN_GUARANTEE,
                                VIR_TYPED_PARAM_ULLONG,
                                reservation->value * 1024) < 0)
4952 4953 4954 4955 4956
        goto cleanup;

    *nparams = 1;
    result = 0;

4957
 cleanup:
4958 4959 4960 4961 4962 4963 4964
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Long_Free(&reservation);

    return result;
}

4965 4966
#define MATCH(FLAG) (flags & (FLAG))
static int
4967 4968 4969
esxConnectListAllDomains(virConnectPtr conn,
                         virDomainPtr **domains,
                         unsigned int flags)
4970 4971 4972
{
    int ret = -1;
    esxPrivate *priv = conn->privateData;
4973 4974
    bool needIdentity;
    bool needPowerState;
4975 4976 4977
    virDomainPtr dom;
    virDomainPtr *doms = NULL;
    size_t ndoms = 0;
4978
    esxVI_String *propertyNameList = NULL;
4979 4980
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
4981
    esxVI_AutoStartDefaults *autoStartDefaults = NULL;
4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998
    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
     */
4999
    if ((MATCH(VIR_CONNECT_LIST_DOMAINS_TRANSIENT) &&
5000 5001 5002 5003 5004
         !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)
5005
            goto cleanup;
5006 5007 5008 5009 5010

        ret = 0;
        goto cleanup;
    }

5011
    if (esxVI_EnsureSession(priv->primary) < 0)
5012 5013 5014 5015 5016
        return -1;

    /* check system default autostart value */
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_AUTOSTART)) {
        if (esxVI_LookupAutoStartDefaults(priv->primary,
5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029
                                          &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) ||
5030
                   domains;
5031 5032 5033 5034 5035 5036 5037

    if (needIdentity) {
        /* Request required data for esxVI_GetVirtualMachineIdentity */
        if (esxVI_String_AppendValueListToList(&propertyNameList,
                                               "configStatus\0"
                                               "name\0"
                                               "config.uuid\0") < 0) {
5038
            goto cleanup;
5039 5040 5041 5042 5043
        }
    }

    needPowerState = MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_ACTIVE) ||
                     MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_STATE) ||
5044
                     domains;
5045

5046 5047 5048
    if (needPowerState) {
        if (esxVI_String_AppendValueToList(&propertyNameList,
                                           "runtime.powerState") < 0) {
5049
            goto cleanup;
5050
        }
5051 5052
    }

5053
    if (esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
5054 5055 5056 5057 5058
                                       &virtualMachineList) < 0)
        goto cleanup;

    if (domains) {
        if (VIR_ALLOC_N(doms, 1) < 0)
5059
            goto cleanup;
5060 5061 5062
        ndoms = 1;
    }

5063
    for (virtualMachine = virtualMachineList; virtualMachine;
5064
         virtualMachine = virtualMachine->_next) {
5065 5066
        if (needIdentity) {
            VIR_FREE(name);
5067

5068 5069 5070 5071 5072
            if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id,
                                                &name, uuid) < 0) {
                goto cleanup;
            }
        }
5073

5074 5075 5076 5077 5078 5079
        if (needPowerState) {
            if (esxVI_GetVirtualMachinePowerState(virtualMachine,
                                                  &powerState) < 0) {
                goto cleanup;
            }
        }
5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090

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

5093 5094 5095 5096 5097 5098
            if (esxVI_LookupRootSnapshotTreeList(priv->primary, uuid,
                                                 &rootSnapshotTreeList) < 0) {
                goto cleanup;
            }

            if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT) &&
5099
                   rootSnapshotTreeList) ||
5100
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT) &&
5101
                   !rootSnapshotTreeList)))
5102 5103 5104 5105 5106 5107 5108
                continue;
        }

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

5109
            if (autoStartDefaults->enabled == esxVI_Boolean_True) {
5110
                for (powerInfo = powerInfoList; powerInfo;
5111 5112 5113 5114
                     powerInfo = powerInfo->_next) {
                    if (STREQ(powerInfo->key->value, virtualMachine->obj->value)) {
                        if (STRCASEEQ(powerInfo->startAction, "powerOn"))
                            autostart = true;
5115

5116 5117
                        break;
                    }
5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130
                }
            }

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

5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150
            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;
        }

5151
        if (VIR_RESIZE_N(doms, ndoms, count, 2) < 0)
5152
            goto cleanup;
5153

5154 5155 5156
        if (!(dom = virGetDomain(conn, name, uuid)))
            goto cleanup;

5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170
        /* 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;

5171
 cleanup:
5172 5173
    if (doms) {
        for (id = 0; id < count; id++) {
5174
            virDomainFree(doms[id]);
5175
        }
5176 5177

        VIR_FREE(doms);
5178
    }
5179

5180
    VIR_FREE(name);
5181 5182
    esxVI_AutoStartDefaults_Free(&autoStartDefaults);
    esxVI_AutoStartPowerInfo_Free(&powerInfoList);
5183 5184
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
5185 5186
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

5187 5188 5189
    return ret;
}
#undef MATCH
5190 5191


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



int
esxRegister(void)
{
5276 5277 5278 5279 5280
    if (virRegisterDriver(&esxDriver) < 0 ||
        esxInterfaceRegister() < 0 ||
        esxNetworkRegister() < 0 ||
        esxStorageRegister() < 0 ||
        esxDeviceRegister() < 0 ||
M
Matthias Bolte 已提交
5281 5282
        esxSecretRegister() < 0 ||
        esxNWFilterRegister() < 0) {
5283 5284
        return -1;
    }
5285 5286 5287

    return 0;
}