esx_driver.c 168.4 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
        if (virBufferCheckError(&buffer) < 0)
344 345 346 347 348
            goto cleanup;

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

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

    success = true;

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

    VIR_FREE(datastoreName);
369
    VIR_FREE(directoryAndFileName);
370 371
    esxVI_ObjectContent_Free(&datastore);
    esxVI_DatastoreHostMount_Free(&hostMount);
372

373
    return result;
374 375 376 377 378 379 380 381 382 383
}



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

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

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

405
    vmDiskFileInfo = esxVI_VmDiskFileInfo_DynamicCast(fileInfo);
406

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

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

    result = 0;

434
 cleanup:
435
    esxVI_FileInfo_Free(&fileInfo);
436 437 438 439

    return result;
}

440 441


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

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

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

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

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

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

484
                    edxLongModeBit = parsedHostCpuIdInfo.edx[29];
485 486 487 488 489 490

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

                    break;
                }
            }

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

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

    return priv->supportsLongMode;
}



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

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

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

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

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

    result = 0;

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

    return result;
}


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

573 574 575 576 577
    if (supportsLongMode == esxVI_Boolean_Undefined) {
        return NULL;
    }

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

583
    if (!caps)
584 585
        return NULL;

586
    virCapabilitiesAddHostMigrateTransport(caps, "vpxmigr");
587

588

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

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

599
    if (!guest) {
600 601 602
        goto failure;
    }

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

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

614
        if (!guest) {
615 616 617
            goto failure;
        }

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

623 624
    return caps;

625
 failure:
626
    virObjectUnref(caps);
627 628 629 630 631 632

    return NULL;
}



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

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

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

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

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

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

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

M
Matthias Bolte 已提交
680 681
    password = esxUtil_EscapeForXml(unescapedPassword);

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

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

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

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

    /* Query the host for maintenance mode and vCenter IP address */
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "runtime.inMaintenanceMode\0"
                                           "summary.managementServerIp\0") < 0 ||
722 723
        esxVI_LookupHostSystemProperties(priv->host, propertyNameList,
                                         &hostSystem) < 0 ||
724 725 726 727 728 729 730 731 732 733 734
        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) {
735
        VIR_WARN("The server is in maintenance mode");
736 737
    }

738 739
    if (VIR_STRDUP(*vCenterIpAddress, *vCenterIpAddress) < 0)
        goto cleanup;
740 741 742

    result = 0;

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

    return result;
}



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

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

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

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

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

794
    unescapedPassword = virAuthGetPassword(conn, auth, "esx", username, hostname);
795

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

M
Matthias Bolte 已提交
801 802
    password = esxUtil_EscapeForXml(unescapedPassword);

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

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

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

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

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

842 843
    result = 0;

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

    return result;
}



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

E
Eric Blake 已提交
910 911
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

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

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

920
    if (!plus) {
921 922 923 924 925 926 927 928 929 930 931 932 933
        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;
        }

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

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

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

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

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

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

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

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

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

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

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

1026
                if (potentialVCenterIpAddress &&
1027
                    STRNEQ(vCenterIpAddress, potentialVCenterIpAddress)) {
1028 1029 1030 1031 1032 1033
                    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 已提交
1034
                    goto cleanup;
1035 1036
                }
            }
1037

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

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

1054
        priv->primary = priv->vCenter;
1055 1056
    }

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

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

1064
    if (!(priv->xmlopt = virVMXDomainXMLConfInit()))
1065 1066
        goto cleanup;

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

1071
 cleanup:
1072
    esxFreePrivate(&priv);
1073
    VIR_FREE(potentialVCenterIpAddress);
1074

M
Matthias Bolte 已提交
1075
    return result;
1076 1077 1078 1079 1080
}



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

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

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

1100
    esxFreePrivate(&priv);
1101 1102 1103

    conn->privateData = NULL;

E
Eric Blake 已提交
1104
    return result;
1105 1106 1107 1108 1109
}



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

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

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

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

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

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



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

    switch (feature) {
      case VIR_DRV_FEATURE_MIGRATION_V1:
1154
        supportsVMotion = esxSupportsVMotion(priv);
1155

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

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

      default:
        return 0;
    }
}



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



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

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

1190
        return -1;
1191 1192 1193 1194 1195 1196 1197 1198
    }

    return 0;
}



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

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

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

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

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

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

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

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

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

    return complete;
}



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

1289
    memset(nodeinfo, 0, sizeof(*nodeinfo));
1290

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

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

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

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

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

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

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

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

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

            ptr = dynamicProperty->val->string;

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

                ++ptr;
            }

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

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

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

    return result;
}



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

1422
    return virCapabilitiesFormatXML(priv->caps);
1423 1424 1425 1426
}



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

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

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

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

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

        if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

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

        count++;

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

M
Matthias Bolte 已提交
1480 1481
    success = true;

1482
 cleanup:
1483 1484 1485
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

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



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

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

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



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

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

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

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

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

M
Matthias Bolte 已提交
1545
        VIR_FREE(name_candidate);
1546

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

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

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

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

        domain->id = id;

        break;
    }

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

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

    return domain;
}



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

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

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

1608
    domain = virGetDomain(conn, name, uuid);
1609

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

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

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

    return domain;
}



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

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

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

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

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

1666
    domain = virGetDomain(conn, name, uuid);
1667

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

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

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

    return domain;
}



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

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

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

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

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

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

M
Matthias Bolte 已提交
1733 1734
    result = 0;

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

    return result;
}



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

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

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

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

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

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

M
Matthias Bolte 已提交
1791 1792
    result = 0;

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

    return result;
}



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

1813 1814
    virCheckFlags(0, -1);

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

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

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

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

M
Matthias Bolte 已提交
1838 1839
    result = 0;

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

    return result;
}


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

1854 1855

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

E
Eric Blake 已提交
1864 1865
    virCheckFlags(0, -1);

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

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

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

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

