esx_driver.c 172.0 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-2014 Matthias Bolte <matthias.bolte@googlemail.com>
6 7 8 9 10 11 12 13 14 15 16 17 18
 * Copyright (C) 2009 Maximilian Wilhelm <max@rfc2324.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
19
 * License along with this library.  If not, see
O
Osier Yang 已提交
20
 * <http://www.gnu.org/licenses/>.
21 22 23 24 25 26 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 "esx_stream.h"
48
#include "virstring.h"
49
#include "viruri.h"
50 51 52

#define VIR_FROM_THIS VIR_FROM_ESX

53 54
VIR_LOG_INIT("esx.esx_driver");

55 56
static int esxDomainGetMaxVcpus(virDomainPtr domain);

57 58 59 60
typedef struct _esxVMX_Data esxVMX_Data;

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



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

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



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

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

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

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

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

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

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

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

190
            tmp = strippedFileName;
191

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

198 199
                ++tmp;
            }
200

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

205 206
            break;
        }
207

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

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

224
            esxVI_ObjectContent_Free(&datastoreList);
225

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

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

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

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

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

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

266
    return result;
267 268 269 270
}



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

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

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

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

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

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

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

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

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

337 338
                ++tmp;
            }
339
        }
340

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

344
        if (virBufferCheckError(&buffer) < 0)
345 346 347 348 349
            goto cleanup;

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

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

    success = true;

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

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

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



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

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

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

406
    vmDiskFileInfo = esxVI_VmDiskFileInfo_DynamicCast(fileInfo);
407

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

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

    result = 0;

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

    return result;
}

441 442


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

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

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

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

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

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

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

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

                    break;
                }
            }

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

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

    return priv->supportsLongMode;
}



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

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

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

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

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

    result = 0;

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

    return result;
}


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

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

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

584
    if (!caps)
585 586
        return NULL;

587
    virCapabilitiesAddHostMigrateTransport(caps, "vpxmigr");
588

589

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

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

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

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

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

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

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

624 625
    return caps;

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

    return NULL;
}



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

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

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

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

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

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

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

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

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

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

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

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

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

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

    result = 0;

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

    return result;
}



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

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

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

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

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

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

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

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

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

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

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

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

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

843 844
    result = 0;

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

    return result;
}



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

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

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

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

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

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

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

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

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

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

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

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

M
Matthias Bolte 已提交
975 976 977 978 979 980 981
    /*
     * Set the port dependent on the transport protocol if no port is
     * specified. This allows us to rely on the port parameter being
     * correctly set when building URIs later on, without the need to
     * distinguish between the situations port == 0 and port != 0
     */
    if (conn->uri->port == 0) {
982 983
        if (STRCASEEQ(conn->uri->scheme, "vpx") ||
            STRCASEEQ(conn->uri->scheme, "esx")) {
984
            if (STRCASEEQ(priv->parsedUri->transport, "https")) {
M
Matthias Bolte 已提交
985 986 987 988 989
                conn->uri->port = 443;
            } else {
                conn->uri->port = 80;
            }
        } else { /* GSX */
990
            if (STRCASEEQ(priv->parsedUri->transport, "https")) {
M
Matthias Bolte 已提交
991 992 993 994
                conn->uri->port = 8333;
            } else {
                conn->uri->port = 8222;
            }
995
        }
M
Matthias Bolte 已提交
996
    }
997

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

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

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

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

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

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

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

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

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

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

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

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

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



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

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

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

1102
    esxFreePrivate(&priv);
1103 1104 1105

    conn->privateData = NULL;

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



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

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

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

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

1135
 cleanup:
M
Matthias Bolte 已提交
1136 1137 1138 1139
    /*
     * If we goto cleanup in case of an error then priv->supportsVMotion is
     * still esxVI_Boolean_Undefined, therefore we don't need to set it.
     */
1140 1141 1142
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

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



1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
static esxVI_Boolean
esxSupportsScreenshot(esxPrivate *priv)
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;

    if (priv->supportsScreenshot != esxVI_Boolean_Undefined)
        return priv->supportsScreenshot;

    if (esxVI_EnsureSession(priv->primary) < 0)
        return esxVI_Boolean_Undefined;

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "capability.screenshotSupported") < 0 ||
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0 ||
        esxVI_GetBoolean(hostSystem, "capability.screenshotSupported",
                         &priv->supportsScreenshot,
                         esxVI_Occurrence_RequiredItem) < 0)
        goto cleanup;

 cleanup:
    /*
     * If we goto cleanup in case of an error then priv->supportsScreenshot is
     * still esxVI_Boolean_Undefined, therefore we don't need to set it.
     */
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return priv->supportsScreenshot;
}



1182
static int
1183
esxConnectSupportsFeature(virConnectPtr conn, int feature)
1184
{
M
Matthias Bolte 已提交
1185
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1186
    esxVI_Boolean supportsVMotion = esxVI_Boolean_Undefined;
1187 1188 1189

    switch (feature) {
      case VIR_DRV_FEATURE_MIGRATION_V1:
1190
        supportsVMotion = esxSupportsVMotion(priv);
1191

M
Matthias Bolte 已提交
1192
        if (supportsVMotion == esxVI_Boolean_Undefined) {
1193 1194 1195
            return -1;
        }

M
Matthias Bolte 已提交
1196
        /* Migration is only possible via a vCenter and if VMotion is enabled */
1197
        return priv->vCenter &&
M
Matthias Bolte 已提交
1198
               supportsVMotion == esxVI_Boolean_True ? 1 : 0;
1199 1200 1201 1202 1203 1204 1205 1206 1207

      default:
        return 0;
    }
}



static const char *
1208
esxConnectGetType(virConnectPtr conn ATTRIBUTE_UNUSED)
1209 1210 1211 1212 1213 1214 1215
{
    return "ESX";
}



static int
1216
esxConnectGetVersion(virConnectPtr conn, unsigned long *version)
1217
{
M
Matthias Bolte 已提交
1218
    esxPrivate *priv = conn->privateData;
1219

1220
    if (virParseVersionString(priv->primary->service->about->version,
1221
                              version, false) < 0) {
1222 1223 1224
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not parse version number from '%s'"),
                       priv->primary->service->about->version);
1225

1226
        return -1;
1227 1228 1229 1230 1231 1232 1233 1234
    }

    return 0;
}



static char *
1235
esxConnectGetHostname(virConnectPtr conn)
1236
{
M
Matthias Bolte 已提交
1237
    esxPrivate *priv = conn->privateData;
1238 1239 1240 1241 1242 1243 1244
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    const char *hostName = NULL;
    const char *domainName = NULL;
    char *complete = NULL;

1245
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1246
        return NULL;
1247 1248 1249
    }

    if (esxVI_String_AppendValueListToList
1250
          (&propertyNameList,
1251 1252
           "config.network.dnsConfig.hostName\0"
           "config.network.dnsConfig.domainName\0") < 0 ||
1253 1254
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1255
        goto cleanup;
1256 1257
    }

1258
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
1259 1260 1261
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name,
                  "config.network.dnsConfig.hostName")) {
1262
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1263
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1264
                goto cleanup;
1265 1266 1267 1268 1269
            }

            hostName = dynamicProperty->val->string;
        } else if (STREQ(dynamicProperty->name,
                         "config.network.dnsConfig.domainName")) {
1270
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1271
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1272
                goto cleanup;
1273 1274 1275 1276 1277 1278 1279 1280
            }

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

1281
    if (!hostName || strlen(hostName) < 1) {
1282 1283
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing or empty 'hostName' property"));
M
Matthias Bolte 已提交
1284
        goto cleanup;
1285 1286
    }

1287
    if (!domainName || strlen(domainName) < 1) {
1288
        if (VIR_STRDUP(complete, hostName) < 0)
M
Matthias Bolte 已提交
1289
            goto cleanup;
1290
    } else {
1291
        if (virAsprintf(&complete, "%s.%s", hostName, domainName) < 0)
M
Matthias Bolte 已提交
1292
            goto cleanup;
1293 1294
    }

1295
 cleanup:
M
Matthias Bolte 已提交
1296 1297
    /*
     * If we goto cleanup in case of an error then complete is still NULL,
1298
     * either VIR_STRDUP returned -1 or virAsprintf failed. When virAsprintf
M
Matthias Bolte 已提交
1299 1300
     * fails it guarantees setting complete to NULL
     */
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return complete;
}



static int
esxNodeGetInfo(virConnectPtr conn, virNodeInfoPtr nodeinfo)
{
M
Matthias Bolte 已提交
1312
    int result = -1;
M
Matthias Bolte 已提交
1313
    esxPrivate *priv = conn->privateData;
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
    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;

1325
    memset(nodeinfo, 0, sizeof(*nodeinfo));
1326

1327
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1328
        return -1;
1329 1330
    }

1331
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1332 1333 1334 1335 1336 1337 1338
                                           "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 ||
1339 1340
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1341
        goto cleanup;
1342 1343
    }

1344
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
1345 1346
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuInfo.hz")) {
1347
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1348
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1349
                goto cleanup;
1350 1351 1352 1353 1354
            }

            cpuInfo_hz = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuCores")) {
1355
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1356
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1357
                goto cleanup;
1358 1359 1360 1361 1362
            }

            cpuInfo_numCpuCores = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuPackages")) {
1363
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1364
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1365
                goto cleanup;
1366 1367 1368 1369 1370
            }

            cpuInfo_numCpuPackages = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuThreads")) {
1371
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1372
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1373
                goto cleanup;
1374 1375 1376 1377
            }

            cpuInfo_numCpuThreads = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name, "hardware.memorySize")) {
1378
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1379
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1380
                goto cleanup;
1381 1382 1383 1384 1385
            }

            memorySize = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.numaInfo.numNodes")) {
1386
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1387
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1388
                goto cleanup;
1389 1390 1391 1392 1393
            }

            numaInfo_numNodes = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "summary.hardware.cpuModel")) {
1394
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1395
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1396
                goto cleanup;
1397 1398 1399 1400 1401 1402
            }

            ptr = dynamicProperty->val->string;

            /* Strip the string to fit more relevant information in 32 chars */
            while (*ptr != '\0') {
M
Matthias Bolte 已提交
1403 1404
                if (STRPREFIX(ptr, "  ")) {
                    memmove(ptr, ptr + 1, strlen(ptr + 1) + 1);
1405
                    continue;
1406
                } else if (STRPREFIX(ptr, "(R)") || STRPREFIX(ptr, "(C)")) {
M
Matthias Bolte 已提交
1407
                    memmove(ptr, ptr + 3, strlen(ptr + 3) + 1);
1408
                    continue;
1409 1410 1411
                } else if (STRPREFIX(ptr, "(TM)")) {
                    memmove(ptr, ptr + 4, strlen(ptr + 4) + 1);
                    continue;
1412 1413 1414 1415 1416
                }

                ++ptr;
            }

1417 1418 1419
            if (!virStrncpy(nodeinfo->model, dynamicProperty->val->string,
                            sizeof(nodeinfo->model) - 1,
                            sizeof(nodeinfo->model))) {
1420 1421 1422
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("CPU Model %s too long for destination"),
                               dynamicProperty->val->string);
M
Matthias Bolte 已提交
1423
                goto cleanup;
C
Chris Lalancette 已提交
1424
            }
1425 1426 1427 1428 1429 1430 1431
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    nodeinfo->memory = memorySize / 1024; /* Scale from bytes to kilobytes */
    nodeinfo->cpus = cpuInfo_numCpuCores;
1432
    nodeinfo->mhz = cpuInfo_hz / (1000 * 1000); /* Scale from hz to mhz */
1433 1434 1435 1436 1437 1438 1439 1440 1441
    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 已提交
1442 1443
    result = 0;

1444
 cleanup:
1445 1446 1447 1448 1449 1450 1451 1452
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



1453
static char *
1454
esxConnectGetCapabilities(virConnectPtr conn)
1455
{
M
Matthias Bolte 已提交
1456
    esxPrivate *priv = conn->privateData;
1457

1458
    return virCapabilitiesFormatXML(priv->caps);
1459 1460 1461 1462
}



1463
static int
1464
esxConnectListDomains(virConnectPtr conn, int *ids, int maxids)
1465
{
M
Matthias Bolte 已提交
1466
    bool success = false;
M
Matthias Bolte 已提交
1467
    esxPrivate *priv = conn->privateData;
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;

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

1478
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1479
        return -1;
1480 1481
    }

1482
    if (esxVI_String_AppendValueToList(&propertyNameList,
1483
                                       "runtime.powerState") < 0 ||
1484 1485
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1486
        goto cleanup;
1487 1488
    }

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

        if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

        if (esxUtil_ParseVirtualMachineIDString(virtualMachine->obj->value,
                                                &ids[count]) < 0 ||
            ids[count] <= 0) {
1503 1504 1505
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to parse positive integer from '%s'"),
                           virtualMachine->obj->value);
M
Matthias Bolte 已提交
1506
            goto cleanup;
1507 1508 1509 1510 1511 1512 1513 1514 1515
        }

        count++;

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

M
Matthias Bolte 已提交
1516 1517
    success = true;