M
Matthias Bolte 已提交
1889 1890
    result = 0;

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

    return result;
}



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

1914 1915
    virCheckFlags(0, -1);

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

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

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

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

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

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

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

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

    return result;
}


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

1974 1975

static char *
1976
esxDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED)
1977
{
1978
    char *osType;
1979

1980
    ignore_value(VIR_STRDUP(osType, "hvm"));
1981
    return osType;
1982 1983 1984 1985
}



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

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

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

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

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

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

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

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

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

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

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

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

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

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

M
Matthias Bolte 已提交
2095 2096
    result = 0;

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

    return result;
}



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

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

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

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

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

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

M
Matthias Bolte 已提交
2152 2153
    result = 0;

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

    return result;
}



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

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

2199
    memset(info, 0, sizeof(*info));
M
Matthias Bolte 已提交
2200

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

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

    info->state = VIR_DOMAIN_NOSTATE;

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

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

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

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

            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;

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

2271
            counterId->value = priv->usedCpuTimeCounterId;
2272

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

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

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

2288 2289 2290 2291 2292
                priv->usedCpuTimeCounterId = -1;
            }

            esxVI_Int_Free(&counterIdList);
            esxVI_PerfCounterInfo_Free(&perfCounterInfo);
2293 2294
        }

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

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

2311
                counterId = NULL;
2312

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

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

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

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

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

2355 2356 2357 2358 2359 2360
            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;
            }
2361

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

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

2378 2379
                perfEntityMetric =
                  esxVI_PerfEntityMetric_DynamicCast(perfEntityMetricBase);
2380

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

2388 2389
                perfMetricIntSeries =
                  esxVI_PerfMetricIntSeries_DynamicCast(perfEntityMetric->value);
2390

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

2398
                for (; perfMetricIntSeries;
2399
                     perfMetricIntSeries = perfMetricIntSeries->_next) {
2400
                    VIR_DEBUG("perfMetricIntSeries ...");
2401

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

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

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

M
Matthias Bolte 已提交
2420 2421
    result = 0;

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

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

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

    return result;
}



2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486
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;

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

    return result;
}



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

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

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

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

M
Matthias Bolte 已提交
2524
    maxVcpus = esxDomainGetMaxVcpus(domain);
2525

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

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

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

    spec->numCPUs->value = nvcpus;

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

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

M
Matthias Bolte 已提交
2564 2565
    result = 0;

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

    return result;
}


M
Matthias Bolte 已提交
2576

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

2583

M
Matthias Bolte 已提交
2584

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

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

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

M
Matthias Bolte 已提交
2602 2603
    priv->maxVcpus = -1;

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

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

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

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

2630
 cleanup:
2631 2632 2633
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
2634
    return priv->maxVcpus;
2635 2636
}

M
Matthias Bolte 已提交
2637 2638


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

M
Matthias Bolte 已提交
2646 2647


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

E
Eric Blake 已提交
2668 2669
    /* Flags checked by virDomainDefFormat */

2670
    memset(&data, 0, sizeof(data));
2671

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

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

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

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

2702
    if (virBufferCheckError(&buffer) < 0)
M
Matthias Bolte 已提交
2703
        goto cleanup;
2704

2705 2706
    url = virBufferContentAndReset(&buffer);

2707
    if (esxVI_CURL_Download(priv->primary->curl, url, &vmx, 0, NULL) < 0) {
M
Matthias Bolte 已提交
2708
        goto cleanup;
2709 2710
    }

2711
    data.ctx = priv->primary;
2712

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

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

2728
    def = virVMXParseConfig(&ctx, priv->xmlopt, vmx);
2729

2730
    if (def) {
2731 2732 2733 2734
        if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
            def->id = id;
        }

2735
        xml = virDomainDefFormat(def, flags);
2736 2737
    }

2738
 cleanup:
2739
    if (!url) {
M
Matthias Bolte 已提交
2740 2741 2742
        virBufferFreeAndReset(&buffer);
    }

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

    return xml;
}



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

E
Eric Blake 已提交
2769 2770
    virCheckFlags(0, NULL);

2771
    memset(&data, 0, sizeof(data));
2772

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

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

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

2787
    def = virVMXParseConfig(&ctx, priv->xmlopt, nativeConfig);
2788

2789
    if (def) {
2790
        xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
2791 2792 2793 2794 2795 2796 2797 2798 2799
    }

    virDomainDefFree(def);

    return xml;
}



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

E
Eric Blake 已提交
2812 2813
    virCheckFlags(0, NULL);

2814
    memset(&data, 0, sizeof(data));
2815

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

2822 2823 2824 2825 2826 2827 2828
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        return NULL;
    }

2829
    def = virDomainDefParseString(domainXml, priv->caps, priv->xmlopt,
2830 2831
                                  1 << VIR_DOMAIN_VIRT_VMWARE,
                                  VIR_DOMAIN_XML_INACTIVE);
M
Matthias Bolte 已提交
2832

2833
    if (!def) {
M
Matthias Bolte 已提交
2834 2835 2836
        return NULL;
    }

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

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

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

    virDomainDefFree(def);

    return vmx;
}



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

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

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

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

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

        if (powerState == esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

2893
        names[count] = NULL;
2894

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

2900 2901
        ++count;

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

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

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

M
Matthias Bolte 已提交
2915
        count = -1;
2916 2917
    }

M
Matthias Bolte 已提交
2918 2919
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
2920

M
Matthias Bolte 已提交
2921
    return count;
2922 2923 2924 2925 2926
}



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

2931
    if (esxVI_EnsureSession(priv->primary) < 0) {
2932 2933 2934
        return -1;
    }

2935
    return esxVI_LookupNumberOfDomainsByPowerState
2936
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, true);
2937 2938 2939 2940 2941
}



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

2954 2955
    virCheckFlags(0, -1);

2956
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2957
        return -1;
2958 2959
    }

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

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2971 2972
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered off"));
M
Matthias Bolte 已提交
2973
        goto cleanup;
2974 2975
    }

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

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

2991
    domain->id = id;
M
Matthias Bolte 已提交
2992 2993
    result = 0;

2994
 cleanup:
2995 2996 2997
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
2998
    VIR_FREE(taskInfoErrorMessage);
2999 3000 3001 3002

    return result;
}

3003 3004


3005 3006 3007 3008 3009
static int
esxDomainCreate(virDomainPtr domain)
{
    return esxDomainCreateWithFlags(domain, 0);
}
3010

3011 3012


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

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

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

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

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

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

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

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

    /* Build VMX from domain XML */
3078 3079 3080 3081 3082 3083 3084
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        goto cleanup;
    }

3085
    data.ctx = priv->primary;
3086
    data.datastorePathWithoutFileName = NULL;
3087 3088 3089 3090 3091 3092

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

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

3095
    if (!vmx) {
M
Matthias Bolte 已提交
3096
        goto cleanup;
M
Matthias Bolte 已提交
3097 3098
    }

3099 3100 3101
    /*
     * Build VMX datastore URL. Use the source of the first file-based harddisk
     * to deduce the datastore and path for the VMX file. Don't just use the
N
Nehal J Wani 已提交
3102
     * first disk, because it may be CDROM disk and ISO images are normally not
3103 3104 3105
     * 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 已提交
3106
    if (def->ndisks < 1) {
3107 3108 3109
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Domain XML doesn't contain any disks, cannot deduce "
                         "datastore and path for VMX file"));
M
Matthias Bolte 已提交
3110
        goto cleanup;
3111 3112 3113 3114
    }

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

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

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

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

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

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

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

3156 3157
    escapedName = esxUtil_EscapeDatastoreItem(def->name);

3158
    if (!escapedName) {
3159 3160 3161 3162
        goto cleanup;
    }

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

3168
    if (virBufferCheckError(&buffer) < 0)
M
Matthias Bolte 已提交
3169
        goto cleanup;
M
Matthias Bolte 已提交
3170 3171 3172

    url = virBufferContentAndReset(&buffer);

3173 3174 3175 3176 3177 3178
    /* Check, if VMX file already exists */
    /* FIXME */

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

3179
    if (esxVI_CURL_Upload(priv->primary->curl, url, vmx) < 0) {
3180 3181 3182 3183
        goto cleanup;
    }

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

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

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

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

3214
    if (domain) {
M
Matthias Bolte 已提交
3215 3216 3217 3218 3219
        domain->id = -1;
    }

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

3220
 cleanup:
3221
    if (!url) {
M
Matthias Bolte 已提交
3222 3223 3224
        virBufferFreeAndReset(&buffer);
    }

M
Matthias Bolte 已提交
3225 3226 3227 3228
    virDomainDefFree(def);
    VIR_FREE(vmx);
    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
3229
    VIR_FREE(escapedName);
M
Matthias Bolte 已提交
3230 3231 3232 3233 3234 3235 3236
    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);
3237
    VIR_FREE(taskInfoErrorMessage);
M
Matthias Bolte 已提交
3238 3239 3240 3241 3242 3243

    return domain;
}



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

3255 3256 3257 3258
    /* 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);
3259

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

3266
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
3267
        return -1;
3268 3269
    }

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

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

3286
    if (esxVI_UnregisterVM(ctx, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
3287
        goto cleanup;
3288 3289
    }

M
Matthias Bolte 已提交
3290 3291
    result = 0;

3292
 cleanup:
3293 3294 3295 3296 3297 3298 3299
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}


3300 3301 3302 3303 3304
static int
esxDomainUndefine(virDomainPtr domain)
{
    return esxDomainUndefineFlags(domain, 0);
}
3305

3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338
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;
    }

3339
    if (!powerInfoList) {
3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350
        /* 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;
    }

3351
    for (powerInfo = powerInfoList; powerInfo;
3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363
         powerInfo = powerInfo->_next) {
        if (STREQ(powerInfo->key->value, virtualMachine->obj->value)) {
            if (STRCASEEQ(powerInfo->startAction, "powerOn")) {
                *autostart = 1;
            }

            break;
        }
    }

    result = 0;

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

3421
            for (powerInfo = powerInfoList; powerInfo;
3422 3423
                 powerInfo = powerInfo->_next) {
                if (STRNEQ(powerInfo->key->value, virtualMachine->obj->value)) {
3424 3425 3426
                    virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                                   _("Cannot enable general autostart option "
                                     "without affecting other domains"));
3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442
                    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 ||
3443
        esxVI_Int_Alloc(&newPowerInfo->stopDelay) < 0) {
3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454
        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";

3455 3456 3457 3458 3459
    if (esxVI_AutoStartPowerInfo_AppendToList(&spec->powerInfo,
                                              newPowerInfo) < 0) {
        goto cleanup;
    }

3460
    newPowerInfo = NULL;
3461

3462 3463 3464 3465 3466 3467 3468 3469 3470
    if (esxVI_ReconfigureAutostart
          (priv->primary,
           priv->primary->hostSystem->configManager->autoStartManager,
           spec) < 0) {
        goto cleanup;
    }

    result = 0;

3471
 cleanup:
3472
    if (newPowerInfo) {
3473 3474 3475 3476 3477 3478 3479 3480 3481 3482
        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);

3483
    esxVI_AutoStartPowerInfo_Free(&newPowerInfo);
3484

3485 3486 3487 3488 3489
    return result;
}



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

3525
    if (VIR_STRDUP(type, "allocation") < 0)
3526
        return NULL;
3527

3528
    if (nparams) {
3529 3530
        *nparams = 3; /* reservation, limit, shares */
    }
3531 3532 3533 3534 3535 3536 3537

    return type;
}



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

3551 3552
    virCheckFlags(0, -1);

3553
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3554
        return -1;