1518
 cleanup:
1519 1520 1521
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
1522
    return success ? count : -1;
1523 1524 1525 1526 1527
}



static int
1528
esxConnectNumOfDomains(virConnectPtr conn)
1529
{
M
Matthias Bolte 已提交
1530
    esxPrivate *priv = conn->privateData;
1531

1532
    if (esxVI_EnsureSession(priv->primary) < 0) {
1533 1534 1535
        return -1;
    }

1536
    return esxVI_LookupNumberOfDomainsByPowerState
1537
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, false);
1538 1539 1540 1541 1542 1543 1544
}



static virDomainPtr
esxDomainLookupByID(virConnectPtr conn, int id)
{
M
Matthias Bolte 已提交
1545
    esxPrivate *priv = conn->privateData;
1546 1547 1548 1549
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
M
Matthias Bolte 已提交
1550 1551 1552
    int id_candidate = -1;
    char *name_candidate = NULL;
    unsigned char uuid_candidate[VIR_UUID_BUFLEN];
1553 1554
    virDomainPtr domain = NULL;

1555
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1556
        return NULL;
1557 1558
    }

1559
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1560
                                           "configStatus\0"
1561 1562
                                           "name\0"
                                           "runtime.powerState\0"
1563
                                           "config.uuid\0") < 0 ||
1564 1565
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1566
        goto cleanup;
1567 1568
    }

1569
    for (virtualMachine = virtualMachineList; virtualMachine;
1570
         virtualMachine = virtualMachine->_next) {
1571
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1572
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1573
            goto cleanup;
1574 1575 1576 1577 1578 1579 1580
        }

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

M
Matthias Bolte 已提交
1581
        VIR_FREE(name_candidate);
1582

1583
        if (esxVI_GetVirtualMachineIdentity(virtualMachine,
M
Matthias Bolte 已提交
1584 1585
                                            &id_candidate, &name_candidate,
                                            uuid_candidate) < 0) {
M
Matthias Bolte 已提交
1586
            goto cleanup;
1587 1588
        }

M
Matthias Bolte 已提交
1589
        if (id != id_candidate) {
1590 1591 1592
            continue;
        }

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

1595
        if (!domain) {
M
Matthias Bolte 已提交
1596
            goto cleanup;
1597 1598 1599 1600 1601 1602 1603
        }

        domain->id = id;

        break;
    }

1604
    if (!domain) {
1605
        virReportError(VIR_ERR_NO_DOMAIN, _("No domain with ID %d"), id);
1606 1607
    }

1608
 cleanup:
1609 1610
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
M
Matthias Bolte 已提交
1611
    VIR_FREE(name_candidate);
1612 1613 1614 1615 1616 1617 1618 1619 1620

    return domain;
}



static virDomainPtr
esxDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
M
Matthias Bolte 已提交
1621
    esxPrivate *priv = conn->privateData;
1622 1623 1624
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1625 1626
    int id = -1;
    char *name = NULL;
1627 1628
    virDomainPtr domain = NULL;

1629
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1630
        return NULL;
1631 1632
    }

1633
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1634
                                           "name\0"
1635
                                           "runtime.powerState\0") < 0 ||
1636
        esxVI_LookupVirtualMachineByUuid(priv->primary, uuid, propertyNameList,
1637
                                         &virtualMachine,
M
Matthias Bolte 已提交
1638
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1639 1640
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, &name, NULL) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1641
        goto cleanup;
1642 1643
    }

1644
    domain = virGetDomain(conn, name, uuid);
1645

1646
    if (!domain) {
M
Matthias Bolte 已提交
1647
        goto cleanup;
1648
    }
1649

1650 1651 1652 1653 1654
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1655 1656
    }

1657
 cleanup:
1658
    esxVI_String_Free(&propertyNameList);
1659 1660
    esxVI_ObjectContent_Free(&virtualMachine);
    VIR_FREE(name);
1661 1662 1663 1664 1665 1666 1667 1668 1669

    return domain;
}



static virDomainPtr
esxDomainLookupByName(virConnectPtr conn, const char *name)
{
M
Matthias Bolte 已提交
1670
    esxPrivate *priv = conn->privateData;
1671 1672 1673
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1674 1675
    int id = -1;
    unsigned char uuid[VIR_UUID_BUFLEN];
1676 1677
    virDomainPtr domain = NULL;

1678
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1679
        return NULL;
1680 1681
    }

1682
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1683
                                           "configStatus\0"
1684
                                           "runtime.powerState\0"
1685
                                           "config.uuid\0") < 0 ||
1686
        esxVI_LookupVirtualMachineByName(priv->primary, name, propertyNameList,
1687 1688
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
1689
        goto cleanup;
1690 1691
    }

1692
    if (!virtualMachine) {
1693
        virReportError(VIR_ERR_NO_DOMAIN, _("No domain with name '%s'"), name);
M
Matthias Bolte 已提交
1694
        goto cleanup;
1695
    }
1696

M
Matthias Bolte 已提交
1697 1698 1699
    if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, uuid) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
1700
    }
1701

1702
    domain = virGetDomain(conn, name, uuid);
1703

1704
    if (!domain) {
M
Matthias Bolte 已提交
1705
        goto cleanup;
1706 1707
    }

1708 1709 1710 1711 1712
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1713 1714
    }

1715
 cleanup:
1716
    esxVI_String_Free(&propertyNameList);
1717
    esxVI_ObjectContent_Free(&virtualMachine);
1718 1719 1720 1721 1722 1723 1724 1725 1726

    return domain;
}



static int
esxDomainSuspend(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1727
    int result = -1;
M
Matthias Bolte 已提交
1728
    esxPrivate *priv = domain->conn->privateData;
1729 1730 1731 1732 1733
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1734
    char *taskInfoErrorMessage = NULL;
1735

1736
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1737
        return -1;
1738 1739
    }

1740
    if (esxVI_String_AppendValueToList(&propertyNameList,
1741
                                       "runtime.powerState") < 0 ||
1742
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1743
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1744
           priv->parsedUri->autoAnswer) < 0 ||
1745
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1746
        goto cleanup;
1747 1748 1749
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1750 1751
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1752
        goto cleanup;
1753 1754
    }

1755 1756
    if (esxVI_SuspendVM_Task(priv->primary, virtualMachine->obj, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1757
                                    esxVI_Occurrence_RequiredItem,
1758
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1759
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1760
        goto cleanup;
1761 1762 1763
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1764 1765
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not suspend domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
1766
        goto cleanup;
1767 1768
    }

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

1771
 cleanup:
1772 1773 1774
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1775
    VIR_FREE(taskInfoErrorMessage);
1776 1777 1778 1779 1780 1781 1782 1783 1784

    return result;
}



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

1794
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1795
        return -1;
1796 1797
    }

1798
    if (esxVI_String_AppendValueToList(&propertyNameList,
1799
                                       "runtime.powerState") < 0 ||
1800
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1801
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1802
           priv->parsedUri->autoAnswer) < 0 ||
1803
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1804
        goto cleanup;
1805 1806 1807
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended) {
1808
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not suspended"));
M
Matthias Bolte 已提交
1809
        goto cleanup;
1810 1811
    }

1812
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
1813
                             &task) < 0 ||
1814
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1815
                                    esxVI_Occurrence_RequiredItem,
1816
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1817
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1818
        goto cleanup;
1819 1820 1821
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1822 1823
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not resume domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
1824
        goto cleanup;
1825 1826
    }

M
Matthias Bolte 已提交
1827 1828
    result = 0;

1829
 cleanup:
1830 1831 1832
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1833
    VIR_FREE(taskInfoErrorMessage);
1834 1835 1836 1837 1838 1839 1840

    return result;
}



static int
1841
esxDomainShutdownFlags(virDomainPtr domain, unsigned int flags)
1842
{
M
Matthias Bolte 已提交
1843
    int result = -1;
M
Matthias Bolte 已提交
1844
    esxPrivate *priv = domain->conn->privateData;
1845 1846 1847 1848
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1849 1850
    virCheckFlags(0, -1);

1851
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1852
        return -1;
1853 1854
    }

1855
    if (esxVI_String_AppendValueToList(&propertyNameList,
1856
                                       "runtime.powerState") < 0 ||
1857
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1858
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1859
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1860
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1861
        goto cleanup;
1862 1863 1864
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1865 1866
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1867
        goto cleanup;
1868 1869
    }

1870
    if (esxVI_ShutdownGuest(priv->primary, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1871
        goto cleanup;
1872 1873
    }

M
Matthias Bolte 已提交
1874 1875
    result = 0;

1876
 cleanup:
1877 1878 1879 1880 1881 1882 1883
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}


1884 1885 1886 1887 1888 1889
static int
esxDomainShutdown(virDomainPtr domain)
{
    return esxDomainShutdownFlags(domain, 0);
}

1890 1891

static int
E
Eric Blake 已提交
1892
esxDomainReboot(virDomainPtr domain, unsigned int flags)
1893
{
M
Matthias Bolte 已提交
1894
    int result = -1;
M
Matthias Bolte 已提交
1895
    esxPrivate *priv = domain->conn->privateData;
1896 1897 1898 1899
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

E
Eric Blake 已提交
1900 1901
    virCheckFlags(0, -1);

1902
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1903
        return -1;
1904 1905
    }

1906
    if (esxVI_String_AppendValueToList(&propertyNameList,
1907
                                       "runtime.powerState") < 0 ||
1908
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1909
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1910
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1911
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1912
        goto cleanup;
1913 1914 1915
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1916 1917
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1918
        goto cleanup;
1919 1920
    }

1921
    if (esxVI_RebootGuest(priv->primary, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1922
        goto cleanup;
1923 1924
    }

M
Matthias Bolte 已提交
1925 1926
    result = 0;

1927
 cleanup:
1928 1929 1930 1931 1932 1933 1934 1935 1936
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
1937 1938
esxDomainDestroyFlags(virDomainPtr domain,
                      unsigned int flags)
1939
{
M
Matthias Bolte 已提交
1940
    int result = -1;
M
Matthias Bolte 已提交
1941
    esxPrivate *priv = domain->conn->privateData;
1942
    esxVI_Context *ctx = NULL;
1943 1944 1945 1946 1947
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1948
    char *taskInfoErrorMessage = NULL;
1949

1950 1951
    virCheckFlags(0, -1);

1952
    if (priv->vCenter) {
1953 1954 1955 1956 1957
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

1958
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
1959
        return -1;
1960 1961
    }

1962
    if (esxVI_String_AppendValueToList(&propertyNameList,
1963
                                       "runtime.powerState") < 0 ||
1964
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1965
          (ctx, domain->uuid, propertyNameList, &virtualMachine,
1966
           priv->parsedUri->autoAnswer) < 0 ||
1967
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1968
        goto cleanup;
1969 1970 1971
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1972 1973
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1974
        goto cleanup;
1975 1976
    }

1977
    if (esxVI_PowerOffVM_Task(ctx, virtualMachine->obj, &task) < 0 ||
1978 1979
        esxVI_WaitForTaskCompletion(ctx, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
1980
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1981
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1982
        goto cleanup;
1983 1984 1985
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1986 1987
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not destroy domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
1988
        goto cleanup;
1989 1990
    }

1991
    domain->id = -1;
M
Matthias Bolte 已提交
1992 1993
    result = 0;

1994
 cleanup:
1995 1996 1997
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1998
    VIR_FREE(taskInfoErrorMessage);
1999 2000 2001 2002 2003

    return result;
}


2004 2005 2006 2007 2008 2009
static int
esxDomainDestroy(virDomainPtr dom)
{
    return esxDomainDestroyFlags(dom, 0);
}

2010 2011

static char *
2012
esxDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED)
2013
{
2014
    char *osType;
2015

2016
    ignore_value(VIR_STRDUP(osType, "hvm"));
2017
    return osType;
2018 2019 2020 2021
}



2022
static unsigned long long
2023 2024
esxDomainGetMaxMemory(virDomainPtr domain)
{
M
Matthias Bolte 已提交
2025
    esxPrivate *priv = domain->conn->privateData;
2026 2027 2028 2029 2030
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    unsigned long memoryMB = 0;

2031
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2032
        return 0;
2033 2034
    }

2035
    if (esxVI_String_AppendValueToList(&propertyNameList,
2036
                                       "config.hardware.memoryMB") < 0 ||
2037
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2038
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2039
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2040
        goto cleanup;
2041 2042
    }

2043
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
2044 2045
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2046
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2047
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2048
                goto cleanup;
2049 2050 2051
            }

            if (dynamicProperty->val->int32 < 0) {
2052 2053 2054
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Got invalid memory size %d"),
                               dynamicProperty->val->int32);
2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
            } else {
                memoryMB = dynamicProperty->val->int32;
            }

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

2065
 cleanup:
2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076
    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 已提交
2077
    int result = -1;
M
Matthias Bolte 已提交
2078
    esxPrivate *priv = domain->conn->privateData;
2079
    esxVI_String *propertyNameList = NULL;
2080
    esxVI_ObjectContent *virtualMachine = NULL;
2081
    esxVI_VirtualMachinePowerState powerState;