3555 3556
    }

3557
    if (esxVI_String_AppendValueListToList(&propertyNameList,
3558 3559 3560
                                           "config.cpuAllocation.reservation\0"
                                           "config.cpuAllocation.limit\0"
                                           "config.cpuAllocation.shares\0") < 0 ||
3561
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
3562
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3563
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3564
        goto cleanup;
3565 3566 3567
    }

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

            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:
3627 3628 3629
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Shares level has unknown value %d"),
                               (int)sharesInfo->level);
3630
                esxVI_SharesInfo_Free(&sharesInfo);
M
Matthias Bolte 已提交
3631
                goto cleanup;
3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643
            }

            esxVI_SharesInfo_Free(&sharesInfo);

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

    *nparams = i;
M
Matthias Bolte 已提交
3644
    result = 0;
3645

3646
 cleanup:
3647 3648 3649 3650 3651 3652
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
}

3653 3654 3655 3656 3657 3658
static int
esxDomainGetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int *nparams)
{
    return esxDomainGetSchedulerParametersFlags(domain, params, nparams, 0);
}
3659 3660 3661


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

3676
    virCheckFlags(0, -1);
3677 3678 3679 3680 3681 3682 3683 3684
    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)
3685
        return -1;
3686

3687
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3688
        return -1;
3689 3690
    }

3691
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3692
          (priv->primary, domain->uuid, NULL, &virtualMachine,
3693
           priv->parsedUri->autoAnswer) < 0 ||
3694 3695
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->cpuAllocation) < 0) {
M
Matthias Bolte 已提交
3696
        goto cleanup;
3697 3698 3699
    }

    for (i = 0; i < nparams; ++i) {
3700
        if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_RESERVATION)) {
3701
            if (esxVI_Long_Alloc(&spec->cpuAllocation->reservation) < 0) {
M
Matthias Bolte 已提交
3702
                goto cleanup;
3703 3704 3705
            }

            if (params[i].value.l < 0) {
3706 3707 3708
                virReportError(VIR_ERR_INVALID_ARG,
                               _("Could not set reservation to %lld MHz, expecting "
                                 "positive value"), params[i].value.l);
M
Matthias Bolte 已提交
3709
                goto cleanup;
3710 3711 3712
            }

            spec->cpuAllocation->reservation->value = params[i].value.l;
3713
        } else if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_LIMIT)) {
3714
            if (esxVI_Long_Alloc(&spec->cpuAllocation->limit) < 0) {
M
Matthias Bolte 已提交
3715
                goto cleanup;
3716 3717 3718
            }

            if (params[i].value.l < -1) {
3719 3720 3721 3722
                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 已提交
3723
                goto cleanup;
3724 3725 3726
            }

            spec->cpuAllocation->limit->value = params[i].value.l;
3727
        } else if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_SHARES)) {
3728 3729
            if (esxVI_SharesInfo_Alloc(&sharesInfo) < 0 ||
                esxVI_Int_Alloc(&sharesInfo->shares) < 0) {
M
Matthias Bolte 已提交
3730
                goto cleanup;
3731 3732 3733
            }

            spec->cpuAllocation->shares = sharesInfo;
3734
            sharesInfo = NULL;
3735

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

3769
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
3770
                              &task) < 0 ||
3771
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3772
                                    esxVI_Occurrence_RequiredItem,
3773
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3774
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3775
        goto cleanup;
3776 3777 3778
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3779 3780 3781
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not change scheduler parameters: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3782
        goto cleanup;
3783 3784
    }

M
Matthias Bolte 已提交
3785 3786
    result = 0;

3787
 cleanup:
3788
    esxVI_SharesInfo_Free(&sharesInfo);
3789 3790 3791
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
3792
    VIR_FREE(taskInfoErrorMessage);
3793 3794 3795 3796

    return result;
}

3797 3798 3799 3800 3801 3802
static int
esxDomainSetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int nparams)
{
    return esxDomainSetSchedulerParametersFlags(domain, params, nparams, 0);
}
3803

E
Eric Blake 已提交
3804 3805 3806 3807 3808 3809
/* 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)
3810 3811 3812 3813 3814

static int
esxDomainMigratePrepare(virConnectPtr dconn,
                        char **cookie ATTRIBUTE_UNUSED,
                        int *cookielen ATTRIBUTE_UNUSED,
3815 3816
                        const char *uri_in ATTRIBUTE_UNUSED,
                        char **uri_out,
E
Eric Blake 已提交
3817
                        unsigned long flags,
3818 3819 3820
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
3821
    esxPrivate *priv = dconn->privateData;
3822

E
Eric Blake 已提交
3823 3824
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

3825
    if (!uri_in) {
3826 3827 3828
        if (virAsprintf(uri_out, "vpxmigr://%s/%s/%s",
                        priv->vCenter->ipAddress,
                        priv->vCenter->computeResource->resourcePool->value,
3829
                        priv->vCenter->hostSystem->_reference->value) < 0)
3830
            return -1;
3831 3832
    }

3833
    return 0;
3834 3835 3836 3837 3838 3839 3840 3841 3842
}



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

E
Eric Blake 已提交
3861 3862
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

3863
    if (!priv->vCenter) {
3864 3865
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration not possible without a vCenter"));
M
Matthias Bolte 已提交
3866
        return -1;
3867 3868
    }

3869
    if (dname) {
3870 3871
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Renaming domains on migration not supported"));
M
Matthias Bolte 已提交
3872
        return -1;
3873 3874
    }

3875
    if (esxVI_EnsureSession(priv->vCenter) < 0) {
M
Matthias Bolte 已提交
3876
        return -1;
3877 3878
    }

3879
    /* Parse migration URI */
3880
    if (!(parsedUri = virURIParse(uri)))
M
Matthias Bolte 已提交
3881
        return -1;
3882

3883
    if (!parsedUri->scheme || STRCASENEQ(parsedUri->scheme, "vpxmigr")) {
3884 3885
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Only vpxmigr:// migration URIs are supported"));
M
Matthias Bolte 已提交
3886
        goto cleanup;
3887 3888
    }

3889
    if (STRCASENEQ(priv->vCenter->ipAddress, parsedUri->server)) {
3890 3891 3892
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration source and destination have to refer to "
                         "the same vCenter"));
3893 3894 3895 3896 3897 3898
        goto cleanup;
    }

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

3899
    if (!path_resourcePool || !path_hostSystem) {
3900 3901
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration URI has to specify resource pool and host system"));
M
Matthias Bolte 已提交
3902
        goto cleanup;
3903 3904
    }

3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917
    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,
3918
           priv->parsedUri->autoAnswer) < 0) {
M
Matthias Bolte 已提交
3919
        goto cleanup;
3920 3921 3922
    }

    /* Validate the purposed migration */
3923
    if (esxVI_ValidateMigration(priv->vCenter, virtualMachine->obj,
3924 3925
                                esxVI_VirtualMachinePowerState_Undefined, NULL,
                                &resourcePool, &hostSystem, &eventList) < 0) {
M
Matthias Bolte 已提交
3926
        goto cleanup;
3927 3928
    }

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

M
Matthias Bolte 已提交
3944
        goto cleanup;
3945 3946 3947
    }

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

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3961 3962 3963 3964
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not migrate domain, migration task finished with "
                         "an error: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3965
        goto cleanup;
3966 3967
    }

M
Matthias Bolte 已提交
3968 3969
    result = 0;

3970
 cleanup:
3971
    virURIFree(parsedUri);
3972 3973 3974
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Event_Free(&eventList);
    esxVI_ManagedObjectReference_Free(&task);
3975
    VIR_FREE(taskInfoErrorMessage);
3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986

    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 已提交
3987
                       unsigned long flags)
3988
{
E
Eric Blake 已提交
3989 3990
    virCheckFlags(ESX_MIGRATION_FLAGS, NULL);

3991 3992 3993 3994 3995
    return esxDomainLookupByName(dconn, dname);
}



M
Matthias Bolte 已提交
3996 3997 3998 3999
static unsigned long long
esxNodeGetFreeMemory(virConnectPtr conn)
{
    unsigned long long result = 0;
M
Matthias Bolte 已提交
4000
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
4001 4002 4003 4004 4005
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *resourcePool = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ResourcePoolResourceUsage *resourcePoolResourceUsage = NULL;

4006
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4007
        return 0;
M
Matthias Bolte 已提交
4008 4009 4010
    }

    /* Get memory usage of resource pool */
4011
    if (esxVI_String_AppendValueToList(&propertyNameList,
M
Matthias Bolte 已提交
4012
                                       "runtime.memory") < 0 ||
4013 4014
        esxVI_LookupObjectContentByType(priv->primary,
                                        priv->primary->computeResource->resourcePool,
4015
                                        "ResourcePool", propertyNameList,
4016 4017
                                        &resourcePool,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4018
        goto cleanup;
M
Matthias Bolte 已提交
4019 4020
    }

4021
    for (dynamicProperty = resourcePool->propSet; dynamicProperty;
M
Matthias Bolte 已提交
4022 4023 4024
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.memory")) {
            if (esxVI_ResourcePoolResourceUsage_CastFromAnyType
4025
                  (dynamicProperty->val, &resourcePoolResourceUsage) < 0) {
M
Matthias Bolte 已提交
4026
                goto cleanup;
M
Matthias Bolte 已提交
4027 4028 4029 4030 4031 4032 4033 4034
            }

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

4035
    if (!resourcePoolResourceUsage) {
4036 4037
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not retrieve memory usage of resource pool"));
M
Matthias Bolte 已提交
4038
        goto cleanup;
M
Matthias Bolte 已提交
4039 4040 4041 4042
    }

    result = resourcePoolResourceUsage->unreservedForVm->value;

4043
 cleanup:
M
Matthias Bolte 已提交
4044 4045 4046 4047 4048 4049 4050 4051 4052
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&resourcePool);
    esxVI_ResourcePoolResourceUsage_Free(&resourcePoolResourceUsage);

    return result;
}



4053
static int
4054
esxConnectIsEncrypted(virConnectPtr conn)
4055
{
M
Matthias Bolte 已提交
4056
    esxPrivate *priv = conn->privateData;
4057

4058
    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
4059 4060 4061 4062 4063 4064 4065 4066 4067
        return 1;
    } else {
        return 0;
    }
}



static int
4068
esxConnectIsSecure(virConnectPtr conn)
4069
{
M
Matthias Bolte 已提交
4070
    esxPrivate *priv = conn->privateData;
4071

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



4081
static int
4082
esxConnectIsAlive(virConnectPtr conn)
4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097
{
    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;
}



4098 4099 4100
static int
esxDomainIsActive(virDomainPtr domain)
{
M
Matthias Bolte 已提交
4101
    int result = -1;
M
Matthias Bolte 已提交
4102
    esxPrivate *priv = domain->conn->privateData;
4103 4104 4105 4106
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

4107
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4108
        return -1;
4109 4110
    }

4111
    if (esxVI_String_AppendValueToList(&propertyNameList,
4112
                                       "runtime.powerState") < 0 ||
4113
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
4114
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
4115
                                         esxVI_Occurrence_RequiredItem) < 0 ||
4116
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
4117
        goto cleanup;
4118 4119 4120 4121 4122 4123 4124 4125
    }

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

4126
 cleanup:
4127 4128 4129 4130 4131 4132 4133 4134 4135
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
4136
esxDomainIsPersistent(virDomainPtr domain)
4137
{
4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153
    /* 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;

4154
 cleanup:
4155 4156 4157
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
4158 4159
}

M
Matthias Bolte 已提交
4160 4161


4162 4163 4164
static int
esxDomainIsUpdated(virDomainPtr domain ATTRIBUTE_UNUSED)
{
4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180
    /* 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;

4181
 cleanup:
4182 4183 4184
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
4185
}
4186

M
Matthias Bolte 已提交
4187 4188


4189 4190
static virDomainSnapshotPtr
esxDomainSnapshotCreateXML(virDomainPtr domain, const char *xmlDesc,
4191
                           unsigned int flags)
4192 4193 4194 4195 4196 4197 4198 4199
{
    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;
4200
    char *taskInfoErrorMessage = NULL;
4201
    virDomainSnapshotPtr snapshot = NULL;
4202 4203
    bool diskOnly = (flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY) != 0;
    bool quiesce = (flags & VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE) != 0;
4204

4205 4206 4207 4208 4209
    /* 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);
4210

4211
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4212
        return NULL;
4213 4214
    }

4215
    def = virDomainSnapshotDefParseString(xmlDesc, priv->caps,
4216
                                          priv->xmlopt, 0, 0);
4217

4218
    if (!def) {
M
Matthias Bolte 已提交
4219
        return NULL;
4220 4221
    }

4222
    if (def->ndisks) {
4223 4224
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("disk snapshots not supported yet"));
4225 4226 4227
        return NULL;
    }

4228
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
4229
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4230
           priv->parsedUri->autoAnswer) < 0 ||
4231
        esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4232 4233
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, def->name,
4234
                                    &snapshotTree, NULL,
4235
                                    esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4236
        goto cleanup;
4237 4238
    }

4239
    if (snapshotTree) {
4240 4241
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Snapshot '%s' already exists"), def->name);
M
Matthias Bolte 已提交
4242
        goto cleanup;
4243 4244
    }

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

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4258 4259
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not create snapshot: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4260
        goto cleanup;
4261 4262 4263 4264
    }

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

4265
 cleanup:
4266 4267 4268 4269
    virDomainSnapshotDefFree(def);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4270
    VIR_FREE(taskInfoErrorMessage);
4271 4272 4273 4274 4275 4276 4277

    return snapshot;
}



static char *
4278 4279
esxDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                            unsigned int flags)
4280 4281 4282 4283 4284 4285 4286 4287 4288
{
    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;

4289 4290
    virCheckFlags(0, NULL);

4291
    memset(&def, 0, sizeof(def));
4292

4293
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4294
        return NULL;
4295 4296
    }

4297
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4298 4299 4300 4301
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4302
        goto cleanup;
4303 4304 4305 4306
    }

    def.name = snapshot->name;
    def.description = snapshotTree->description;
4307
    def.parent = snapshotTreeParent ? snapshotTreeParent->name : NULL;
4308 4309 4310

    if (esxVI_DateTime_ConvertToCalendarTime(snapshotTree->createTime,
                                             &def.creationTime) < 0) {
M
Matthias Bolte 已提交
4311
        goto cleanup;
4312 4313 4314 4315 4316 4317 4318
    }

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

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

4319
    xml = virDomainSnapshotDefFormat(uuid_string, &def, flags, 0);
4320

4321
 cleanup:
4322 4323 4324 4325 4326 4327 4328 4329
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return xml;
}



static int
4330
esxDomainSnapshotNum(virDomainPtr domain, unsigned int flags)
4331
{
M
Matthias Bolte 已提交
4332
    int count;
4333 4334
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
4335
    bool recurse;
4336
    bool leaves;
4337

4338
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
4339 4340
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4341 4342

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) == 0;
4343
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4344

4345
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4346
        return -1;
4347 4348
    }

4349 4350 4351 4352
    /* ESX snapshots do not require libvirt to maintain any metadata.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA)
        return 0;

4353
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4354
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4355
        return -1;
4356 4357
    }

4358 4359
    count = esxVI_GetNumberOfSnapshotTrees(rootSnapshotTreeList, recurse,
                                           leaves);
4360 4361 4362

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

M
Matthias Bolte 已提交
4363
    return count;
4364 4365 4366 4367 4368 4369
}



static int
esxDomainSnapshotListNames(virDomainPtr domain, char **names, int nameslen,
4370
                           unsigned int flags)
4371
{
M
Matthias Bolte 已提交
4372
    int result;
4373 4374
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
4375
    bool recurse;
4376
    bool leaves;
4377 4378

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
4379 4380
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4381

4382
    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) == 0;
4383
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4384

4385
    if (!names || nameslen < 0) {
4386
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
4387 4388 4389
        return -1;
    }

4390
    if (nameslen == 0 || (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA)) {
4391 4392 4393
        return 0;
    }

4394
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4395
        return -1;
4396 4397
    }

4398
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4399
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4400
        return -1;
4401 4402
    }

4403
    result = esxVI_GetSnapshotTreeNames(rootSnapshotTreeList, names, nameslen,
4404
                                        recurse, leaves);
4405 4406 4407 4408 4409 4410 4411 4412

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



4413 4414 4415 4416 4417 4418 4419 4420
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;
4421
    bool leaves;
4422 4423

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
4424 4425
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4426 4427

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) != 0;
4428
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448

    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,
4449
                                           recurse, leaves);
4450

4451
 cleanup:
4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468
    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;
4469
    bool leaves;
4470 4471

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
4472 4473
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4474 4475

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) != 0;
4476
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4477

4478
    if (!names || nameslen < 0) {
4479
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505
        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,
4506
                                        names, nameslen, recurse, leaves);
4507

4508
 cleanup:
4509 4510 4511 4512 4513 4514 4515
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



4516 4517
static virDomainSnapshotPtr
esxDomainSnapshotLookupByName(virDomainPtr domain, const char *name,
4518
                              unsigned int flags)
4519 4520 4521 4522 4523 4524
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    virDomainSnapshotPtr snapshot = NULL;

4525 4526
    virCheckFlags(0, NULL);

4527
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4528
        return NULL;
4529 4530
    }

4531
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4532 4533
                                         &rootSnapshotTreeList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotTreeList, name, &snapshotTree,
4534
                                    NULL,
4535 4536 4537 4538 4539 4540
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    snapshot = virGetDomainSnapshot(domain, name);

4541
 cleanup:
4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return snapshot;
}



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

4555
    virCheckFlags(0, -1);
4556

4557
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4558
        return -1;
4559 4560
    }

4561
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4562 4563
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4564
        return -1;
4565 4566
    }

4567
    if (currentSnapshotTree) {
M
Matthias Bolte 已提交
4568 4569
        esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);
        return 1;
4570 4571
    }

M
Matthias Bolte 已提交
4572
    return 0;
4573 4574 4575 4576
}



E
Eric Blake 已提交
4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600
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) {
4601 4602 4603
        virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                       _("snapshot '%s' does not have a parent"),
                       snapshotTree->name);
E
Eric Blake 已提交
4604 4605 4606 4607 4608
        goto cleanup;
    }

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

4609
 cleanup:
E
Eric Blake 已提交
4610 4611 4612 4613 4614 4615 4616
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return parent;
}



4617 4618 4619 4620 4621
static virDomainSnapshotPtr
esxDomainSnapshotCurrent(virDomainPtr domain, unsigned int flags)
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *currentSnapshotTree = NULL;
M
Matthias Bolte 已提交
4622
    virDomainSnapshotPtr snapshot = NULL;
4623

4624
    virCheckFlags(0, NULL);
4625

4626
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4627
        return NULL;
4628 4629
    }

4630
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4631 4632
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4633
        return NULL;
4634 4635 4636 4637 4638 4639 4640 4641 4642 4643
    }

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

    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return snapshot;
}


4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675
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);

4676
 cleanup:
4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707
    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;

4708
 cleanup:
4709 4710 4711 4712
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    return ret;
}

4713 4714 4715 4716

static int
esxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4717
    int result = -1;
4718 4719 4720 4721 4722
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
4723
    char *taskInfoErrorMessage = NULL;
4724

4725
    virCheckFlags(0, -1);
4726

4727
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4728
        return -1;
4729 4730
    }

4731
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4732 4733
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
4734
                                    &snapshotTree, NULL,
4735
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4736
        goto cleanup;
4737 4738
    }

4739
    if (esxVI_RevertToSnapshot_Task(priv->primary, snapshotTree->snapshot, NULL,
4740
                                    esxVI_Boolean_Undefined, &task) < 0 ||
4741
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4742
                                    esxVI_Occurrence_RequiredItem,
4743
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4744
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4745
        goto cleanup;
4746 4747 4748
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4749 4750 4751
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not revert to snapshot '%s': %s"), snapshot->name,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4752
        goto cleanup;
4753 4754
    }

M
Matthias Bolte 已提交
4755 4756
    result = 0;

4757
 cleanup:
4758 4759
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4760
    VIR_FREE(taskInfoErrorMessage);
4761 4762 4763 4764 4765 4766 4767 4768 4769

    return result;
}



static int
esxDomainSnapshotDelete(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4770
    int result = -1;
4771 4772 4773 4774 4775 4776
    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;
4777
    char *taskInfoErrorMessage = NULL;
4778

4779 4780
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
                  VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY, -1);
4781

4782
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4783
        return -1;
4784 4785 4786 4787 4788 4789
    }

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

4790
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4791 4792
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
4793
                                    &snapshotTree, NULL,
4794
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4795
        goto cleanup;
4796 4797
    }

4798 4799 4800 4801 4802 4803 4804
    /* 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;
    }

4805
    if (esxVI_RemoveSnapshot_Task(priv->primary, snapshotTree->snapshot,
4806
                                  removeChildren, &task) < 0 ||
4807
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4808
                                    esxVI_Occurrence_RequiredItem,
4809
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4810
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4811
        goto cleanup;
4812 4813 4814
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4815 4816 4817
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not delete snapshot '%s': %s"), snapshot->name,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4818
        goto cleanup;
4819 4820
    }

M
Matthias Bolte 已提交
4821 4822
    result = 0;

4823
 cleanup:
4824 4825
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4826
    VIR_FREE(taskInfoErrorMessage);
4827 4828 4829 4830 4831 4832

    return result;
}



4833
static int
4834
esxDomainSetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
4835 4836 4837 4838 4839 4840 4841 4842
                             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;
4843
    char *taskInfoErrorMessage = NULL;
4844
    size_t i;
4845 4846

    virCheckFlags(0, -1);
4847 4848 4849 4850
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_MEMORY_MIN_GUARANTEE,
                               VIR_TYPED_PARAM_ULLONG,
                               NULL) < 0)
4851
        return -1;
4852 4853 4854 4855 4856 4857 4858

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

    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4859
           priv->parsedUri->autoAnswer) < 0 ||
4860 4861 4862 4863 4864 4865
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0) {
        goto cleanup;
    }

    for (i = 0; i < nparams; ++i) {
4866
        if (STREQ(params[i].field, VIR_DOMAIN_MEMORY_MIN_GUARANTEE)) {
4867 4868 4869 4870 4871
            if (esxVI_Long_Alloc(&spec->memoryAllocation->reservation) < 0) {
                goto cleanup;
            }

            spec->memoryAllocation->reservation->value =
4872
              VIR_DIV_UP(params[i].value.ul, 1024); /* Scale from kilobytes to megabytes */
4873 4874 4875 4876 4877 4878 4879
        }
    }

    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