2082 2083 2084
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2085
    char *taskInfoErrorMessage = NULL;
2086

2087
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2088
        return -1;
2089 2090
    }

2091 2092 2093 2094
    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "runtime.powerState") < 0 ||
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
2095
           priv->parsedUri->autoAnswer) < 0 ||
2096 2097 2098 2099 2100
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2101 2102
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered off"));
2103 2104 2105 2106
        goto cleanup;
    }

    if (esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
2107
        esxVI_Long_Alloc(&spec->memoryMB) < 0) {
M
Matthias Bolte 已提交
2108
        goto cleanup;
2109 2110
    }

2111
    /* max-memory must be a multiple of 4096 kilobyte */
2112
    spec->memoryMB->value =
2113
      VIR_DIV_UP(memory, 4096) * 4; /* Scale from kilobytes to megabytes */
2114

2115
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2116
                              &task) < 0 ||
2117
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2118
                                    esxVI_Occurrence_RequiredItem,
2119
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2120
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2121
        goto cleanup;
2122 2123 2124
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2125 2126 2127
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set max-memory to %lu kilobytes: %s"), memory,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2128
        goto cleanup;
2129 2130
    }

M
Matthias Bolte 已提交
2131 2132
    result = 0;

2133
 cleanup:
2134
    esxVI_String_Free(&propertyNameList);
2135 2136 2137
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2138
    VIR_FREE(taskInfoErrorMessage);
2139 2140 2141 2142 2143 2144 2145 2146 2147

    return result;
}



static int
esxDomainSetMemory(virDomainPtr domain, unsigned long memory)
{
M
Matthias Bolte 已提交
2148
    int result = -1;
M
Matthias Bolte 已提交
2149
    esxPrivate *priv = domain->conn->privateData;
2150 2151 2152 2153
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2154
    char *taskInfoErrorMessage = NULL;
2155

2156
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2157
        return -1;
2158 2159
    }

2160
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2161
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2162
           priv->parsedUri->autoAnswer) < 0 ||
2163 2164 2165
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0 ||
        esxVI_Long_Alloc(&spec->memoryAllocation->limit) < 0) {
M
Matthias Bolte 已提交
2166
        goto cleanup;
2167 2168 2169
    }

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

2172
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2173
                              &task) < 0 ||
2174
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2175
                                    esxVI_Occurrence_RequiredItem,
2176
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2177
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2178
        goto cleanup;
2179 2180 2181
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2182 2183 2184
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set memory to %lu kilobytes: %s"), memory,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2185
        goto cleanup;
2186 2187
    }

M
Matthias Bolte 已提交
2188 2189
    result = 0;

2190
 cleanup:
2191 2192 2193
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2194
    VIR_FREE(taskInfoErrorMessage);
2195 2196 2197 2198 2199 2200

    return result;
}



2201 2202 2203 2204 2205 2206 2207 2208 2209
/*
 * 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

2210 2211 2212
static int
esxDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info)
{
M
Matthias Bolte 已提交
2213
    int result = -1;
M
Matthias Bolte 已提交
2214
    esxPrivate *priv = domain->conn->privateData;
2215 2216 2217 2218 2219
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int64_t memory_limit = -1;
2220
#if ESX_QUERY_FOR_USED_CPU_TIME
2221 2222 2223 2224 2225 2226 2227
    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;
2228 2229
    esxVI_PerfEntityMetricBase *perfEntityMetricBase = NULL;
    esxVI_PerfEntityMetricBase *perfEntityMetricBaseList = NULL;
2230 2231 2232
    esxVI_PerfEntityMetric *perfEntityMetric = NULL;
    esxVI_PerfMetricIntSeries *perfMetricIntSeries = NULL;
    esxVI_Long *value = NULL;
2233
#endif
2234

2235
    memset(info, 0, sizeof(*info));
M
Matthias Bolte 已提交
2236

2237
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2238
        return -1;
2239 2240
    }

2241
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2242 2243 2244 2245
                                           "runtime.powerState\0"
                                           "config.hardware.memoryMB\0"
                                           "config.hardware.numCPU\0"
                                           "config.memoryAllocation.limit\0") < 0 ||
2246
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2247
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2248
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2249
        goto cleanup;
2250 2251 2252 2253
    }

    info->state = VIR_DOMAIN_NOSTATE;

2254
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
2255 2256 2257
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.powerState")) {
            if (esxVI_VirtualMachinePowerState_CastFromAnyType
2258
                  (dynamicProperty->val, &powerState) < 0) {
M
Matthias Bolte 已提交
2259
                goto cleanup;
2260 2261
            }

2262 2263
            info->state = esxVI_VirtualMachinePowerState_ConvertToLibvirt
                            (powerState);
2264
        } else if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2265
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2266
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2267
                goto cleanup;
2268 2269 2270 2271
            }

            info->maxMem = dynamicProperty->val->int32 * 1024; /* Scale from megabyte to kilobyte */
        } else if (STREQ(dynamicProperty->name, "config.hardware.numCPU")) {
2272
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2273
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2274
                goto cleanup;
2275 2276 2277 2278 2279
            }

            info->nrVirtCpu = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "config.memoryAllocation.limit")) {
2280
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2281
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
2282
                goto cleanup;
2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297
            }

            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;

2298
#if ESX_QUERY_FOR_USED_CPU_TIME
2299
    /* Verify the cached 'used CPU time' performance counter ID */
2300
    /* FIXME: Currently no host for a vpx:// connection */
2301
    if (priv->host) {
2302 2303 2304 2305
        if (info->state == VIR_DOMAIN_RUNNING && priv->usedCpuTimeCounterId >= 0) {
            if (esxVI_Int_Alloc(&counterId) < 0) {
                goto cleanup;
            }
2306

2307
            counterId->value = priv->usedCpuTimeCounterId;
2308

2309 2310 2311
            if (esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                goto cleanup;
            }
2312

2313 2314 2315 2316
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfo) < 0) {
                goto cleanup;
            }
2317

2318 2319 2320 2321 2322
            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);
2323

2324 2325 2326 2327 2328
                priv->usedCpuTimeCounterId = -1;
            }

            esxVI_Int_Free(&counterIdList);
            esxVI_PerfCounterInfo_Free(&perfCounterInfo);
2329 2330
        }

2331 2332 2333 2334 2335 2336 2337 2338 2339 2340
        /*
         * 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;
            }
2341

2342
            for (perfMetricId = perfMetricIdList; perfMetricId;
2343 2344 2345
                 perfMetricId = perfMetricId->_next) {
                VIR_DEBUG("perfMetricId counterId %d, instance '%s'",
                          perfMetricId->counterId->value, perfMetricId->instance);
2346

2347
                counterId = NULL;
2348

2349 2350 2351 2352 2353
                if (esxVI_Int_DeepCopy(&counterId, perfMetricId->counterId) < 0 ||
                    esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                    goto cleanup;
                }
            }
2354

2355 2356
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfoList) < 0) {
M
Matthias Bolte 已提交
2357
                goto cleanup;
2358 2359
            }

2360
            for (perfCounterInfo = perfCounterInfoList; perfCounterInfo;
2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376
                 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;
                }
2377 2378
            }

2379
            if (priv->usedCpuTimeCounterId < 0) {
2380
                VIR_WARN("Could not find 'used CPU time' performance counter");
2381
            }
2382 2383
        }

2384 2385 2386 2387 2388 2389
        /*
         * 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);
2390

2391 2392 2393 2394 2395 2396
            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;
            }
2397

2398 2399 2400 2401 2402 2403 2404 2405 2406 2407
            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;
            }
2408

2409
            for (perfEntityMetricBase = perfEntityMetricBaseList;
2410
                 perfEntityMetricBase;
2411
                 perfEntityMetricBase = perfEntityMetricBase->_next) {
2412
                VIR_DEBUG("perfEntityMetric ...");
2413

2414 2415
                perfEntityMetric =
                  esxVI_PerfEntityMetric_DynamicCast(perfEntityMetricBase);
2416

2417
                if (!perfEntityMetric) {
2418 2419 2420
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("QueryPerf returned object with unexpected type '%s'"),
                                   esxVI_Type_ToString(perfEntityMetricBase->_type));
2421
                    goto cleanup;
2422
                }
2423

2424 2425
                perfMetricIntSeries =
                  esxVI_PerfMetricIntSeries_DynamicCast(perfEntityMetric->value);
2426

2427
                if (!perfMetricIntSeries) {
2428 2429 2430
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("QueryPerf returned object with unexpected type '%s'"),
                                   esxVI_Type_ToString(perfEntityMetric->value->_type));
2431
                    goto cleanup;
2432
                }
2433

2434
                for (; perfMetricIntSeries;
2435
                     perfMetricIntSeries = perfMetricIntSeries->_next) {
2436
                    VIR_DEBUG("perfMetricIntSeries ...");
2437

2438
                    for (value = perfMetricIntSeries->value;
2439
                         value;
2440 2441 2442
                         value = value->_next) {
                        VIR_DEBUG("value %lld", (long long int)value->value);
                    }
2443 2444 2445
                }
            }

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

2448
            /*
E
Eric Blake 已提交
2449
             * FIXME: Cannot map between relative used-cpu-time and absolute
2450 2451 2452
             *        info->cpuTime
             */
        }
2453
    }
2454
#endif
2455

M
Matthias Bolte 已提交
2456 2457
    result = 0;

2458
 cleanup:
2459
#if ESX_QUERY_FOR_USED_CPU_TIME
2460 2461 2462 2463
    /*
     * Remove values owned by data structures to prevent them from being freed
     * by the call to esxVI_PerfQuerySpec_Free().
     */
2464
    if (querySpec) {
2465 2466 2467
        querySpec->entity = NULL;
        querySpec->format = NULL;

2468
        if (querySpec->metricId) {
2469 2470 2471
            querySpec->metricId->instance = NULL;
        }
    }
2472
#endif
2473

2474 2475
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2476
#if ESX_QUERY_FOR_USED_CPU_TIME
2477 2478 2479 2480
    esxVI_PerfMetricId_Free(&perfMetricIdList);
    esxVI_Int_Free(&counterIdList);
    esxVI_PerfCounterInfo_Free(&perfCounterInfoList);
    esxVI_PerfQuerySpec_Free(&querySpec);
2481
    esxVI_PerfEntityMetricBase_Free(&perfEntityMetricBaseList);
2482
#endif
2483 2484 2485 2486 2487 2488

    return result;
}



2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522
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;

2523
 cleanup:
2524 2525 2526 2527 2528 2529 2530 2531
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
}



2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609
static char *
esxDomainScreenshot(virDomainPtr domain, virStreamPtr stream,
                    unsigned int screen, unsigned int flags)
{
    char *mimeType = NULL;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_Boolean supportsScreenshot = esxVI_Boolean_Undefined;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    char *url = NULL;

    virCheckFlags(0, NULL);

    if (screen != 0) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Screen cannot be selected"));
        return NULL;
    }

    supportsScreenshot = esxSupportsScreenshot(priv);

    if (supportsScreenshot == esxVI_Boolean_Undefined)
        return NULL;

    if (supportsScreenshot != esxVI_Boolean_True) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                       _("Screenshot feature is unsupported"));
        return NULL;
    }

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

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

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
        goto cleanup;
    }

    /* Build URL */
    virBufferAsprintf(&buffer, "%s://%s:%d/screen?id=", priv->parsedUri->transport,
                      domain->conn->uri->server, domain->conn->uri->port);
    virBufferURIEncodeString(&buffer, virtualMachine->obj->value);

    if (virBufferCheckError(&buffer))
        goto cleanup;

    url = virBufferContentAndReset(&buffer);

    if (VIR_STRDUP(mimeType, "image/png") < 0)
        goto cleanup;

    if (esxStreamOpenDownload(stream, priv, url, 0, 0) < 0) {
        VIR_FREE(mimeType);
        goto cleanup;
    }

 cleanup:
    virBufferFreeAndReset(&buffer);

    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);

    return mimeType;
}



2610
static int
2611 2612
esxDomainSetVcpusFlags(virDomainPtr domain, unsigned int nvcpus,
                       unsigned int flags)
2613
{
M
Matthias Bolte 已提交
2614
    int result = -1;
M
Matthias Bolte 已提交
2615
    esxPrivate *priv = domain->conn->privateData;
M
Matthias Bolte 已提交
2616
    int maxVcpus;
2617 2618 2619 2620
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2621
    char *taskInfoErrorMessage = NULL;
2622

2623
    if (flags != VIR_DOMAIN_AFFECT_LIVE) {
2624
        virReportError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
2625 2626 2627
        return -1;
    }

2628
    if (nvcpus < 1) {
2629 2630
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Requested number of virtual CPUs must at least be 1"));
M
Matthias Bolte 已提交
2631
        return -1;
2632 2633
    }

2634
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2635
        return -1;
2636 2637
    }

M
Matthias Bolte 已提交
2638
    maxVcpus = esxDomainGetMaxVcpus(domain);
2639

M
Matthias Bolte 已提交
2640
    if (maxVcpus < 0) {
M
Matthias Bolte 已提交
2641
        return -1;
2642 2643
    }

M
Matthias Bolte 已提交
2644
    if (nvcpus > maxVcpus) {
2645 2646 2647 2648
        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 已提交
2649
        return -1;
2650 2651
    }

2652
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2653
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2654
           priv->parsedUri->autoAnswer) < 0 ||
2655 2656
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Int_Alloc(&spec->numCPUs) < 0) {
M
Matthias Bolte 已提交
2657
        goto cleanup;
2658 2659 2660 2661
    }

    spec->numCPUs->value = nvcpus;

2662
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2663
                              &task) < 0 ||
2664
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2665
                                    esxVI_Occurrence_RequiredItem,
2666
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2667
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2668
        goto cleanup;
2669 2670 2671
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2672 2673 2674
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set number of virtual CPUs to %d: %s"), nvcpus,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2675
        goto cleanup;
2676 2677
    }

M
Matthias Bolte 已提交
2678 2679
    result = 0;

2680
 cleanup:
2681 2682 2683
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2684
    VIR_FREE(taskInfoErrorMessage);
2685 2686 2687 2688 2689

    return result;
}


M
Matthias Bolte 已提交
2690

2691 2692 2693
static int
esxDomainSetVcpus(virDomainPtr domain, unsigned int nvcpus)
{
2694
    return esxDomainSetVcpusFlags(domain, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
2695 2696
}

2697

M
Matthias Bolte 已提交
2698

2699
static int
2700
esxDomainGetVcpusFlags(virDomainPtr domain, unsigned int flags)
2701
{
M
Matthias Bolte 已提交
2702
    esxPrivate *priv = domain->conn->privateData;
2703 2704 2705 2706
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

2707
    if (flags != (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_VCPU_MAXIMUM)) {
2708
        virReportError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
2709 2710 2711
        return -1;
    }

M
Matthias Bolte 已提交
2712 2713
    if (priv->maxVcpus > 0) {
        return priv->maxVcpus;
2714 2715
    }

M
Matthias Bolte 已提交
2716 2717
    priv->maxVcpus = -1;

2718
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2719
        return -1;
2720 2721
    }

2722
    if (esxVI_String_AppendValueToList(&propertyNameList,
2723
                                       "capability.maxSupportedVcpus") < 0 ||
2724 2725
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
2726
        goto cleanup;
2727 2728
    }

2729
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
2730 2731
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "capability.maxSupportedVcpus")) {
2732
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2733
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2734
                goto cleanup;
2735 2736
            }

M
Matthias Bolte 已提交
2737
            priv->maxVcpus = dynamicProperty->val->int32;
2738 2739 2740 2741 2742 2743
            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

2744
 cleanup:
2745 2746 2747
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
2748
    return priv->maxVcpus;
2749 2750
}

M
Matthias Bolte 已提交
2751 2752


2753 2754 2755
static int
esxDomainGetMaxVcpus(virDomainPtr domain)
{
2756
    return esxDomainGetVcpusFlags(domain, (VIR_DOMAIN_AFFECT_LIVE |
2757 2758
                                           VIR_DOMAIN_VCPU_MAXIMUM));
}
2759

M
Matthias Bolte 已提交
2760 2761


2762
static char *
2763
esxDomainGetXMLDesc(virDomainPtr domain, unsigned int flags)
2764
{
M
Matthias Bolte 已提交
2765
    esxPrivate *priv = domain->conn->privateData;
2766 2767
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
2768 2769
    esxVI_VirtualMachinePowerState powerState;
    int id;
2770
    char *vmPathName = NULL;
2771
    char *datastoreName = NULL;
M
Matthias Bolte 已提交
2772
    char *directoryName = NULL;
2773
    char *directoryAndFileName = NULL;
2774
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
2775 2776
    char *url = NULL;
    char *vmx = NULL;
2777
    virVMXContext ctx;
2778
    esxVMX_Data data;
2779 2780 2781
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2782 2783
    /* Flags checked by virDomainDefFormat */

2784
    memset(&data, 0, sizeof(data));
2785

2786
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2787
        return NULL;
2788 2789
    }

2790 2791 2792
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "config.files.vmPathName\0"
                                           "runtime.powerState\0") < 0 ||
2793
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2794
                                         propertyNameList, &virtualMachine,
2795
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2796 2797
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0 ||
2798 2799
        esxVI_GetStringValue(virtualMachine, "config.files.vmPathName",
                             &vmPathName, esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2800
        goto cleanup;
2801 2802
    }

2803
    if (esxUtil_ParseDatastorePath(vmPathName, &datastoreName, &directoryName,
2804
                                   &directoryAndFileName) < 0) {
M
Matthias Bolte 已提交
2805
        goto cleanup;
2806 2807
    }

2808
    virBufferAsprintf(&buffer, "%s://%s:%d/folder/", priv->parsedUri->transport,
2809
                      domain->conn->uri->server, domain->conn->uri->port);
2810
    virBufferURIEncodeString(&buffer, directoryAndFileName);
2811
    virBufferAddLit(&buffer, "?dcPath=");
2812
    virBufferURIEncodeString(&buffer, priv->primary->datacenterPath);
2813 2814 2815
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

2816
    if (virBufferCheckError(&buffer) < 0)
M
Matthias Bolte 已提交
2817
        goto cleanup;
2818

2819 2820
    url = virBufferContentAndReset(&buffer);

2821
    if (esxVI_CURL_Download(priv->primary->curl, url, &vmx, 0, NULL) < 0) {
M
Matthias Bolte 已提交
2822
        goto cleanup;
2823 2824
    }

2825
    data.ctx = priv->primary;
2826

2827
    if (!directoryName) {
2828
        if (virAsprintf(&data.datastorePathWithoutFileName, "[%s]",
2829
                        datastoreName) < 0)
2830 2831 2832
            goto cleanup;
    } else {
        if (virAsprintf(&data.datastorePathWithoutFileName, "[%s] %s",
2833
                        datastoreName, directoryName) < 0)
2834 2835
            goto cleanup;
    }
2836 2837 2838 2839 2840 2841

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

2842
    def = virVMXParseConfig(&ctx, priv->xmlopt, vmx);
2843

2844
    if (def) {
2845 2846 2847 2848
        if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
            def->id = id;
        }

2849
        xml = virDomainDefFormat(def, flags);
2850 2851
    }

2852
 cleanup:
2853
    if (!url) {
M
Matthias Bolte 已提交
2854 2855 2856
        virBufferFreeAndReset(&buffer);
    }

2857 2858
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2859
    VIR_FREE(datastoreName);
M
Matthias Bolte 已提交
2860
    VIR_FREE(directoryName);
2861
    VIR_FREE(directoryAndFileName);
2862
    VIR_FREE(url);
2863
    VIR_FREE(data.datastorePathWithoutFileName);
2864
    VIR_FREE(vmx);
2865
    virDomainDefFree(def);
2866 2867 2868 2869 2870 2871 2872

    return xml;
}



static char *
2873 2874 2875
esxConnectDomainXMLFromNative(virConnectPtr conn, const char *nativeFormat,
                              const char *nativeConfig,
                              unsigned int flags)
2876
{
M
Matthias Bolte 已提交
2877
    esxPrivate *priv = conn->privateData;
2878
    virVMXContext ctx;
2879
    esxVMX_Data data;
2880 2881 2882
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2883 2884
    virCheckFlags(0, NULL);

2885
    memset(&data, 0, sizeof(data));
2886

2887
    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2888 2889
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Unsupported config format '%s'"), nativeFormat);
2890
        return NULL;
2891 2892
    }

2893
    data.ctx = priv->primary;
2894
    data.datastorePathWithoutFileName = (char *)"[?] ?";
2895 2896 2897 2898 2899 2900

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

2901
    def = virVMXParseConfig(&ctx, priv->xmlopt, nativeConfig);
2902

2903
    if (def) {
2904
        xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
2905 2906 2907 2908 2909 2910 2911 2912 2913
    }

    virDomainDefFree(def);

    return xml;
}



M
Matthias Bolte 已提交
2914
static char *
2915 2916 2917
esxConnectDomainXMLToNative(virConnectPtr conn, const char *nativeFormat,
                            const char *domainXml,
                            unsigned int flags)
M
Matthias Bolte 已提交
2918
{
M
Matthias Bolte 已提交
2919
    esxPrivate *priv = conn->privateData;
2920 2921
    int virtualHW_version;
    virVMXContext ctx;
2922
    esxVMX_Data data;
M
Matthias Bolte 已提交
2923 2924 2925
    virDomainDefPtr def = NULL;
    char *vmx = NULL;

E
Eric Blake 已提交
2926 2927
    virCheckFlags(0, NULL);

2928
    memset(&data, 0, sizeof(data));
2929

M
Matthias Bolte 已提交
2930
    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2931 2932
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Unsupported config format '%s'"), nativeFormat);
M
Matthias Bolte 已提交
2933 2934 2935
        return NULL;
    }

2936 2937 2938 2939 2940 2941 2942
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        return NULL;
    }

2943
    def = virDomainDefParseString(domainXml, priv->caps, priv->xmlopt,
2944 2945
                                  1 << VIR_DOMAIN_VIRT_VMWARE,
                                  VIR_DOMAIN_XML_INACTIVE);
M
Matthias Bolte 已提交
2946

2947
    if (!def) {
M
Matthias Bolte 已提交
2948 2949 2950
        return NULL;
    }

2951
    data.ctx = priv->primary;
2952
    data.datastorePathWithoutFileName = NULL;
2953 2954 2955 2956 2957 2958

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

2959
    vmx = virVMXFormatConfig(&ctx, priv->xmlopt, def, virtualHW_version);
M
Matthias Bolte 已提交
2960 2961 2962 2963 2964 2965 2966 2967

    virDomainDefFree(def);

    return vmx;
}



2968
static int
2969
esxConnectListDefinedDomains(virConnectPtr conn, char **const names, int maxnames)
2970
{
M
Matthias Bolte 已提交
2971
    bool success = false;
M
Matthias Bolte 已提交
2972
    esxPrivate *priv = conn->privateData;
2973 2974 2975 2976 2977
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;
2978
    size_t i;
2979 2980 2981 2982 2983

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

2984
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2985
        return -1;
2986 2987
    }

2988
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2989 2990
                                           "name\0"
                                           "runtime.powerState\0") < 0 ||
2991 2992
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2993
        goto cleanup;
2994 2995
    }

2996
    for (virtualMachine = virtualMachineList; virtualMachine;
2997
         virtualMachine = virtualMachine->_next) {
2998
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
2999
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
3000
            goto cleanup;
3001 3002 3003 3004 3005 3006
        }

        if (powerState == esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

3007
        names[count] = NULL;
3008

3009 3010 3011
        if (esxVI_GetVirtualMachineIdentity(virtualMachine, NULL, &names[count],
                                            NULL) < 0) {
            goto cleanup;
3012 3013
        }

3014 3015
        ++count;

3016 3017 3018 3019 3020
        if (count >= maxnames) {
            break;
        }
    }

M
Matthias Bolte 已提交
3021
    success = true;
3022

3023
 cleanup:
M
Matthias Bolte 已提交
3024 3025 3026 3027
    if (! success) {
        for (i = 0; i < count; ++i) {
            VIR_FREE(names[i]);
        }
3028

M
Matthias Bolte 已提交
3029
        count = -1;
3030 3031
    }

M
Matthias Bolte 已提交
3032 3033
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
3034

M
Matthias Bolte 已提交
3035
    return count;
3036 3037 3038 3039 3040
}



static int
3041
esxConnectNumOfDefinedDomains(virConnectPtr conn)
3042
{
M
Matthias Bolte 已提交
3043
    esxPrivate *priv = conn->privateData;
3044

3045
    if (esxVI_EnsureSession(priv->primary) < 0) {
3046 3047 3048
        return -1;
    }

3049
    return esxVI_LookupNumberOfDomainsByPowerState
3050
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, true);
3051 3052 3053 3054 3055
}



static int
3056
esxDomainCreateWithFlags(virDomainPtr domain, unsigned int flags)
3057
{
M
Matthias Bolte 已提交
3058
    int result = -1;
M
Matthias Bolte 已提交
3059
    esxPrivate *priv = domain->conn->privateData;
3060 3061 3062
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
3063
    int id = -1;
3064 3065
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3066
    char *taskInfoErrorMessage = NULL;
3067

3068 3069
    virCheckFlags(0, -1);

3070
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3071
        return -1;
3072 3073
    }

3074
    if (esxVI_String_AppendValueToList(&propertyNameList,
3075
                                       "runtime.powerState") < 0 ||
3076
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3077
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
3078
           priv->parsedUri->autoAnswer) < 0 ||
3079 3080
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0) {
M
Matthias Bolte 已提交
3081
        goto cleanup;
3082 3083 3084
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
3085 3086
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered off"));
M
Matthias Bolte 已提交
3087
        goto cleanup;
3088 3089
    }

3090
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
3091
                             &task) < 0 ||
3092
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3093
                                    esxVI_Occurrence_RequiredItem,
3094
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3095
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3096
        goto cleanup;