4880
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4881
                                    &taskInfoErrorMessage) < 0) {
4882 4883 4884 4885
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4886 4887 4888
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not change memory parameters: %s"),
                       taskInfoErrorMessage);
4889 4890 4891 4892 4893
        goto cleanup;
    }

    result = 0;

4894
 cleanup:
4895 4896 4897
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
4898
    VIR_FREE(taskInfoErrorMessage);
4899 4900 4901 4902 4903 4904 4905

    return result;
}



static int
4906
esxDomainGetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935
                             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;
    }

4936 4937 4938 4939
    /* Scale from megabytes to kilobytes */
    if (virTypedParameterAssign(params, VIR_DOMAIN_MEMORY_MIN_GUARANTEE,
                                VIR_TYPED_PARAM_ULLONG,
                                reservation->value * 1024) < 0)
4940 4941 4942 4943 4944
        goto cleanup;

    *nparams = 1;
    result = 0;

4945
 cleanup:
4946 4947 4948 4949 4950 4951 4952
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Long_Free(&reservation);

    return result;
}

4953 4954
#define MATCH(FLAG) (flags & (FLAG))
static int
4955 4956 4957
esxConnectListAllDomains(virConnectPtr conn,
                         virDomainPtr **domains,
                         unsigned int flags)
4958 4959 4960
{
    int ret = -1;
    esxPrivate *priv = conn->privateData;
4961 4962
    bool needIdentity;
    bool needPowerState;
4963 4964 4965
    virDomainPtr dom;
    virDomainPtr *doms = NULL;
    size_t ndoms = 0;
4966
    esxVI_String *propertyNameList = NULL;
4967 4968
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
4969
    esxVI_AutoStartDefaults *autoStartDefaults = NULL;
4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986
    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
     */
4987
    if ((MATCH(VIR_CONNECT_LIST_DOMAINS_TRANSIENT) &&
4988 4989 4990 4991 4992
         !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)
4993
            goto cleanup;
4994 4995 4996 4997 4998

        ret = 0;
        goto cleanup;
    }

4999
    if (esxVI_EnsureSession(priv->primary) < 0)
5000 5001 5002 5003 5004
        return -1;

    /* check system default autostart value */
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_AUTOSTART)) {
        if (esxVI_LookupAutoStartDefaults(priv->primary,
5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017
                                          &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) ||
5018
                   domains;
5019 5020 5021 5022 5023 5024 5025

    if (needIdentity) {
        /* Request required data for esxVI_GetVirtualMachineIdentity */
        if (esxVI_String_AppendValueListToList(&propertyNameList,
                                               "configStatus\0"
                                               "name\0"
                                               "config.uuid\0") < 0) {
5026
            goto cleanup;
5027 5028 5029 5030 5031
        }
    }

    needPowerState = MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_ACTIVE) ||
                     MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_STATE) ||