3097 3098 3099
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3100 3101
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not start domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3102
        goto cleanup;
3103 3104
    }

3105
    domain->id = id;
M
Matthias Bolte 已提交
3106 3107
    result = 0;

3108
 cleanup:
3109 3110 3111
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
3112
    VIR_FREE(taskInfoErrorMessage);
3113 3114 3115 3116

    return result;
}

3117 3118


3119 3120 3121 3122 3123
static int
esxDomainCreate(virDomainPtr domain)
{
    return esxDomainCreateWithFlags(domain, 0);
}
3124

3125 3126


M
Matthias Bolte 已提交
3127
static virDomainPtr
3128
esxDomainDefineXML(virConnectPtr conn, const char *xml)
M
Matthias Bolte 已提交
3129
{
M
Matthias Bolte 已提交
3130
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
3131 3132
    virDomainDefPtr def = NULL;
    char *vmx = NULL;
3133
    size_t i;
3134
    virDomainDiskDefPtr disk = NULL;
M
Matthias Bolte 已提交
3135
    esxVI_ObjectContent *virtualMachine = NULL;
3136 3137
    int virtualHW_version;
    virVMXContext ctx;
3138
    esxVMX_Data data;
M
Matthias Bolte 已提交
3139 3140
    char *datastoreName = NULL;
    char *directoryName = NULL;
3141
    char *escapedName = NULL;
M
Matthias Bolte 已提交
3142 3143 3144 3145 3146 3147 3148 3149
    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;
3150
    char *taskInfoErrorMessage = NULL;
M
Matthias Bolte 已提交
3151
    virDomainPtr domain = NULL;
3152
    const char *src;
M
Matthias Bolte 已提交
3153

3154
    memset(&data, 0, sizeof(data));
3155

3156
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3157
        return NULL;
M
Matthias Bolte 已提交
3158 3159 3160
    }

    /* Parse domain XML */
3161 3162
    def = virDomainDefParseString(xml, priv->caps, priv->xmlopt,
                                  1 << VIR_DOMAIN_VIRT_VMWARE,
M
Matthias Bolte 已提交
3163 3164
                                  VIR_DOMAIN_XML_INACTIVE);

3165
    if (!def) {
M
Matthias Bolte 已提交
3166
        return NULL;
M
Matthias Bolte 已提交
3167 3168 3169
    }

    /* Check if an existing domain should be edited */
3170
    if (esxVI_LookupVirtualMachineByUuid(priv->primary, def->uuid, NULL,
M
Matthias Bolte 已提交
3171
                                         &virtualMachine,
M
Matthias Bolte 已提交
3172
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
3173
        goto cleanup;
M
Matthias Bolte 已提交
3174 3175
    }

3176
    if (!virtualMachine &&
3177 3178 3179 3180 3181 3182
        esxVI_LookupVirtualMachineByName(priv->primary, def->name, NULL,
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
    }

3183
    if (virtualMachine) {
M
Matthias Bolte 已提交
3184
        /* FIXME */
3185 3186 3187
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Domain already exists, editing existing domains is not "
                         "supported yet"));
M
Matthias Bolte 已提交
3188
        goto cleanup;
M
Matthias Bolte 已提交
3189 3190 3191
    }

    /* Build VMX from domain XML */
3192 3193 3194 3195 3196 3197 3198
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        goto cleanup;
    }

3199
    data.ctx = priv->primary;
3200
    data.datastorePathWithoutFileName = NULL;
3201 3202 3203 3204 3205 3206

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

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

3209
    if (!vmx) {
M
Matthias Bolte 已提交
3210
        goto cleanup;
M
Matthias Bolte 已提交
3211 3212
    }

3213 3214 3215
    /*
     * 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 已提交
3216
     * first disk, because it may be CDROM disk and ISO images are normally not
3217 3218 3219
     * 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 已提交
3220
    if (def->ndisks < 1) {
3221 3222 3223
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Domain XML doesn't contain any disks, cannot deduce "
                         "datastore and path for VMX file"));
M
Matthias Bolte 已提交
3224
        goto cleanup;
3225 3226 3227 3228
    }

    for (i = 0; i < def->ndisks; ++i) {
        if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK &&
E
Eric Blake 已提交
3229
            virDomainDiskGetType(def->disks[i]) == VIR_STORAGE_TYPE_FILE) {
3230 3231 3232 3233 3234
            disk = def->disks[i];
            break;
        }
    }

3235
    if (!disk) {
3236 3237 3238
        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 已提交
3239
        goto cleanup;
M
Matthias Bolte 已提交
3240 3241
    }

3242 3243
    src = virDomainDiskGetSource(disk);
    if (!src) {
3244 3245 3246
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("First file-based harddisk has no source, cannot deduce "
                         "datastore and path for VMX file"));
M
Matthias Bolte 已提交
3247
        goto cleanup;
M
Matthias Bolte 已提交
3248 3249
    }

3250
    if (esxUtil_ParseDatastorePath(src, &datastoreName, &directoryName,
3251
                                   NULL) < 0) {
M
Matthias Bolte 已提交
3252
        goto cleanup;
M
Matthias Bolte 已提交
3253 3254
    }

3255
    if (! virFileHasSuffix(src, ".vmdk")) {
3256 3257
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Expecting source '%s' of first file-based harddisk to "
3258
                         "be a VMDK image"), src);
M
Matthias Bolte 已提交
3259
        goto cleanup;
M
Matthias Bolte 已提交
3260 3261
    }

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

3265
    if (directoryName) {
M
Matthias Bolte 已提交
3266 3267 3268 3269
        virBufferURIEncodeString(&buffer, directoryName);
        virBufferAddChar(&buffer, '/');
    }

3270 3271
    escapedName = esxUtil_EscapeDatastoreItem(def->name);

3272
    if (!escapedName) {
3273 3274 3275 3276
        goto cleanup;
    }

    virBufferURIEncodeString(&buffer, escapedName);
M
Matthias Bolte 已提交
3277
    virBufferAddLit(&buffer, ".vmx?dcPath=");
3278
    virBufferURIEncodeString(&buffer, priv->primary->datacenterPath);
M
Matthias Bolte 已提交
3279 3280 3281
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

3282
    if (virBufferCheckError(&buffer) < 0)
M
Matthias Bolte 已提交
3283
        goto cleanup;
M
Matthias Bolte 已提交
3284 3285 3286

    url = virBufferContentAndReset(&buffer);

3287 3288 3289 3290 3291 3292
    /* Check, if VMX file already exists */
    /* FIXME */

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

3293
    if (esxVI_CURL_Upload(priv->primary->curl, url, vmx) < 0) {
3294 3295 3296 3297
        goto cleanup;
    }

    /* Register the domain */
3298
    if (directoryName) {
M
Matthias Bolte 已提交
3299
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s/%s.vmx", datastoreName,
3300
                        directoryName, escapedName) < 0)
M
Matthias Bolte 已提交
3301
            goto cleanup;
M
Matthias Bolte 已提交
3302 3303
    } else {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s.vmx", datastoreName,
3304
                        escapedName) < 0)
M
Matthias Bolte 已提交
3305
            goto cleanup;
M
Matthias Bolte 已提交
3306 3307
    }

3308
    if (esxVI_RegisterVM_Task(priv->primary, priv->primary->datacenter->vmFolder,
M
Matthias Bolte 已提交
3309
                              datastoreRelatedPath, NULL, esxVI_Boolean_False,
3310 3311 3312 3313
                              priv->primary->computeResource->resourcePool,
                              priv->primary->hostSystem->_reference,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, def->uuid,
3314
                                    esxVI_Occurrence_OptionalItem,
3315
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3316
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3317
        goto cleanup;
M
Matthias Bolte 已提交
3318 3319 3320
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3321 3322
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not define domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3323
        goto cleanup;
M
Matthias Bolte 已提交
3324 3325 3326 3327
    }

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

3328
    if (domain) {
M
Matthias Bolte 已提交
3329 3330 3331 3332 3333
        domain->id = -1;
    }

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

3334
 cleanup:
3335
    if (!url) {
M
Matthias Bolte 已提交
3336 3337 3338
        virBufferFreeAndReset(&buffer);
    }

M
Matthias Bolte 已提交
3339 3340 3341 3342
    virDomainDefFree(def);
    VIR_FREE(vmx);
    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
3343
    VIR_FREE(escapedName);
M
Matthias Bolte 已提交
3344 3345 3346 3347 3348 3349 3350
    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);
3351
    VIR_FREE(taskInfoErrorMessage);
M
Matthias Bolte 已提交
3352 3353 3354 3355 3356 3357

    return domain;
}



3358
static int
3359 3360
esxDomainUndefineFlags(virDomainPtr domain,
                       unsigned int flags)
3361
{
M
Matthias Bolte 已提交
3362
    int result = -1;
M
Matthias Bolte 已提交
3363
    esxPrivate *priv = domain->conn->privateData;
3364
    esxVI_Context *ctx = NULL;
3365 3366 3367 3368
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

3369 3370 3371 3372
    /* 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);
3373

3374
    if (priv->vCenter) {
3375 3376 3377 3378 3379
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

3380
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
3381
        return -1;
3382 3383
    }

3384
    if (esxVI_String_AppendValueToList(&propertyNameList,
3385
                                       "runtime.powerState") < 0 ||
3386 3387
        esxVI_LookupVirtualMachineByUuid(ctx, domain->uuid, propertyNameList,
                                         &virtualMachine,
M
Matthias Bolte 已提交
3388
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3389
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
3390
        goto cleanup;
3391 3392 3393 3394
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended &&
        powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
3395 3396
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not suspended or powered off"));
M
Matthias Bolte 已提交
3397
        goto cleanup;
3398 3399
    }

3400
    if (esxVI_UnregisterVM(ctx, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
3401
        goto cleanup;
3402 3403
    }

M
Matthias Bolte 已提交
3404 3405
    result = 0;

3406
 cleanup:
3407 3408 3409 3410 3411 3412 3413
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}


3414 3415 3416 3417 3418
static int
esxDomainUndefine(virDomainPtr domain)
{
    return esxDomainUndefineFlags(domain, 0);
}
3419

3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452
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;
    }

3453
    if (!powerInfoList) {
3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464
        /* 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;
    }

3465
    for (powerInfo = powerInfoList; powerInfo;
3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477
         powerInfo = powerInfo->_next) {
        if (STREQ(powerInfo->key->value, virtualMachine->obj->value)) {
            if (STRCASEEQ(powerInfo->startAction, "powerOn")) {
                *autostart = 1;
            }

            break;
        }
    }

    result = 0;

3478
 cleanup:
3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534
    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;
            }

3535
            for (powerInfo = powerInfoList; powerInfo;
3536 3537
                 powerInfo = powerInfo->_next) {
                if (STRNEQ(powerInfo->key->value, virtualMachine->obj->value)) {
3538 3539 3540
                    virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                                   _("Cannot enable general autostart option "
                                     "without affecting other domains"));
3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556
                    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 ||
3557
        esxVI_Int_Alloc(&newPowerInfo->stopDelay) < 0) {
3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568
        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";

3569 3570 3571 3572 3573
    if (esxVI_AutoStartPowerInfo_AppendToList(&spec->powerInfo,
                                              newPowerInfo) < 0) {
        goto cleanup;
    }

3574
    newPowerInfo = NULL;
3575

3576 3577 3578 3579 3580 3581 3582 3583 3584
    if (esxVI_ReconfigureAutostart
          (priv->primary,
           priv->primary->hostSystem->configManager->autoStartManager,
           spec) < 0) {
        goto cleanup;
    }

    result = 0;

3585
 cleanup:
3586
    if (newPowerInfo) {
3587 3588 3589 3590 3591 3592 3593 3594 3595 3596
        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);

3597
    esxVI_AutoStartPowerInfo_Free(&newPowerInfo);
3598

3599 3600 3601 3602 3603
    return result;
}



3604 3605 3606 3607 3608 3609 3610 3611 3612 3613
/*
 * 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:
 *
3614
 * - reservation (VIR_TYPED_PARAM_LLONG >= 0, in megaherz)
3615
 *
3616
 *   The amount of CPU resource that is guaranteed to be available to the domain.
3617 3618
 *
 *
3619
 * - limit (VIR_TYPED_PARAM_LLONG >= 0, or -1, in megaherz)
3620
 *
3621 3622
 *   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
3623 3624 3625 3626
 *   utilization of the domain is unlimited. If the limit is not set to -1, it
 *   must be greater than or equal to the reservation.
 *
 *
3627
 * - shares (VIR_TYPED_PARAM_INT >= 0, or in {-1, -2, -3}, no unit)
3628 3629 3630 3631 3632 3633
 *
 *   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'.
 */
3634
static char *
3635
esxDomainGetSchedulerType(virDomainPtr domain ATTRIBUTE_UNUSED, int *nparams)
3636
{
3637
    char *type;
3638

3639
    if (VIR_STRDUP(type, "allocation") < 0)
3640
        return NULL;
3641

3642
    if (nparams) {
3643 3644
        *nparams = 3; /* reservation, limit, shares */
    }
3645 3646 3647 3648 3649 3650 3651

    return type;
}



static int
3652 3653 3654
esxDomainGetSchedulerParametersFlags(virDomainPtr domain,
                                     virTypedParameterPtr params, int *nparams,
                                     unsigned int flags)
3655
{
M
Matthias Bolte 已提交
3656
    int result = -1;
M
Matthias Bolte 已提交
3657
    esxPrivate *priv = domain->conn->privateData;
3658 3659 3660 3661 3662
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    unsigned int mask = 0;
3663
    size_t i = 0;
3664

3665 3666
    virCheckFlags(0, -1);

3667
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3668
        return -1;
3669 3670
    }

3671
    if (esxVI_String_AppendValueListToList(&propertyNameList,
3672 3673 3674
                                           "config.cpuAllocation.reservation\0"
                                           "config.cpuAllocation.limit\0"
                                           "config.cpuAllocation.shares\0") < 0 ||
3675
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
3676
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3677
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3678
        goto cleanup;
3679 3680 3681
    }

    for (dynamicProperty = virtualMachine->propSet;
3682
         dynamicProperty && mask != 7 && i < 3 && i < *nparams;
3683 3684
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.cpuAllocation.reservation") &&
M
Matthias Bolte 已提交
3685
            ! (mask & (1 << 0))) {
3686
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3687
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3688
                goto cleanup;
3689
            }
3690 3691 3692 3693 3694
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_SCHEDULER_RESERVATION,
                                        VIR_TYPED_PARAM_LLONG,
                                        dynamicProperty->val->int64) < 0)
                goto cleanup;
3695 3696 3697 3698
            mask |= 1 << 0;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.limit") &&
M
Matthias Bolte 已提交
3699
                   ! (mask & (1 << 1))) {
3700
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3701
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3702
                goto cleanup;
3703
            }
3704 3705 3706 3707 3708
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_SCHEDULER_LIMIT,
                                        VIR_TYPED_PARAM_LLONG,
                                        dynamicProperty->val->int64) < 0)
                goto cleanup;
3709 3710 3711 3712
            mask |= 1 << 1;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.shares") &&
M
Matthias Bolte 已提交
3713
                   ! (mask & (1 << 2))) {
3714 3715 3716 3717
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_SCHEDULER_SHARES,
                                        VIR_TYPED_PARAM_INT, 0) < 0)
                goto cleanup;
3718
            if (esxVI_SharesInfo_CastFromAnyType(dynamicProperty->val,
3719
                                                 &sharesInfo) < 0) {
M
Matthias Bolte 已提交
3720
                goto cleanup;
3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740
            }

            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:
3741 3742 3743
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Shares level has unknown value %d"),
                               (int)sharesInfo->level);
3744
                esxVI_SharesInfo_Free(&sharesInfo);
M
Matthias Bolte 已提交
3745
                goto cleanup;
3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757
            }

            esxVI_SharesInfo_Free(&sharesInfo);

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

    *nparams = i;
M
Matthias Bolte 已提交
3758
    result = 0;
3759

3760
 cleanup:
3761 3762 3763 3764 3765 3766
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
}

3767 3768 3769 3770 3771 3772
static int
esxDomainGetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int *nparams)
{
    return esxDomainGetSchedulerParametersFlags(domain, params, nparams, 0);
}
3773 3774 3775


static int
3776 3777 3778
esxDomainSetSchedulerParametersFlags(virDomainPtr domain,
                                     virTypedParameterPtr params, int nparams,
                                     unsigned int flags)
3779
{
M
Matthias Bolte 已提交
3780
    int result = -1;
M
Matthias Bolte 已提交
3781
    esxPrivate *priv = domain->conn->privateData;
3782 3783 3784 3785 3786
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3787
    char *taskInfoErrorMessage = NULL;
3788
    size_t i;
3789

3790
    virCheckFlags(0, -1);
3791 3792 3793 3794 3795 3796 3797 3798
    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)
3799
        return -1;
3800

3801
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3802
        return -1;
3803 3804
    }

3805
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3806
          (priv->primary, domain->uuid, NULL, &virtualMachine,
3807
           priv->parsedUri->autoAnswer) < 0 ||
3808 3809
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->cpuAllocation) < 0) {
M
Matthias Bolte 已提交
3810
        goto cleanup;
3811 3812 3813
    }

    for (i = 0; i < nparams; ++i) {
3814
        if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_RESERVATION)) {
3815
            if (esxVI_Long_Alloc(&spec->cpuAllocation->reservation) < 0) {
M
Matthias Bolte 已提交
3816
                goto cleanup;
3817 3818 3819
            }

            if (params[i].value.l < 0) {
3820 3821 3822
                virReportError(VIR_ERR_INVALID_ARG,
                               _("Could not set reservation to %lld MHz, expecting "
                                 "positive value"), params[i].value.l);
M
Matthias Bolte 已提交
3823
                goto cleanup;
3824 3825 3826
            }

            spec->cpuAllocation->reservation->value = params[i].value.l;
3827
        } else if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_LIMIT)) {
3828
            if (esxVI_Long_Alloc(&spec->cpuAllocation->limit) < 0) {
M
Matthias Bolte 已提交
3829
                goto cleanup;
3830 3831 3832
            }

            if (params[i].value.l < -1) {
3833 3834 3835 3836
                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 已提交
3837
                goto cleanup;
3838 3839 3840
            }

            spec->cpuAllocation->limit->value = params[i].value.l;
3841
        } else if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_SHARES)) {
3842 3843
            if (esxVI_SharesInfo_Alloc(&sharesInfo) < 0 ||
                esxVI_Int_Alloc(&sharesInfo->shares) < 0) {
M
Matthias Bolte 已提交
3844
                goto cleanup;
3845 3846 3847
            }

            spec->cpuAllocation->shares = sharesInfo;
3848
            sharesInfo = NULL;
3849

3850
            if (params[i].value.i >= 0) {
3851
                spec->cpuAllocation->shares->level = esxVI_SharesLevel_Custom;
3852
                spec->cpuAllocation->shares->shares->value = params[i].value.i;
3853
            } else {
3854
                switch (params[i].value.i) {
3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872
                  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:
3873 3874 3875 3876
                    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 已提交
3877
                    goto cleanup;
3878 3879 3880 3881 3882
                }
            }
        }
    }

3883
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
3884
                              &task) < 0 ||
3885
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3886
                                    esxVI_Occurrence_RequiredItem,
3887
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3888
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3889
        goto cleanup;
3890 3891 3892
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3893 3894 3895
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not change scheduler parameters: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3896
        goto cleanup;
3897 3898
    }

M
Matthias Bolte 已提交
3899 3900
    result = 0;

3901
 cleanup:
3902
    esxVI_SharesInfo_Free(&sharesInfo);
3903 3904 3905
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
3906
    VIR_FREE(taskInfoErrorMessage);
3907 3908 3909 3910

    return result;
}

3911 3912 3913 3914 3915 3916
static int
esxDomainSetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int nparams)
{
    return esxDomainSetSchedulerParametersFlags(domain, params, nparams, 0);
}
3917

E
Eric Blake 已提交
3918 3919 3920 3921 3922 3923
/* 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)
3924 3925 3926 3927 3928

static int
esxDomainMigratePrepare(virConnectPtr dconn,
                        char **cookie ATTRIBUTE_UNUSED,
                        int *cookielen ATTRIBUTE_UNUSED,
3929 3930
                        const char *uri_in ATTRIBUTE_UNUSED,
                        char **uri_out,
E
Eric Blake 已提交
3931
                        unsigned long flags,
3932 3933 3934
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
3935
    esxPrivate *priv = dconn->privateData;
3936

E
Eric Blake 已提交
3937 3938
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

3939
    if (!uri_in) {
3940 3941 3942
        if (virAsprintf(uri_out, "vpxmigr://%s/%s/%s",
                        priv->vCenter->ipAddress,
                        priv->vCenter->computeResource->resourcePool->value,
3943
                        priv->vCenter->hostSystem->_reference->value) < 0)
3944
            return -1;
3945 3946
    }

3947
    return 0;
3948 3949 3950 3951 3952 3953 3954 3955 3956
}



static int
esxDomainMigratePerform(virDomainPtr domain,
                        const char *cookie ATTRIBUTE_UNUSED,
                        int cookielen ATTRIBUTE_UNUSED,
                        const char *uri,
E
Eric Blake 已提交
3957
                        unsigned long flags,
3958 3959 3960
                        const char *dname,
                        unsigned long bandwidth ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
3961
    int result = -1;
M
Matthias Bolte 已提交
3962
    esxPrivate *priv = domain->conn->privateData;
M
Martin Kletzander 已提交
3963
    virURIPtr parsedUri = NULL;
3964 3965 3966
    char *saveptr;
    char *path_resourcePool;
    char *path_hostSystem;
3967
    esxVI_ObjectContent *virtualMachine = NULL;
3968 3969
    esxVI_ManagedObjectReference resourcePool;
    esxVI_ManagedObjectReference hostSystem;
3970 3971 3972
    esxVI_Event *eventList = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3973
    char *taskInfoErrorMessage = NULL;
3974

E
Eric Blake 已提交
3975 3976
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

3977
    if (!priv->vCenter) {
3978 3979
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration not possible without a vCenter"));
M
Matthias Bolte 已提交
3980
        return -1;
3981 3982
    }

3983
    if (dname) {
3984 3985
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Renaming domains on migration not supported"));
M
Matthias Bolte 已提交
3986
        return -1;
3987 3988
    }

3989
    if (esxVI_EnsureSession(priv->vCenter) < 0) {
M
Matthias Bolte 已提交
3990
        return -1;
3991 3992
    }

3993
    /* Parse migration URI */
3994
    if (!(parsedUri = virURIParse(uri)))
M
Matthias Bolte 已提交
3995
        return -1;
3996

3997
    if (!parsedUri->scheme || STRCASENEQ(parsedUri->scheme, "vpxmigr")) {
3998 3999
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Only vpxmigr:// migration URIs are supported"));
M
Matthias Bolte 已提交
4000
        goto cleanup;
4001 4002
    }

4003
    if (STRCASENEQ(priv->vCenter->ipAddress, parsedUri->server)) {
4004 4005 4006
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration source and destination have to refer to "
                         "the same vCenter"));
4007 4008 4009 4010 4011 4012
        goto cleanup;
    }

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

4013
    if (!path_resourcePool || !path_hostSystem) {
4014 4015
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration URI has to specify resource pool and host system"));
M
Matthias Bolte 已提交
4016
        goto cleanup;
4017 4018
    }

4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031
    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,
4032
           priv->parsedUri->autoAnswer) < 0) {
M
Matthias Bolte 已提交
4033
        goto cleanup;
4034 4035 4036
    }

    /* Validate the purposed migration */
4037
    if (esxVI_ValidateMigration(priv->vCenter, virtualMachine->obj,
4038 4039
                                esxVI_VirtualMachinePowerState_Undefined, NULL,
                                &resourcePool, &hostSystem, &eventList) < 0) {
M
Matthias Bolte 已提交
4040
        goto cleanup;
4041 4042
    }

4043
    if (eventList) {
4044 4045 4046 4047
        /*
         * FIXME: Need to report the complete list of events. Limit reporting
         *        to the first event for now.
         */
4048
        if (eventList->fullFormattedMessage) {
4049 4050 4051
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not migrate domain, validation reported a "
                             "problem: %s"), eventList->fullFormattedMessage);
4052
        } else {
4053 4054 4055
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Could not migrate domain, validation reported a "
                             "problem"));
4056 4057
        }

M
Matthias Bolte 已提交
4058
        goto cleanup;
4059 4060 4061
    }

    /* Perform the purposed migration */
4062 4063
    if (esxVI_MigrateVM_Task(priv->vCenter, virtualMachine->obj,
                             &resourcePool, &hostSystem,
4064 4065 4066
                             esxVI_VirtualMachineMovePriority_DefaultPriority,
                             esxVI_VirtualMachinePowerState_Undefined,
                             &task) < 0 ||
4067
        esxVI_WaitForTaskCompletion(priv->vCenter, task, domain->uuid,
4068
                                    esxVI_Occurrence_RequiredItem,
4069
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4070
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4071
        goto cleanup;
4072 4073 4074
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4075 4076 4077 4078
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not migrate domain, migration task finished with "
                         "an error: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4079
        goto cleanup;
4080 4081
    }

M
Matthias Bolte 已提交
4082 4083
    result = 0;

4084
 cleanup:
4085
    virURIFree(parsedUri);
4086 4087 4088
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Event_Free(&eventList);
    esxVI_ManagedObjectReference_Free(&task);
4089
    VIR_FREE(taskInfoErrorMessage);
4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100

    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 已提交
4101
                       unsigned long flags)
4102
{
E
Eric Blake 已提交
4103 4104
    virCheckFlags(ESX_MIGRATION_FLAGS, NULL);

4105 4106 4107 4108 4109
    return esxDomainLookupByName(dconn, dname);
}