5032
                     domains;
5033

5034 5035 5036
    if (needPowerState) {
        if (esxVI_String_AppendValueToList(&propertyNameList,
                                           "runtime.powerState") < 0) {
5037
            goto cleanup;
5038
        }
5039 5040
    }

5041
    if (esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
5042 5043 5044 5045 5046
                                       &virtualMachineList) < 0)
        goto cleanup;

    if (domains) {
        if (VIR_ALLOC_N(doms, 1) < 0)
5047
            goto cleanup;
5048 5049 5050
        ndoms = 1;
    }

5051
    for (virtualMachine = virtualMachineList; virtualMachine;
5052
         virtualMachine = virtualMachine->_next) {
5053 5054
        if (needIdentity) {
            VIR_FREE(name);
5055

5056 5057 5058 5059 5060
            if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id,
                                                &name, uuid) < 0) {
                goto cleanup;
            }
        }
5061

5062 5063 5064 5065 5066 5067
        if (needPowerState) {
            if (esxVI_GetVirtualMachinePowerState(virtualMachine,
                                                  &powerState) < 0) {
                goto cleanup;
            }
        }
5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078

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

5081 5082 5083 5084 5085 5086
            if (esxVI_LookupRootSnapshotTreeList(priv->primary, uuid,
                                                 &rootSnapshotTreeList) < 0) {
                goto cleanup;
            }

            if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT) &&
5087
                   rootSnapshotTreeList) ||
5088
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT) &&
5089
                   !rootSnapshotTreeList)))
5090 5091 5092 5093 5094 5095 5096
                continue;
        }

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

5097
            if (autoStartDefaults->enabled == esxVI_Boolean_True) {
5098
                for (powerInfo = powerInfoList; powerInfo;
5099 5100 5101 5102
                     powerInfo = powerInfo->_next) {
                    if (STREQ(powerInfo->key->value, virtualMachine->obj->value)) {
                        if (STRCASEEQ(powerInfo->startAction, "powerOn"))
                            autostart = true;
5103

5104 5105
                        break;
                    }
5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118
                }
            }

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

5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138
            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;
        }

5139
        if (VIR_RESIZE_N(doms, ndoms, count, 2) < 0)
5140
            goto cleanup;
5141

5142 5143 5144
        if (!(dom = virGetDomain(conn, name, uuid)))
            goto cleanup;

5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158
        /* 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;

5159
 cleanup:
5160 5161
    if (doms) {
        for (id = 0; id < count; id++) {
5162
            virDomainFree(doms[id]);
5163
        }
5164 5165

        VIR_FREE(doms);
5166
    }
5167

5168
    VIR_FREE(name);
5169 5170
    esxVI_AutoStartDefaults_Free(&autoStartDefaults);
    esxVI_AutoStartPowerInfo_Free(&powerInfoList);
5171 5172
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
5173 5174
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

5175 5176 5177
    return ret;
}
#undef MATCH
5178 5179


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



int
esxRegister(void)
{
5264 5265 5266 5267 5268
    if (virRegisterDriver(&esxDriver) < 0 ||
        esxInterfaceRegister() < 0 ||
        esxNetworkRegister() < 0 ||
        esxStorageRegister() < 0 ||
        esxDeviceRegister() < 0 ||
M
Matthias Bolte 已提交
5269 5270
        esxSecretRegister() < 0 ||
        esxNWFilterRegister() < 0) {
5271 5272
        return -1;
    }
5273 5274 5275

    return 0;
}