M
Matthias Bolte 已提交
4110 4111 4112 4113
static unsigned long long
esxNodeGetFreeMemory(virConnectPtr conn)
{
    unsigned long long result = 0;
M
Matthias Bolte 已提交
4114
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
4115 4116 4117 4118 4119
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *resourcePool = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ResourcePoolResourceUsage *resourcePoolResourceUsage = NULL;

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

    /* Get memory usage of resource pool */
4125
    if (esxVI_String_AppendValueToList(&propertyNameList,
M
Matthias Bolte 已提交
4126
                                       "runtime.memory") < 0 ||
4127 4128
        esxVI_LookupObjectContentByType(priv->primary,
                                        priv->primary->computeResource->resourcePool,
4129
                                        "ResourcePool", propertyNameList,
4130 4131
                                        &resourcePool,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4132
        goto cleanup;
M
Matthias Bolte 已提交
4133 4134
    }

4135
    for (dynamicProperty = resourcePool->propSet; dynamicProperty;
M
Matthias Bolte 已提交
4136 4137 4138
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.memory")) {
            if (esxVI_ResourcePoolResourceUsage_CastFromAnyType
4139
                  (dynamicProperty->val, &resourcePoolResourceUsage) < 0) {
M
Matthias Bolte 已提交
4140
                goto cleanup;
M
Matthias Bolte 已提交
4141 4142 4143 4144 4145 4146 4147 4148
            }

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

4149
    if (!resourcePoolResourceUsage) {
4150 4151
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not retrieve memory usage of resource pool"));
M
Matthias Bolte 已提交
4152
        goto cleanup;
M
Matthias Bolte 已提交
4153 4154 4155 4156
    }

    result = resourcePoolResourceUsage->unreservedForVm->value;

4157
 cleanup:
M
Matthias Bolte 已提交
4158 4159 4160 4161 4162 4163 4164 4165 4166
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&resourcePool);
    esxVI_ResourcePoolResourceUsage_Free(&resourcePoolResourceUsage);

    return result;
}



4167
static int
4168
esxConnectIsEncrypted(virConnectPtr conn)
4169
{
M
Matthias Bolte 已提交
4170
    esxPrivate *priv = conn->privateData;
4171

4172
    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
4173 4174 4175 4176 4177 4178 4179 4180 4181
        return 1;
    } else {
        return 0;
    }
}



static int
4182
esxConnectIsSecure(virConnectPtr conn)
4183
{
M
Matthias Bolte 已提交
4184
    esxPrivate *priv = conn->privateData;
4185

4186
    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
4187 4188 4189 4190 4191 4192 4193 4194
        return 1;
    } else {
        return 0;
    }
}



4195
static int
4196
esxConnectIsAlive(virConnectPtr conn)
4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211
{
    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;
}



4212 4213 4214
static int
esxDomainIsActive(virDomainPtr domain)
{
M
Matthias Bolte 已提交
4215
    int result = -1;
M
Matthias Bolte 已提交
4216
    esxPrivate *priv = domain->conn->privateData;
4217 4218 4219 4220
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

4221
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4222
        return -1;
4223 4224
    }

4225
    if (esxVI_String_AppendValueToList(&propertyNameList,
4226
                                       "runtime.powerState") < 0 ||
4227
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
4228
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
4229
                                         esxVI_Occurrence_RequiredItem) < 0 ||
4230
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
4231
        goto cleanup;
4232 4233 4234 4235 4236 4237 4238 4239
    }

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

4240
 cleanup:
4241 4242 4243 4244 4245 4246 4247 4248 4249
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
4250
esxDomainIsPersistent(virDomainPtr domain)
4251
{
4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267
    /* 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;

4268
 cleanup:
4269 4270 4271
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
4272 4273
}

M
Matthias Bolte 已提交
4274 4275


4276 4277 4278
static int
esxDomainIsUpdated(virDomainPtr domain ATTRIBUTE_UNUSED)
{
4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294
    /* 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;

4295
 cleanup:
4296 4297 4298
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
4299
}
4300

M
Matthias Bolte 已提交
4301 4302


4303 4304
static virDomainSnapshotPtr
esxDomainSnapshotCreateXML(virDomainPtr domain, const char *xmlDesc,
4305
                           unsigned int flags)
4306 4307 4308 4309 4310 4311 4312 4313
{
    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;
4314
    char *taskInfoErrorMessage = NULL;
4315
    virDomainSnapshotPtr snapshot = NULL;
4316 4317
    bool diskOnly = (flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY) != 0;
    bool quiesce = (flags & VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE) != 0;
4318

4319 4320 4321 4322 4323
    /* 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);
4324

4325
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4326
        return NULL;
4327 4328
    }

4329
    def = virDomainSnapshotDefParseString(xmlDesc, priv->caps,
4330
                                          priv->xmlopt, 0, 0);
4331

4332
    if (!def) {
M
Matthias Bolte 已提交
4333
        return NULL;
4334 4335
    }

4336
    if (def->ndisks) {
4337 4338
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("disk snapshots not supported yet"));
4339 4340 4341
        return NULL;
    }

4342
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
4343
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4344
           priv->parsedUri->autoAnswer) < 0 ||
4345
        esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4346 4347
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, def->name,
4348
                                    &snapshotTree, NULL,
4349
                                    esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4350
        goto cleanup;
4351 4352
    }

4353
    if (snapshotTree) {
4354 4355
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Snapshot '%s' already exists"), def->name);
M
Matthias Bolte 已提交
4356
        goto cleanup;
4357 4358
    }

4359
    if (esxVI_CreateSnapshot_Task(priv->primary, virtualMachine->obj,
4360
                                  def->name, def->description,
4361 4362 4363
                                  diskOnly ? esxVI_Boolean_False : esxVI_Boolean_True,
                                  quiesce ? esxVI_Boolean_True : esxVI_Boolean_False,
                                  &task) < 0 ||
4364
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
4365
                                    esxVI_Occurrence_RequiredItem,
4366
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4367
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4368
        goto cleanup;
4369 4370 4371
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4372 4373
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not create snapshot: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4374
        goto cleanup;
4375 4376 4377 4378
    }

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

4379
 cleanup:
4380 4381 4382 4383
    virDomainSnapshotDefFree(def);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4384
    VIR_FREE(taskInfoErrorMessage);
4385 4386 4387 4388 4389 4390 4391

    return snapshot;
}



static char *
4392 4393
esxDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                            unsigned int flags)
4394 4395 4396 4397 4398 4399 4400 4401 4402
{
    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;

4403 4404
    virCheckFlags(0, NULL);

4405
    memset(&def, 0, sizeof(def));
4406

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

4411
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4412 4413 4414 4415
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4416
        goto cleanup;
4417 4418 4419 4420
    }

    def.name = snapshot->name;
    def.description = snapshotTree->description;
4421
    def.parent = snapshotTreeParent ? snapshotTreeParent->name : NULL;
4422 4423 4424

    if (esxVI_DateTime_ConvertToCalendarTime(snapshotTree->createTime,
                                             &def.creationTime) < 0) {
M
Matthias Bolte 已提交
4425
        goto cleanup;
4426 4427 4428 4429 4430 4431 4432
    }

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

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

4433
    xml = virDomainSnapshotDefFormat(uuid_string, &def, flags, 0);
4434

4435
 cleanup:
4436 4437 4438 4439 4440 4441 4442 4443
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return xml;
}



static int
4444
esxDomainSnapshotNum(virDomainPtr domain, unsigned int flags)
4445
{
M
Matthias Bolte 已提交
4446
    int count;
4447 4448
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
4449
    bool recurse;
4450
    bool leaves;
4451

4452
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
4453 4454
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4455 4456

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) == 0;
4457
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4458

4459
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4460
        return -1;
4461 4462
    }

4463 4464 4465 4466
    /* ESX snapshots do not require libvirt to maintain any metadata.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA)
        return 0;

4467
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4468
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4469
        return -1;
4470 4471
    }

4472 4473
    count = esxVI_GetNumberOfSnapshotTrees(rootSnapshotTreeList, recurse,
                                           leaves);
4474 4475 4476

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

M
Matthias Bolte 已提交
4477
    return count;
4478 4479 4480 4481 4482 4483
}



static int
esxDomainSnapshotListNames(virDomainPtr domain, char **names, int nameslen,
4484
                           unsigned int flags)
4485
{
M
Matthias Bolte 已提交
4486
    int result;
4487 4488
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
4489
    bool recurse;
4490
    bool leaves;
4491 4492

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
4493 4494
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4495

4496
    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) == 0;
4497
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4498

4499
    if (!names || nameslen < 0) {
4500
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
4501 4502 4503
        return -1;
    }

4504
    if (nameslen == 0 || (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA)) {
4505 4506 4507
        return 0;
    }

4508
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4509
        return -1;
4510 4511
    }

4512
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4513
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4514
        return -1;
4515 4516
    }

4517
    result = esxVI_GetSnapshotTreeNames(rootSnapshotTreeList, names, nameslen,
4518
                                        recurse, leaves);
4519 4520 4521 4522 4523 4524 4525 4526

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



4527 4528 4529 4530 4531 4532 4533 4534
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;
4535
    bool leaves;
4536 4537

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
4538 4539
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4540 4541

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) != 0;
4542
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562

    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,
4563
                                           recurse, leaves);
4564

4565
 cleanup:
4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582
    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;
4583
    bool leaves;
4584 4585

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
4586 4587
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4588 4589

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) != 0;
4590
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4591

4592
    if (!names || nameslen < 0) {
4593
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619
        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,
4620
                                        names, nameslen, recurse, leaves);
4621

4622
 cleanup:
4623 4624 4625 4626 4627 4628 4629
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



4630 4631
static virDomainSnapshotPtr
esxDomainSnapshotLookupByName(virDomainPtr domain, const char *name,
4632
                              unsigned int flags)
4633 4634 4635 4636 4637 4638
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    virDomainSnapshotPtr snapshot = NULL;

4639 4640
    virCheckFlags(0, NULL);

4641
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4642
        return NULL;
4643 4644
    }

4645
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4646 4647
                                         &rootSnapshotTreeList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotTreeList, name, &snapshotTree,
4648
                                    NULL,
4649 4650 4651 4652 4653 4654
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    snapshot = virGetDomainSnapshot(domain, name);

4655
 cleanup:
4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return snapshot;
}



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

4669
    virCheckFlags(0, -1);
4670

4671
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4672
        return -1;
4673 4674
    }

4675
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4676 4677
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4678
        return -1;
4679 4680
    }

4681
    if (currentSnapshotTree) {
M
Matthias Bolte 已提交
4682 4683
        esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);
        return 1;
4684 4685
    }

M
Matthias Bolte 已提交
4686
    return 0;
4687 4688 4689 4690
}



E
Eric Blake 已提交
4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714
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) {
4715 4716 4717
        virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                       _("snapshot '%s' does not have a parent"),
                       snapshotTree->name);
E
Eric Blake 已提交
4718 4719 4720 4721 4722
        goto cleanup;
    }

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

4723
 cleanup:
E
Eric Blake 已提交
4724 4725 4726 4727 4728 4729 4730
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return parent;
}



4731 4732 4733 4734 4735
static virDomainSnapshotPtr
esxDomainSnapshotCurrent(virDomainPtr domain, unsigned int flags)
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *currentSnapshotTree = NULL;
M
Matthias Bolte 已提交
4736
    virDomainSnapshotPtr snapshot = NULL;
4737

4738
    virCheckFlags(0, NULL);
4739

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

4744
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4745 4746
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4747
        return NULL;
4748 4749 4750 4751 4752 4753 4754 4755 4756 4757
    }

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

    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return snapshot;
}


4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789
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);

4790
 cleanup:
4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821
    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;

4822
 cleanup:
4823 4824 4825 4826
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    return ret;
}

4827 4828 4829 4830

static int
esxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4831
    int result = -1;
4832 4833 4834 4835 4836
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
4837
    char *taskInfoErrorMessage = NULL;
4838

4839
    virCheckFlags(0, -1);
4840

4841
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4842
        return -1;
4843 4844
    }

4845
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4846 4847
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
4848
                                    &snapshotTree, NULL,
4849
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4850
        goto cleanup;
4851 4852
    }

4853
    if (esxVI_RevertToSnapshot_Task(priv->primary, snapshotTree->snapshot, NULL,
4854
                                    esxVI_Boolean_Undefined, &task) < 0 ||
4855
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4856
                                    esxVI_Occurrence_RequiredItem,
4857
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4858
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4859
        goto cleanup;
4860 4861 4862
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4863 4864 4865
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not revert to snapshot '%s': %s"), snapshot->name,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4866
        goto cleanup;
4867 4868
    }

M
Matthias Bolte 已提交
4869 4870
    result = 0;

4871
 cleanup:
4872 4873
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4874
    VIR_FREE(taskInfoErrorMessage);
4875 4876 4877 4878 4879 4880 4881 4882 4883

    return result;
}



static int
esxDomainSnapshotDelete(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4884
    int result = -1;
4885 4886 4887 4888 4889 4890
    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;
4891
    char *taskInfoErrorMessage = NULL;
4892

4893 4894
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
                  VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY, -1);
4895

4896
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4897
        return -1;
4898 4899 4900 4901 4902 4903
    }

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

4904
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4905 4906
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
4907
                                    &snapshotTree, NULL,
4908
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4909
        goto cleanup;
4910 4911
    }

4912 4913 4914 4915 4916 4917 4918
    /* 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;
    }

4919
    if (esxVI_RemoveSnapshot_Task(priv->primary, snapshotTree->snapshot,
4920
                                  removeChildren, &task) < 0 ||
4921
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4922
                                    esxVI_Occurrence_RequiredItem,
4923
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4924
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4925
        goto cleanup;
4926 4927 4928
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4929 4930 4931
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not delete snapshot '%s': %s"), snapshot->name,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4932
        goto cleanup;
4933 4934
    }

M
Matthias Bolte 已提交
4935 4936
    result = 0;

4937
 cleanup:
4938 4939
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4940
    VIR_FREE(taskInfoErrorMessage);
4941 4942 4943 4944 4945 4946

    return result;
}



4947
static int
4948
esxDomainSetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
4949 4950 4951 4952 4953 4954 4955 4956
                             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;
4957
    char *taskInfoErrorMessage = NULL;
4958
    size_t i;
4959 4960

    virCheckFlags(0, -1);
4961 4962 4963 4964
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_MEMORY_MIN_GUARANTEE,
                               VIR_TYPED_PARAM_ULLONG,
                               NULL) < 0)
4965
        return -1;
4966 4967 4968 4969 4970 4971 4972

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

    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4973
           priv->parsedUri->autoAnswer) < 0 ||
4974 4975 4976 4977 4978 4979
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0) {
        goto cleanup;
    }

    for (i = 0; i < nparams; ++i) {
4980
        if (STREQ(params[i].field, VIR_DOMAIN_MEMORY_MIN_GUARANTEE)) {
4981 4982 4983 4984 4985
            if (esxVI_Long_Alloc(&spec->memoryAllocation->reservation) < 0) {
                goto cleanup;
            }

            spec->memoryAllocation->reservation->value =
4986
              VIR_DIV_UP(params[i].value.ul, 1024); /* Scale from kilobytes to megabytes */
4987 4988 4989 4990 4991 4992 4993
        }
    }

    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
4994
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4995
                                    &taskInfoErrorMessage) < 0) {
4996 4997 4998 4999
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
5000 5001 5002
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not change memory parameters: %s"),
                       taskInfoErrorMessage);
5003 5004 5005 5006 5007
        goto cleanup;
    }

    result = 0;

5008
 cleanup:
5009 5010 5011
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
5012
    VIR_FREE(taskInfoErrorMessage);
5013 5014 5015 5016 5017 5018 5019

    return result;
}



static int
5020
esxDomainGetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049
                             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;
    }

5050 5051 5052 5053
    /* Scale from megabytes to kilobytes */
    if (virTypedParameterAssign(params, VIR_DOMAIN_MEMORY_MIN_GUARANTEE,
                                VIR_TYPED_PARAM_ULLONG,
                                reservation->value * 1024) < 0)
5054 5055 5056 5057 5058
        goto cleanup;

    *nparams = 1;
    result = 0;

5059
 cleanup:
5060 5061 5062 5063 5064 5065 5066
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Long_Free(&reservation);

    return result;
}

5067 5068
#define MATCH(FLAG) (flags & (FLAG))
static int
5069 5070 5071
esxConnectListAllDomains(virConnectPtr conn,
                         virDomainPtr **domains,
                         unsigned int flags)
5072 5073 5074
{
    int ret = -1;
    esxPrivate *priv = conn->privateData;
5075 5076
    bool needIdentity;
    bool needPowerState;
5077 5078 5079
    virDomainPtr dom;
    virDomainPtr *doms = NULL;
    size_t ndoms = 0;
5080
    esxVI_String *propertyNameList = NULL;
5081 5082
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
5083
    esxVI_AutoStartDefaults *autoStartDefaults = NULL;
5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100
    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
     */
5101
    if ((MATCH(VIR_CONNECT_LIST_DOMAINS_TRANSIENT) &&
5102 5103 5104 5105 5106
         !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)
5107
            goto cleanup;
5108 5109 5110 5111 5112

        ret = 0;
        goto cleanup;
    }

5113
    if (esxVI_EnsureSession(priv->primary) < 0)
5114 5115 5116 5117 5118
        return -1;

    /* check system default autostart value */
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_AUTOSTART)) {
        if (esxVI_LookupAutoStartDefaults(priv->primary,
5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131
                                          &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) ||
5132
                   domains;
5133 5134 5135 5136 5137 5138 5139

    if (needIdentity) {
        /* Request required data for esxVI_GetVirtualMachineIdentity */
        if (esxVI_String_AppendValueListToList(&propertyNameList,
                                               "configStatus\0"
                                               "name\0"
                                               "config.uuid\0") < 0) {
5140
            goto cleanup;
5141 5142 5143 5144 5145
        }
    }

    needPowerState = MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_ACTIVE) ||
                     MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_STATE) ||
5146
                     domains;
5147

5148 5149 5150
    if (needPowerState) {
        if (esxVI_String_AppendValueToList(&propertyNameList,
                                           "runtime.powerState") < 0) {
5151
            goto cleanup;
5152
        }
5153 5154
    }

5155
    if (esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
5156 5157 5158 5159 5160
                                       &virtualMachineList) < 0)
        goto cleanup;

    if (domains) {
        if (VIR_ALLOC_N(doms, 1) < 0)
5161
            goto cleanup;
5162 5163 5164
        ndoms = 1;
    }

5165
    for (virtualMachine = virtualMachineList; virtualMachine;
5166
         virtualMachine = virtualMachine->_next) {
5167 5168
        if (needIdentity) {
            VIR_FREE(name);
5169

5170 5171 5172 5173 5174
            if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id,
                                                &name, uuid) < 0) {
                goto cleanup;
            }
        }
5175

5176 5177 5178 5179 5180 5181
        if (needPowerState) {
            if (esxVI_GetVirtualMachinePowerState(virtualMachine,
                                                  &powerState) < 0) {
                goto cleanup;
            }
        }
5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192

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

5195 5196 5197 5198 5199 5200
            if (esxVI_LookupRootSnapshotTreeList(priv->primary, uuid,
                                                 &rootSnapshotTreeList) < 0) {
                goto cleanup;
            }

            if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT) &&
5201
                   rootSnapshotTreeList) ||
5202
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT) &&
5203
                   !rootSnapshotTreeList)))
5204 5205 5206 5207 5208 5209 5210
                continue;
        }

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

5211
            if (autoStartDefaults->enabled == esxVI_Boolean_True) {
5212
                for (powerInfo = powerInfoList; powerInfo;
5213 5214 5215 5216
                     powerInfo = powerInfo->_next) {
                    if (STREQ(powerInfo->key->value, virtualMachine->obj->value)) {
                        if (STRCASEEQ(powerInfo->startAction, "powerOn"))
                            autostart = true;
5217

5218 5219
                        break;
                    }
5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232
                }
            }

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

5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252
            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;
        }

5253
        if (VIR_RESIZE_N(doms, ndoms, count, 2) < 0)
5254
            goto cleanup;
5255

5256 5257 5258
        if (!(dom = virGetDomain(conn, name, uuid)))
            goto cleanup;

5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272
        /* 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;

5273
 cleanup:
5274 5275
    if (doms) {
        for (id = 0; id < count; id++) {
5276
            virDomainFree(doms[id]);
5277
        }
5278 5279

        VIR_FREE(doms);
5280
    }
5281

5282
    VIR_FREE(name);
5283 5284
    esxVI_AutoStartDefaults_Free(&autoStartDefaults);
    esxVI_AutoStartPowerInfo_Free(&powerInfoList);
5285 5286
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
5287 5288
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

5289 5290 5291
    return ret;
}
#undef MATCH
5292 5293


5294
static virDriver esxDriver = {
5295 5296
    .no = VIR_DRV_ESX,
    .name = "ESX",
5297 5298 5299 5300 5301 5302
    .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 */
5303
    .nodeGetInfo = esxNodeGetInfo, /* 0.7.0 */
5304 5305 5306 5307
    .connectGetCapabilities = esxConnectGetCapabilities, /* 0.7.1 */
    .connectListDomains = esxConnectListDomains, /* 0.7.0 */
    .connectNumOfDomains = esxConnectNumOfDomains, /* 0.7.0 */
    .connectListAllDomains = esxConnectListAllDomains, /* 0.10.2 */
5308 5309 5310 5311 5312 5313
    .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 */
5314
    .domainShutdownFlags = esxDomainShutdownFlags, /* 0.9.10 */
5315 5316
    .domainReboot = esxDomainReboot, /* 0.7.0 */
    .domainDestroy = esxDomainDestroy, /* 0.7.0 */
5317
    .domainDestroyFlags = esxDomainDestroyFlags, /* 0.9.4 */
5318 5319 5320 5321 5322 5323 5324 5325
    .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 */
5326
    .domainScreenshot = esxDomainScreenshot, /* 1.2.10 */
5327 5328 5329 5330 5331
    .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 */
5332 5333 5334 5335
    .connectDomainXMLFromNative = esxConnectDomainXMLFromNative, /* 0.7.0 */
    .connectDomainXMLToNative = esxConnectDomainXMLToNative, /* 0.7.2 */
    .connectListDefinedDomains = esxConnectListDefinedDomains, /* 0.7.0 */
    .connectNumOfDefinedDomains = esxConnectNumOfDefinedDomains, /* 0.7.0 */
5336 5337 5338 5339
    .domainCreate = esxDomainCreate, /* 0.7.0 */
    .domainCreateWithFlags = esxDomainCreateWithFlags, /* 0.8.2 */
    .domainDefineXML = esxDomainDefineXML, /* 0.7.2 */
    .domainUndefine = esxDomainUndefine, /* 0.7.1 */
5340
    .domainUndefineFlags = esxDomainUndefineFlags, /* 0.9.4 */
5341 5342 5343 5344
    .domainGetAutostart = esxDomainGetAutostart, /* 0.9.0 */
    .domainSetAutostart = esxDomainSetAutostart, /* 0.9.0 */
    .domainGetSchedulerType = esxDomainGetSchedulerType, /* 0.7.0 */
    .domainGetSchedulerParameters = esxDomainGetSchedulerParameters, /* 0.7.0 */
5345
    .domainGetSchedulerParametersFlags = esxDomainGetSchedulerParametersFlags, /* 0.9.2 */
5346
    .domainSetSchedulerParameters = esxDomainSetSchedulerParameters, /* 0.7.0 */
5347
    .domainSetSchedulerParametersFlags = esxDomainSetSchedulerParametersFlags, /* 0.9.2 */
5348 5349 5350 5351
    .domainMigratePrepare = esxDomainMigratePrepare, /* 0.7.0 */
    .domainMigratePerform = esxDomainMigratePerform, /* 0.7.0 */
    .domainMigrateFinish = esxDomainMigrateFinish, /* 0.7.0 */
    .nodeGetFreeMemory = esxNodeGetFreeMemory, /* 0.7.2 */
5352 5353
    .connectIsEncrypted = esxConnectIsEncrypted, /* 0.7.3 */
    .connectIsSecure = esxConnectIsSecure, /* 0.7.3 */
5354 5355 5356 5357 5358 5359 5360
    .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 */
5361 5362
    .domainSnapshotNumChildren = esxDomainSnapshotNumChildren, /* 0.9.7 */
    .domainSnapshotListChildrenNames = esxDomainSnapshotListChildrenNames, /* 0.9.7 */
5363 5364
    .domainSnapshotLookupByName = esxDomainSnapshotLookupByName, /* 0.8.0 */
    .domainHasCurrentSnapshot = esxDomainHasCurrentSnapshot, /* 0.8.0 */
E
Eric Blake 已提交
5365
    .domainSnapshotGetParent = esxDomainSnapshotGetParent, /* 0.9.7 */
5366 5367
    .domainSnapshotCurrent = esxDomainSnapshotCurrent, /* 0.8.0 */
    .domainRevertToSnapshot = esxDomainRevertToSnapshot, /* 0.8.0 */
5368 5369
    .domainSnapshotIsCurrent = esxDomainSnapshotIsCurrent, /* 0.9.13 */
    .domainSnapshotHasMetadata = esxDomainSnapshotHasMetadata, /* 0.9.13 */
5370
    .domainSnapshotDelete = esxDomainSnapshotDelete, /* 0.8.0 */
5371
    .connectIsAlive = esxConnectIsAlive, /* 0.9.8 */
5372 5373 5374 5375 5376 5377 5378
};



int
esxRegister(void)
{
5379 5380 5381 5382 5383
    if (virRegisterDriver(&esxDriver) < 0 ||
        esxInterfaceRegister() < 0 ||
        esxNetworkRegister() < 0 ||
        esxStorageRegister() < 0 ||
        esxDeviceRegister() < 0 ||
M
Matthias Bolte 已提交
5384 5385
        esxSecretRegister() < 0 ||
        esxNWFilterRegister() < 0) {
5386 5387
        return -1;
    }
5388 5389 5390

    return 0;
}