esx_driver.c 121.1 KB
Newer Older
1 2

/*
3
 * esx_driver.c: core driver functions for managing VMware ESX hosts
4
 *
E
Eric Blake 已提交
5
 * Copyright (C) 2010 Red Hat, Inc.
6
 * Copyright (C) 2009-2010 Matthias Bolte <matthias.bolte@googlemail.com>
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
 * 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
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 */

#include <config.h>

#include <netdb.h>

#include "internal.h"
#include "domain_conf.h"
31
#include "authhelper.h"
32 33 34 35 36
#include "util.h"
#include "memory.h"
#include "logging.h"
#include "uuid.h"
#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 47 48 49 50 51 52 53 54
#include "esx_vi.h"
#include "esx_vi_methods.h"
#include "esx_util.h"
#include "esx_vmx.h"

#define VIR_FROM_THIS VIR_FROM_ESX

static int esxDomainGetMaxVcpus(virDomainPtr domain);



55
static esxVI_Boolean
56
esxSupportsLongMode(esxPrivate *priv)
57 58 59 60 61 62
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_HostCpuIdInfo *hostCpuIdInfoList = NULL;
    esxVI_HostCpuIdInfo *hostCpuIdInfo = NULL;
63
    esxVI_ParsedHostCpuIdInfo parsedHostCpuIdInfo;
64 65 66 67 68 69
    char edxLongModeBit = '?';

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

70
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
71
        return esxVI_Boolean_Undefined;
72 73
    }

74
    if (esxVI_String_AppendValueToList(&propertyNameList,
75
                                       "hardware.cpuFeature") < 0 ||
76 77
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
78
        goto cleanup;
79 80 81
    }

    if (hostSystem == NULL) {
82 83
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
84
        goto cleanup;
85 86 87 88 89 90
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuFeature")) {
            if (esxVI_HostCpuIdInfo_CastListFromAnyType
91
                  (dynamicProperty->val, &hostCpuIdInfoList) < 0) {
M
Matthias Bolte 已提交
92
                goto cleanup;
93 94 95 96 97
            }

            for (hostCpuIdInfo = hostCpuIdInfoList; hostCpuIdInfo != NULL;
                 hostCpuIdInfo = hostCpuIdInfo->_next) {
                if (hostCpuIdInfo->level->value == -2147483647) { /* 0x80000001 */
98 99
                    if (esxVI_ParseHostCpuIdInfo(&parsedHostCpuIdInfo,
                                                 hostCpuIdInfo) < 0) {
M
Matthias Bolte 已提交
100
                        goto cleanup;
101 102
                    }

103
                    edxLongModeBit = parsedHostCpuIdInfo.edx[29];
104 105 106 107 108 109

                    if (edxLongModeBit == '1') {
                        priv->supportsLongMode = esxVI_Boolean_True;
                    } else if (edxLongModeBit == '0') {
                        priv->supportsLongMode = esxVI_Boolean_False;
                    } else {
110
                        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
111 112 113 114
                                  _("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 已提交
115
                        goto cleanup;
116 117 118 119 120 121 122 123 124 125 126 127 128
                    }

                    break;
                }
            }

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

  cleanup:
M
Matthias Bolte 已提交
129 130 131 132
    /*
     * 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.
     */
133 134 135 136 137 138 139 140 141
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_HostCpuIdInfo_Free(&hostCpuIdInfoList);

    return priv->supportsLongMode;
}



142 143 144 145 146 147 148 149
static int
esxLookupHostSystemBiosUuid(esxPrivate *priv, unsigned char *uuid)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

150
    if (esxVI_EnsureSession(priv->primary) < 0) {
151 152 153 154 155
        return -1;
    }

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "hardware.systemInfo.uuid") < 0 ||
156 157
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
        goto cleanup;
    }

    if (hostSystem == NULL) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
        goto cleanup;
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.systemInfo.uuid")) {
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
                                         esxVI_Type_String) < 0) {
                goto cleanup;
            }

            if (strlen(dynamicProperty->val->string) > 0) {
                if (virUUIDParse(dynamicProperty->val->string, uuid) < 0) {
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                              _("Could not parse UUID from string '%s'"),
                              dynamicProperty->val->string);
                    goto cleanup;
                }
            } else {
                /* HostSystem has an empty UUID */
                memset(uuid, 0, VIR_UUID_BUFLEN);
            }

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

    result = 0;

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



204
static virCapsPtr
205
esxCapsInit(esxPrivate *priv)
206
{
207
    esxVI_Boolean supportsLongMode = esxSupportsLongMode(priv);
208 209 210
    virCapsPtr caps = NULL;
    virCapsGuestPtr guest = NULL;

211 212 213 214 215 216 217 218 219
    if (supportsLongMode == esxVI_Boolean_Undefined) {
        return NULL;
    }

    if (supportsLongMode == esxVI_Boolean_True) {
        caps = virCapabilitiesNew("x86_64", 1, 1);
    } else {
        caps = virCapabilitiesNew("i686", 1, 1);
    }
220 221

    if (caps == NULL) {
222
        virReportOOMError();
223 224 225
        return NULL;
    }

226
    virCapabilitiesSetMacPrefix(caps, (unsigned char[]){ 0x00, 0x0c, 0x29 });
227
    virCapabilitiesAddHostMigrateTransport(caps, "vpxmigr");
228

229 230
    caps->hasWideScsiBus = true;

231 232 233 234
    if (esxLookupHostSystemBiosUuid(priv, caps->host.host_uuid) < 0) {
        goto failure;
    }

235 236 237
    /* i686 */
    guest = virCapabilitiesAddGuest(caps, "hvm", "i686", 32, NULL, NULL, 0,
                                    NULL);
238 239 240 241 242 243 244 245 246 247 248 249 250 251

    if (guest == NULL) {
        goto failure;
    }

    /*
     * FIXME: Maybe distinguish betwen ESX and GSX here, see
     * esxVMX_ParseConfig() and VIR_DOMAIN_VIRT_VMWARE
     */
    if (virCapabilitiesAddGuestDomain(guest, "vmware", NULL, NULL, 0,
                                      NULL) == NULL) {
        goto failure;
    }

252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    /* x86_64 */
    if (supportsLongMode == esxVI_Boolean_True) {
        guest = virCapabilitiesAddGuest(caps, "hvm", "x86_64", 64, NULL, NULL,
                                        0, NULL);

        if (guest == NULL) {
            goto failure;
        }

        /*
         * FIXME: Maybe distinguish betwen ESX and GSX here, see
         * esxVMX_ParseConfig() and VIR_DOMAIN_VIRT_VMWARE
         */
        if (virCapabilitiesAddGuestDomain(guest, "vmware", NULL, NULL, 0,
                                          NULL) == NULL) {
            goto failure;
        }
    }

271 272 273 274 275 276 277 278 279 280
    return caps;

  failure:
    virCapabilitiesFree(caps);

    return NULL;
}



281 282 283 284
static int
esxConnectToHost(esxPrivate *priv, virConnectAuthPtr auth,
                 const char *hostname, int port,
                 const char *predefinedUsername,
M
Matthias Bolte 已提交
285
                 esxUtil_ParsedUri *parsedUri,
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
                 esxVI_ProductVersion expectedProductVersion,
                 char **vCenterIpAddress)
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
    char *password = NULL;
    char *url = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_Boolean inMaintenanceMode = esxVI_Boolean_Undefined;

    if (vCenterIpAddress == NULL || *vCenterIpAddress != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

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

    if (predefinedUsername != NULL) {
        username = strdup(predefinedUsername);

        if (username == NULL) {
            virReportOOMError();
            goto cleanup;
        }
    } else {
        username = virRequestUsername(auth, "root", hostname);

        if (username == NULL) {
            ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Username request failed"));
            goto cleanup;
        }
    }

    password = virRequestPassword(auth, username, hostname);

    if (password == NULL) {
        ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
        goto cleanup;
    }

    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->transport, hostname,
                    port) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    if (esxVI_Context_Alloc(&priv->host) < 0 ||
        esxVI_Context_Connect(priv->host, url, ipAddress, username, password,
338 339
                              parsedUri) < 0 ||
        esxVI_Context_LookupObjectsByPath(priv->host, parsedUri) < 0) {
340 341 342 343 344
        goto cleanup;
    }

    if (expectedProductVersion == esxVI_ProductVersion_ESX) {
        if (priv->host->productVersion != esxVI_ProductVersion_ESX35 &&
M
Matthias Bolte 已提交
345 346 347
            priv->host->productVersion != esxVI_ProductVersion_ESX40 &&
            priv->host->productVersion != esxVI_ProductVersion_ESX41 &&
            priv->host->productVersion != esxVI_ProductVersion_ESX4x) {
348
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
M
Matthias Bolte 已提交
349
                      _("%s is neither an ESX 3.5 host nor an ESX 4.x host"),
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
                      hostname);
            goto cleanup;
        }
    } else { /* GSX */
        if (priv->host->productVersion != esxVI_ProductVersion_GSX20) {
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                      _("%s isn't a GSX 2.0 host"), hostname);
            goto cleanup;
        }
    }

    /* Query the host for maintenance mode and vCenter IP address */
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "runtime.inMaintenanceMode\0"
                                           "summary.managementServerIp\0") < 0 ||
365 366
        esxVI_LookupHostSystemProperties(priv->host, propertyNameList,
                                         &hostSystem) < 0 ||
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
        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) {
        VIR_WARN0("The server is in maintenance mode");
    }

    if (*vCenterIpAddress != NULL) {
        *vCenterIpAddress = strdup(*vCenterIpAddress);

        if (*vCenterIpAddress == NULL) {
            virReportOOMError();
            goto cleanup;
        }
    }

    result = 0;

  cleanup:
    VIR_FREE(password);
    VIR_FREE(username);
    VIR_FREE(url);
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



static int
esxConnectToVCenter(esxPrivate *priv, virConnectAuthPtr auth,
                    const char *hostname, int port,
                    const char *predefinedUsername,
408
                    const char *hostSystemIpAddress,
M
Matthias Bolte 已提交
409
                    esxUtil_ParsedUri *parsedUri)
410 411 412 413 414 415 416
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
    char *password = NULL;
    char *url = NULL;

417 418 419 420 421 422 423 424
    if (hostSystemIpAddress == NULL &&
        (parsedUri->path_datacenter == NULL ||
         parsedUri->path_computeResource == NULL)) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Path has to specify the datacenter and compute resource"));
        return -1;
    }

425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
    if (esxUtil_ResolveHostname(hostname, ipAddress, NI_MAXHOST) < 0) {
        return -1;
    }

    if (predefinedUsername != NULL) {
        username = strdup(predefinedUsername);

        if (username == NULL) {
            virReportOOMError();
            goto cleanup;
        }
    } else {
        username = virRequestUsername(auth, "administrator", hostname);

        if (username == NULL) {
            ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Username request failed"));
            goto cleanup;
        }
    }

    password = virRequestPassword(auth, username, hostname);

    if (password == NULL) {
        ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
        goto cleanup;
    }

    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->transport, hostname,
                    port) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    if (esxVI_Context_Alloc(&priv->vCenter) < 0 ||
        esxVI_Context_Connect(priv->vCenter, url, ipAddress, username,
M
Matthias Bolte 已提交
460
                              password, parsedUri) < 0) {
461 462 463 464
        goto cleanup;
    }

    if (priv->vCenter->productVersion != esxVI_ProductVersion_VPX25 &&
M
Matthias Bolte 已提交
465 466 467
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX40 &&
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX41 &&
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX4x) {
468 469
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("%s is neither a vCenter 2.5 server nor a vCenter "
M
Matthias Bolte 已提交
470
                    "4.x server"), hostname);
471 472 473
        goto cleanup;
    }

474 475 476 477 478 479 480 481 482 483 484
    if (hostSystemIpAddress != NULL) {
        if (esxVI_Context_LookupObjectsByHostSystemIp(priv->vCenter,
                                                      hostSystemIpAddress) < 0) {
            goto cleanup;
        }
    } else {
        if (esxVI_Context_LookupObjectsByPath(priv->vCenter, parsedUri) < 0) {
            goto cleanup;
        }
    }

485 486 487 488 489 490 491 492 493 494 495 496
    result = 0;

  cleanup:
    VIR_FREE(password);
    VIR_FREE(username);
    VIR_FREE(url);

    return result;
}



497
/*
498 499
 * URI format: {vpx|esx|gsx}://[<username>@]<hostname>[:<port>]/[<path>][?<query parameter> ...]
 *             <path> = <datacenter>/<computeresource>[/<hostsystem>]
500
 *
501 502
 * If no port is specified the default port is set dependent on the scheme and
 * transport parameter:
503 504
 * - vpx+http  80
 * - vpx+https 443
505
 * - esx+http  80
506
 * - esx+https 443
507 508 509
 * - gsx+http  8222
 * - gsx+https 8333
 *
510 511 512 513 514
 * 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
 * can be omitted.
 *
515 516
 * Optional query parameters:
 * - transport={http|https}
517
 * - vcenter={<vcenter>|*}             only useful for an esx:// connection
518 519
 * - no_verify={0|1}
 * - auto_answer={0|1}
M
Matthias Bolte 已提交
520
 * - proxy=[{http|socks|socks4|socks4a|socks5}://]<hostname>[:<port>]
521
 *
522 523 524
 * If no transport parameter is specified https is used.
 *
 * The vcenter parameter is only necessary for migration, because the vCenter
525
 * server is in charge to initiate a migration between two ESX hosts. The
526
 * vcenter parameter can be set to an explicitly hostname or to *. If set to *,
527 528
 * 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.
529 530
 *
 * If the no_verify parameter is set to 1, this disables libcurl client checks
531
 * of the server's certificate. The default value it 0.
532 533 534 535
 *
 * If the auto_answer parameter is set to 1, the driver will respond to all
 * virtual machine questions with the default answer, otherwise virtual machine
 * questions will be reported as errors. The default value it 0.
M
Matthias Bolte 已提交
536 537 538 539
 *
 * 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.
540 541 542 543
 */
static virDrvOpenStatus
esxOpen(virConnectPtr conn, virConnectAuthPtr auth, int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
544
    virDrvOpenStatus result = VIR_DRV_OPEN_ERROR;
545
    esxPrivate *priv = NULL;
M
Matthias Bolte 已提交
546
    esxUtil_ParsedUri *parsedUri = NULL;
547
    char *potentialVCenterIpAddress = NULL;
M
Matthias Bolte 已提交
548
    char vCenterIpAddress[NI_MAXHOST] = "";
549

550
    /* Decline if the URI is NULL or the scheme is not one of {vpx|esx|gsx} */
551
    if (conn->uri == NULL || conn->uri->scheme == NULL ||
552 553
        (STRCASENEQ(conn->uri->scheme, "vpx") &&
         STRCASENEQ(conn->uri->scheme, "esx") &&
554
         STRCASENEQ(conn->uri->scheme, "gsx"))) {
555 556 557
        return VIR_DRV_OPEN_DECLINED;
    }

M
Matthias Bolte 已提交
558 559 560
    /* Decline URIs without server part, or missing auth */
    if (conn->uri->server == NULL || auth == NULL || auth->cb == NULL) {
        return VIR_DRV_OPEN_DECLINED;
561 562 563 564
    }

    /* Allocate per-connection private data */
    if (VIR_ALLOC(priv) < 0) {
565
        virReportOOMError();
M
Matthias Bolte 已提交
566
        goto cleanup;
567 568
    }

M
Matthias Bolte 已提交
569
    if (esxUtil_ParseUri(&parsedUri, conn->uri) < 0) {
570 571 572
        goto cleanup;
    }

M
Matthias Bolte 已提交
573 574
    priv->transport = parsedUri->transport;
    parsedUri->transport = NULL;
575

M
Matthias Bolte 已提交
576 577
    priv->maxVcpus = -1;
    priv->supportsVMotion = esxVI_Boolean_Undefined;
578
    priv->supportsLongMode = esxVI_Boolean_Undefined;
M
Matthias Bolte 已提交
579 580
    priv->autoAnswer = parsedUri->autoAnswer ? esxVI_Boolean_True
                                             : esxVI_Boolean_False;
581 582
    priv->usedCpuTimeCounterId = -1;

M
Matthias Bolte 已提交
583 584 585 586 587 588 589
    /*
     * 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) {
590 591
        if (STRCASEEQ(conn->uri->scheme, "vpx") ||
            STRCASEEQ(conn->uri->scheme, "esx")) {
M
Matthias Bolte 已提交
592 593 594 595 596 597 598 599 600 601 602
            if (STRCASEEQ(priv->transport, "https")) {
                conn->uri->port = 443;
            } else {
                conn->uri->port = 80;
            }
        } else { /* GSX */
            if (STRCASEEQ(priv->transport, "https")) {
                conn->uri->port = 8333;
            } else {
                conn->uri->port = 8222;
            }
603
        }
M
Matthias Bolte 已提交
604
    }
605

606 607 608 609
    if (STRCASEEQ(conn->uri->scheme, "esx") ||
        STRCASEEQ(conn->uri->scheme, "gsx")) {
        /* Connect to host */
        if (esxConnectToHost(priv, auth, conn->uri->server, conn->uri->port,
M
Matthias Bolte 已提交
610
                             conn->uri->user, parsedUri,
611 612 613 614
                             STRCASEEQ(conn->uri->scheme, "esx")
                               ? esxVI_ProductVersion_ESX
                               : esxVI_ProductVersion_GSX,
                             &potentialVCenterIpAddress) < 0) {
M
Matthias Bolte 已提交
615
            goto cleanup;
616
        }
617

618
        /* Connect to vCenter */
M
Matthias Bolte 已提交
619 620
        if (parsedUri->vCenter != NULL) {
            if (STREQ(parsedUri->vCenter, "*")) {
621 622 623
                if (potentialVCenterIpAddress == NULL) {
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                              _("This host is not managed by a vCenter"));
M
Matthias Bolte 已提交
624
                    goto cleanup;
625 626
                }

627 628 629 630 631 632 633 634
                if (virStrcpyStatic(vCenterIpAddress,
                                    potentialVCenterIpAddress) == NULL) {
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                              _("vCenter IP address %s too big for destination"),
                              potentialVCenterIpAddress);
                    goto cleanup;
                }
            } else {
M
Matthias Bolte 已提交
635
                if (esxUtil_ResolveHostname(parsedUri->vCenter,
636 637 638
                                            vCenterIpAddress, NI_MAXHOST) < 0) {
                    goto cleanup;
                }
639

640 641
                if (potentialVCenterIpAddress != NULL &&
                    STRNEQ(vCenterIpAddress, potentialVCenterIpAddress)) {
642
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
643 644 645
                              _("This host is managed by a vCenter with IP "
                                "address %s, but a mismachting vCenter '%s' "
                                "(%s) has been specified"),
M
Matthias Bolte 已提交
646
                              potentialVCenterIpAddress, parsedUri->vCenter,
647
                              vCenterIpAddress);
M
Matthias Bolte 已提交
648
                    goto cleanup;
649 650
                }
            }
651

652
            if (esxConnectToVCenter(priv, auth, vCenterIpAddress,
653 654
                                    conn->uri->port, NULL,
                                    priv->host->ipAddress, parsedUri) < 0) {
655 656
                goto cleanup;
            }
657 658
        }

659 660 661 662
        priv->primary = priv->host;
    } else { /* VPX */
        /* Connect to vCenter */
        if (esxConnectToVCenter(priv, auth, conn->uri->server, conn->uri->port,
663
                                conn->uri->user, NULL, parsedUri) < 0) {
M
Matthias Bolte 已提交
664
            goto cleanup;
665 666
        }

667
        priv->primary = priv->vCenter;
668 669 670
    }

    conn->privateData = priv;
671

M
Matthias Bolte 已提交
672
    /* Setup capabilities */
673
    priv->caps = esxCapsInit(priv);
674

M
Matthias Bolte 已提交
675
    if (priv->caps == NULL) {
M
Matthias Bolte 已提交
676
        goto cleanup;
677 678
    }

M
Matthias Bolte 已提交
679
    result = VIR_DRV_OPEN_SUCCESS;
680

M
Matthias Bolte 已提交
681 682
  cleanup:
    if (result == VIR_DRV_OPEN_ERROR && priv != NULL) {
683
        esxVI_Context_Free(&priv->host);
M
Matthias Bolte 已提交
684
        esxVI_Context_Free(&priv->vCenter);
685

686 687
        virCapabilitiesFree(priv->caps);

M
Matthias Bolte 已提交
688
        VIR_FREE(priv->transport);
689 690 691
        VIR_FREE(priv);
    }

M
Matthias Bolte 已提交
692
    esxUtil_FreeParsedUri(&parsedUri);
693
    VIR_FREE(potentialVCenterIpAddress);
694

M
Matthias Bolte 已提交
695
    return result;
696 697 698 699 700 701 702
}



static int
esxClose(virConnectPtr conn)
{
M
Matthias Bolte 已提交
703
    esxPrivate *priv = conn->privateData;
E
Eric Blake 已提交
704
    int result = 0;
705

706 707 708 709 710
    if (priv->host != NULL) {
        if (esxVI_EnsureSession(priv->host) < 0 ||
            esxVI_Logout(priv->host) < 0) {
            result = -1;
        }
711

712 713
        esxVI_Context_Free(&priv->host);
    }
714

M
Matthias Bolte 已提交
715
    if (priv->vCenter != NULL) {
E
Eric Blake 已提交
716 717 718 719
        if (esxVI_EnsureSession(priv->vCenter) < 0 ||
            esxVI_Logout(priv->vCenter) < 0) {
            result = -1;
        }
720

M
Matthias Bolte 已提交
721
        esxVI_Context_Free(&priv->vCenter);
722 723
    }

724 725
    virCapabilitiesFree(priv->caps);

726 727 728 729 730
    VIR_FREE(priv->transport);
    VIR_FREE(priv);

    conn->privateData = NULL;

E
Eric Blake 已提交
731
    return result;
732 733 734 735 736
}



static esxVI_Boolean
737
esxSupportsVMotion(esxPrivate *priv)
738 739 740 741
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;

M
Matthias Bolte 已提交
742 743
    if (priv->supportsVMotion != esxVI_Boolean_Undefined) {
        return priv->supportsVMotion;
744 745
    }

746
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
747
        return esxVI_Boolean_Undefined;
748 749
    }

750
    if (esxVI_String_AppendValueToList(&propertyNameList,
751
                                       "capability.vmotionSupported") < 0 ||
752 753
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
754
        goto cleanup;
755 756 757
    }

    if (hostSystem == NULL) {
758 759
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
760
        goto cleanup;
761 762
    }

763 764 765 766
    if (esxVI_GetBoolean(hostSystem, "capability.vmotionSupported",
                         &priv->supportsVMotion,
                         esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
767 768 769
    }

  cleanup:
M
Matthias Bolte 已提交
770 771 772 773
    /*
     * 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.
     */
774 775 776
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
777
    return priv->supportsVMotion;
778 779 780 781 782 783 784
}



static int
esxSupportsFeature(virConnectPtr conn, int feature)
{
M
Matthias Bolte 已提交
785
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
786
    esxVI_Boolean supportsVMotion = esxVI_Boolean_Undefined;
787 788 789

    switch (feature) {
      case VIR_DRV_FEATURE_MIGRATION_V1:
790
        supportsVMotion = esxSupportsVMotion(priv);
791

M
Matthias Bolte 已提交
792
        if (supportsVMotion == esxVI_Boolean_Undefined) {
793 794 795
            return -1;
        }

M
Matthias Bolte 已提交
796 797 798
        /* Migration is only possible via a vCenter and if VMotion is enabled */
        return priv->vCenter != NULL &&
               supportsVMotion == esxVI_Boolean_True ? 1 : 0;
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817

      default:
        return 0;
    }
}



static const char *
esxGetType(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    return "ESX";
}



static int
esxGetVersion(virConnectPtr conn, unsigned long *version)
{
M
Matthias Bolte 已提交
818
    esxPrivate *priv = conn->privateData;
819

820
    if (virParseVersionString(priv->primary->service->about->version,
821 822
                              version) < 0) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
823
                  _("Could not parse version number from '%s'"),
824
                  priv->primary->service->about->version);
825

826
        return -1;
827 828 829 830 831 832 833 834 835 836
    }

    return 0;
}



static char *
esxGetHostname(virConnectPtr conn)
{
M
Matthias Bolte 已提交
837
    esxPrivate *priv = conn->privateData;
838 839 840 841 842 843 844
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    const char *hostName = NULL;
    const char *domainName = NULL;
    char *complete = NULL;

845
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
846
        return NULL;
847 848 849
    }

    if (esxVI_String_AppendValueListToList
850
          (&propertyNameList,
851 852
           "config.network.dnsConfig.hostName\0"
           "config.network.dnsConfig.domainName\0") < 0 ||
853 854
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
855
        goto cleanup;
856 857 858
    }

    if (hostSystem == NULL) {
859 860
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
861
        goto cleanup;
862 863 864 865 866 867
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name,
                  "config.network.dnsConfig.hostName")) {
868
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
869
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
870
                goto cleanup;
871 872 873 874 875
            }

            hostName = dynamicProperty->val->string;
        } else if (STREQ(dynamicProperty->name,
                         "config.network.dnsConfig.domainName")) {
876
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
877
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
878
                goto cleanup;
879 880 881 882 883 884 885 886
            }

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

M
Matthias Bolte 已提交
887
    if (hostName == NULL || strlen(hostName) < 1) {
888 889
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Missing or empty 'hostName' property"));
M
Matthias Bolte 已提交
890
        goto cleanup;
891 892
    }

M
Matthias Bolte 已提交
893
    if (domainName == NULL || strlen(domainName) < 1) {
894
        complete = strdup(hostName);
895

896
        if (complete == NULL) {
897
            virReportOOMError();
M
Matthias Bolte 已提交
898
            goto cleanup;
899 900 901
        }
    } else {
        if (virAsprintf(&complete, "%s.%s", hostName, domainName) < 0) {
902
            virReportOOMError();
M
Matthias Bolte 已提交
903
            goto cleanup;
904
        }
905 906 907
    }

  cleanup:
M
Matthias Bolte 已提交
908 909 910 911 912
    /*
     * If we goto cleanup in case of an error then complete is still NULL,
     * either strdup returned NULL or virAsprintf failed. When virAsprintf
     * fails it guarantees setting complete to NULL
     */
913 914 915 916 917 918 919 920 921 922 923
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return complete;
}



static int
esxNodeGetInfo(virConnectPtr conn, virNodeInfoPtr nodeinfo)
{
M
Matthias Bolte 已提交
924
    int result = -1;
M
Matthias Bolte 已提交
925
    esxPrivate *priv = conn->privateData;
926 927 928 929 930 931 932 933 934 935 936
    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;

M
Matthias Bolte 已提交
937
    memset(nodeinfo, 0, sizeof (*nodeinfo));
938

939
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
940
        return -1;
941 942
    }

943
    if (esxVI_String_AppendValueListToList(&propertyNameList,
944 945 946 947 948 949 950
                                           "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 ||
951 952
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
953
        goto cleanup;
954 955 956
    }

    if (hostSystem == NULL) {
957 958
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
959
        goto cleanup;
960 961 962 963 964
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuInfo.hz")) {
965
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
966
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
967
                goto cleanup;
968 969 970 971 972
            }

            cpuInfo_hz = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuCores")) {
973
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
974
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
975
                goto cleanup;
976 977 978 979 980
            }

            cpuInfo_numCpuCores = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuPackages")) {
981
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
982
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
983
                goto cleanup;
984 985 986 987 988
            }

            cpuInfo_numCpuPackages = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuThreads")) {
989
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
990
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
991
                goto cleanup;
992 993 994 995
            }

            cpuInfo_numCpuThreads = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name, "hardware.memorySize")) {
996
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
997
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
998
                goto cleanup;
999 1000 1001 1002 1003
            }

            memorySize = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.numaInfo.numNodes")) {
1004
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1005
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1006
                goto cleanup;
1007 1008 1009 1010 1011
            }

            numaInfo_numNodes = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "summary.hardware.cpuModel")) {
1012
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1013
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1014
                goto cleanup;
1015 1016 1017 1018 1019 1020
            }

            ptr = dynamicProperty->val->string;

            /* Strip the string to fit more relevant information in 32 chars */
            while (*ptr != '\0') {
M
Matthias Bolte 已提交
1021 1022
                if (STRPREFIX(ptr, "  ")) {
                    memmove(ptr, ptr + 1, strlen(ptr + 1) + 1);
1023
                    continue;
1024
                } else if (STRPREFIX(ptr, "(R)") || STRPREFIX(ptr, "(C)")) {
M
Matthias Bolte 已提交
1025
                    memmove(ptr, ptr + 3, strlen(ptr + 3) + 1);
1026
                    continue;
1027 1028 1029
                } else if (STRPREFIX(ptr, "(TM)")) {
                    memmove(ptr, ptr + 4, strlen(ptr + 4) + 1);
                    continue;
1030 1031 1032 1033 1034
                }

                ++ptr;
            }

C
Chris Lalancette 已提交
1035 1036 1037
            if (virStrncpy(nodeinfo->model, dynamicProperty->val->string,
                           sizeof(nodeinfo->model) - 1,
                           sizeof(nodeinfo->model)) == NULL) {
1038
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1039
                          _("CPU Model %s too long for destination"),
C
Chris Lalancette 已提交
1040
                          dynamicProperty->val->string);
M
Matthias Bolte 已提交
1041
                goto cleanup;
C
Chris Lalancette 已提交
1042
            }
1043 1044 1045 1046 1047 1048 1049
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    nodeinfo->memory = memorySize / 1024; /* Scale from bytes to kilobytes */
    nodeinfo->cpus = cpuInfo_numCpuCores;
1050
    nodeinfo->mhz = cpuInfo_hz / (1000 * 1000); /* Scale from hz to mhz */
1051 1052 1053 1054 1055 1056 1057 1058 1059
    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 已提交
1060 1061
    result = 0;

1062 1063 1064 1065 1066 1067 1068 1069 1070
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



1071 1072 1073
static char *
esxGetCapabilities(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1074
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1075
    char *xml = virCapabilitiesFormatXML(priv->caps);
1076 1077

    if (xml == NULL) {
1078
        virReportOOMError();
1079 1080 1081 1082 1083 1084 1085 1086
        return NULL;
    }

    return xml;
}



1087 1088 1089
static int
esxListDomains(virConnectPtr conn, int *ids, int maxids)
{
M
Matthias Bolte 已提交
1090
    bool success = false;
M
Matthias Bolte 已提交
1091
    esxPrivate *priv = conn->privateData;
1092 1093 1094 1095 1096 1097 1098
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;

    if (ids == NULL || maxids < 0) {
1099 1100
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
1101 1102 1103 1104 1105 1106
    }

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

1107
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1108
        return -1;
1109 1110
    }

1111
    if (esxVI_String_AppendValueToList(&propertyNameList,
1112
                                       "runtime.powerState") < 0 ||
1113 1114
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1115
        goto cleanup;
1116 1117 1118 1119
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
1120
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1121
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1122
            goto cleanup;
1123 1124 1125 1126 1127 1128 1129 1130 1131
        }

        if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

        if (esxUtil_ParseVirtualMachineIDString(virtualMachine->obj->value,
                                                &ids[count]) < 0 ||
            ids[count] <= 0) {
1132
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1133
                      _("Failed to parse positive integer from '%s'"),
1134
                      virtualMachine->obj->value);
M
Matthias Bolte 已提交
1135
            goto cleanup;
1136 1137 1138 1139 1140 1141 1142 1143 1144
        }

        count++;

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

M
Matthias Bolte 已提交
1145 1146
    success = true;

1147 1148 1149 1150
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
1151
    return success ? count : -1;
1152 1153 1154 1155 1156 1157 1158
}



static int
esxNumberOfDomains(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1159
    esxPrivate *priv = conn->privateData;
1160

1161
    if (esxVI_EnsureSession(priv->primary) < 0) {
1162 1163 1164
        return -1;
    }

1165
    return esxVI_LookupNumberOfDomainsByPowerState
1166
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn,
1167 1168 1169 1170 1171 1172 1173 1174
              esxVI_Boolean_False);
}



static virDomainPtr
esxDomainLookupByID(virConnectPtr conn, int id)
{
M
Matthias Bolte 已提交
1175
    esxPrivate *priv = conn->privateData;
1176 1177 1178 1179
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
M
Matthias Bolte 已提交
1180 1181 1182
    int id_candidate = -1;
    char *name_candidate = NULL;
    unsigned char uuid_candidate[VIR_UUID_BUFLEN];
1183 1184
    virDomainPtr domain = NULL;

1185
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1186
        return NULL;
1187 1188
    }

1189
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1190
                                           "configStatus\0"
1191 1192
                                           "name\0"
                                           "runtime.powerState\0"
1193
                                           "config.uuid\0") < 0 ||
1194 1195
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1196
        goto cleanup;
1197 1198 1199 1200
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
1201
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1202
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1203
            goto cleanup;
1204 1205 1206 1207 1208 1209 1210
        }

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

M
Matthias Bolte 已提交
1211
        VIR_FREE(name_candidate);
1212

1213
        if (esxVI_GetVirtualMachineIdentity(virtualMachine,
M
Matthias Bolte 已提交
1214 1215
                                            &id_candidate, &name_candidate,
                                            uuid_candidate) < 0) {
M
Matthias Bolte 已提交
1216
            goto cleanup;
1217 1218
        }

M
Matthias Bolte 已提交
1219
        if (id != id_candidate) {
1220 1221 1222
            continue;
        }

M
Matthias Bolte 已提交
1223
        domain = virGetDomain(conn, name_candidate, uuid_candidate);
1224 1225

        if (domain == NULL) {
M
Matthias Bolte 已提交
1226
            goto cleanup;
1227 1228 1229 1230 1231 1232 1233 1234
        }

        domain->id = id;

        break;
    }

    if (domain == NULL) {
1235
        ESX_ERROR(VIR_ERR_NO_DOMAIN, _("No domain with ID %d"), id);
1236 1237 1238 1239 1240
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
M
Matthias Bolte 已提交
1241
    VIR_FREE(name_candidate);
1242 1243 1244 1245 1246 1247 1248 1249 1250

    return domain;
}



static virDomainPtr
esxDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
M
Matthias Bolte 已提交
1251
    esxPrivate *priv = conn->privateData;
1252 1253 1254
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1255 1256
    int id = -1;
    char *name = NULL;
1257 1258
    virDomainPtr domain = NULL;

1259
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1260
        return NULL;
1261 1262
    }

1263
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1264
                                           "name\0"
1265
                                           "runtime.powerState\0") < 0 ||
1266
        esxVI_LookupVirtualMachineByUuid(priv->primary, uuid, propertyNameList,
1267
                                         &virtualMachine,
M
Matthias Bolte 已提交
1268
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1269 1270
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, &name, NULL) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1271
        goto cleanup;
1272 1273
    }

1274
    domain = virGetDomain(conn, name, uuid);
1275 1276

    if (domain == NULL) {
M
Matthias Bolte 已提交
1277
        goto cleanup;
1278
    }
1279

1280 1281 1282 1283 1284
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1285 1286 1287 1288
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1289 1290
    esxVI_ObjectContent_Free(&virtualMachine);
    VIR_FREE(name);
1291 1292 1293 1294 1295 1296 1297 1298 1299

    return domain;
}



static virDomainPtr
esxDomainLookupByName(virConnectPtr conn, const char *name)
{
M
Matthias Bolte 已提交
1300
    esxPrivate *priv = conn->privateData;
1301 1302 1303
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1304 1305
    int id = -1;
    unsigned char uuid[VIR_UUID_BUFLEN];
1306 1307
    virDomainPtr domain = NULL;

1308
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1309
        return NULL;
1310 1311
    }

1312
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1313
                                           "configStatus\0"
1314
                                           "runtime.powerState\0"
1315
                                           "config.uuid\0") < 0 ||
1316
        esxVI_LookupVirtualMachineByName(priv->primary, name, propertyNameList,
1317 1318
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
1319
        goto cleanup;
1320 1321
    }

1322
    if (virtualMachine == NULL) {
1323
        ESX_ERROR(VIR_ERR_NO_DOMAIN, _("No domain with name '%s'"), name);
M
Matthias Bolte 已提交
1324
        goto cleanup;
1325
    }
1326 1327


M
Matthias Bolte 已提交
1328 1329 1330
    if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, uuid) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
1331
    }
1332

1333
    domain = virGetDomain(conn, name, uuid);
1334

1335
    if (domain == NULL) {
M
Matthias Bolte 已提交
1336
        goto cleanup;
1337 1338
    }

1339 1340 1341 1342 1343
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1344 1345 1346 1347
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1348
    esxVI_ObjectContent_Free(&virtualMachine);
1349 1350 1351 1352 1353 1354 1355 1356 1357

    return domain;
}



static int
esxDomainSuspend(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1358
    int result = -1;
M
Matthias Bolte 已提交
1359
    esxPrivate *priv = domain->conn->privateData;
1360 1361 1362 1363 1364 1365
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1366
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1367
        return -1;
1368 1369
    }

1370
    if (esxVI_String_AppendValueToList(&propertyNameList,
1371
                                       "runtime.powerState") < 0 ||
1372
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1373
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1374 1375
           priv->autoAnswer) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1376
        goto cleanup;
1377 1378 1379
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1380 1381
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1382
        goto cleanup;
1383 1384
    }

1385 1386
    if (esxVI_SuspendVM_Task(priv->primary, virtualMachine->obj, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1387
                                    esxVI_Occurrence_RequiredItem,
1388
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
1389
        goto cleanup;
1390 1391 1392
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1393
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not suspend domain"));
M
Matthias Bolte 已提交
1394
        goto cleanup;
1395 1396
    }

M
Matthias Bolte 已提交
1397 1398
    result = 0;

1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainResume(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1412
    int result = -1;
M
Matthias Bolte 已提交
1413
    esxPrivate *priv = domain->conn->privateData;
1414 1415 1416 1417 1418 1419
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1420
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1421
        return -1;
1422 1423
    }

1424
    if (esxVI_String_AppendValueToList(&propertyNameList,
1425
                                       "runtime.powerState") < 0 ||
1426
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1427
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1428 1429
           priv->autoAnswer) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1430
        goto cleanup;
1431 1432 1433
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended) {
1434
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not suspended"));
M
Matthias Bolte 已提交
1435
        goto cleanup;
1436 1437
    }

1438
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
1439
                             &task) < 0 ||
1440
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1441
                                    esxVI_Occurrence_RequiredItem,
1442
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
1443
        goto cleanup;
1444 1445 1446
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1447
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not resume domain"));
M
Matthias Bolte 已提交
1448
        goto cleanup;
1449 1450
    }

M
Matthias Bolte 已提交
1451 1452
    result = 0;

1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainShutdown(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1466
    int result = -1;
M
Matthias Bolte 已提交
1467
    esxPrivate *priv = domain->conn->privateData;
1468 1469 1470 1471
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1472
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1473
        return -1;
1474 1475
    }

1476
    if (esxVI_String_AppendValueToList(&propertyNameList,
1477
                                       "runtime.powerState") < 0 ||
1478
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1479
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1480
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1481
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1482
        goto cleanup;
1483 1484 1485
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1486 1487
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1488
        goto cleanup;
1489 1490
    }

1491
    if (esxVI_ShutdownGuest(priv->primary, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1492
        goto cleanup;
1493 1494
    }

M
Matthias Bolte 已提交
1495 1496
    result = 0;

1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
esxDomainReboot(virDomainPtr domain, unsigned int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
1509
    int result = -1;
M
Matthias Bolte 已提交
1510
    esxPrivate *priv = domain->conn->privateData;
1511 1512 1513 1514
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1515
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1516
        return -1;
1517 1518
    }

1519
    if (esxVI_String_AppendValueToList(&propertyNameList,
1520
                                       "runtime.powerState") < 0 ||
1521
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1522
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1523
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1524
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1525
        goto cleanup;
1526 1527 1528
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1529 1530
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1531
        goto cleanup;
1532 1533
    }

1534
    if (esxVI_RebootGuest(priv->primary, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1535
        goto cleanup;
1536 1537
    }

M
Matthias Bolte 已提交
1538 1539
    result = 0;

1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
esxDomainDestroy(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1552
    int result = -1;
M
Matthias Bolte 已提交
1553
    esxPrivate *priv = domain->conn->privateData;
1554
    esxVI_Context *ctx = NULL;
1555 1556 1557 1558 1559 1560
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1561 1562 1563 1564 1565 1566
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

1567
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
1568
        return -1;
1569 1570
    }

1571
    if (esxVI_String_AppendValueToList(&propertyNameList,
1572
                                       "runtime.powerState") < 0 ||
1573
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1574
          (ctx, domain->uuid, propertyNameList, &virtualMachine,
1575
           priv->autoAnswer) < 0 ||
1576
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1577
        goto cleanup;
1578 1579 1580
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1581 1582
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1583
        goto cleanup;
1584 1585
    }

1586
    if (esxVI_PowerOffVM_Task(ctx, virtualMachine->obj, &task) < 0 ||
1587 1588 1589
        esxVI_WaitForTaskCompletion(ctx, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
1590
        goto cleanup;
1591 1592 1593
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1594
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not destroy domain"));
M
Matthias Bolte 已提交
1595
        goto cleanup;
1596 1597
    }

1598
    domain->id = -1;
M
Matthias Bolte 已提交
1599 1600
    result = 0;

1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static char *
1612
esxDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED)
1613
{
1614 1615 1616
    char *osType = strdup("hvm");

    if (osType == NULL) {
1617
        virReportOOMError();
1618 1619 1620 1621
        return NULL;
    }

    return osType;
1622 1623 1624 1625 1626 1627 1628
}



static unsigned long
esxDomainGetMaxMemory(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1629
    esxPrivate *priv = domain->conn->privateData;
1630 1631 1632 1633 1634
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    unsigned long memoryMB = 0;

1635
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1636
        return 0;
1637 1638
    }

1639
    if (esxVI_String_AppendValueToList(&propertyNameList,
1640
                                       "config.hardware.memoryMB") < 0 ||
1641
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1642
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1643
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
1644
        goto cleanup;
1645 1646 1647 1648 1649
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
1650
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1651
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1652
                goto cleanup;
1653 1654 1655
            }

            if (dynamicProperty->val->int32 < 0) {
1656 1657
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                          _("Got invalid memory size %d"),
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
                          dynamicProperty->val->int32);
            } else {
                memoryMB = dynamicProperty->val->int32;
            }

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

  cleanup:
    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 已提交
1681
    int result = -1;
M
Matthias Bolte 已提交
1682
    esxPrivate *priv = domain->conn->privateData;
1683 1684 1685 1686 1687
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1688
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1689
        return -1;
1690 1691
    }

1692
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1693
          (priv->primary, domain->uuid, NULL, &virtualMachine,
1694
           priv->autoAnswer) < 0 ||
1695 1696
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Long_Alloc(&spec->memoryMB) < 0) {
M
Matthias Bolte 已提交
1697
        goto cleanup;
1698 1699 1700 1701 1702
    }

    spec->memoryMB->value =
      memory / 1024; /* Scale from kilobytes to megabytes */

1703
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
1704
                              &task) < 0 ||
1705
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1706
                                    esxVI_Occurrence_RequiredItem,
1707
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
1708
        goto cleanup;
1709 1710 1711
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1712
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1713
                  _("Could not set max-memory to %lu kilobytes"), memory);
M
Matthias Bolte 已提交
1714
        goto cleanup;
1715 1716
    }

M
Matthias Bolte 已提交
1717 1718
    result = 0;

1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainSetMemory(virDomainPtr domain, unsigned long memory)
{
M
Matthias Bolte 已提交
1732
    int result = -1;
M
Matthias Bolte 已提交
1733
    esxPrivate *priv = domain->conn->privateData;
1734 1735 1736 1737 1738
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1739
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1740
        return -1;
1741 1742
    }

1743
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1744
          (priv->primary, domain->uuid, NULL, &virtualMachine,
1745
           priv->autoAnswer) < 0 ||
1746 1747 1748
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0 ||
        esxVI_Long_Alloc(&spec->memoryAllocation->limit) < 0) {
M
Matthias Bolte 已提交
1749
        goto cleanup;
1750 1751 1752 1753 1754
    }

    spec->memoryAllocation->limit->value =
      memory / 1024; /* Scale from kilobytes to megabytes */

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

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1764
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1765
                  _("Could not set memory to %lu kilobytes"), memory);
M
Matthias Bolte 已提交
1766
        goto cleanup;
1767 1768
    }

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

1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info)
{
M
Matthias Bolte 已提交
1784
    int result = -1;
M
Matthias Bolte 已提交
1785
    esxPrivate *priv = domain->conn->privateData;
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int64_t memory_limit = -1;
    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;
1798 1799
    esxVI_PerfEntityMetricBase *perfEntityMetricBase = NULL;
    esxVI_PerfEntityMetricBase *perfEntityMetricBaseList = NULL;
1800 1801 1802 1803
    esxVI_PerfEntityMetric *perfEntityMetric = NULL;
    esxVI_PerfMetricIntSeries *perfMetricIntSeries = NULL;
    esxVI_Long *value = NULL;

M
Matthias Bolte 已提交
1804 1805
    memset(info, 0, sizeof (*info));

1806
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1807
        return -1;
1808 1809
    }

1810
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1811 1812 1813 1814
                                           "runtime.powerState\0"
                                           "config.hardware.memoryMB\0"
                                           "config.hardware.numCPU\0"
                                           "config.memoryAllocation.limit\0") < 0 ||
1815
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1816
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1817
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
1818
        goto cleanup;
1819 1820 1821 1822 1823 1824 1825 1826
    }

    info->state = VIR_DOMAIN_NOSTATE;

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.powerState")) {
            if (esxVI_VirtualMachinePowerState_CastFromAnyType
1827
                  (dynamicProperty->val, &powerState) < 0) {
M
Matthias Bolte 已提交
1828
                goto cleanup;
1829 1830
            }

1831 1832
            info->state = esxVI_VirtualMachinePowerState_ConvertToLibvirt
                            (powerState);
1833
        } else if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
1834
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1835
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1836
                goto cleanup;
1837 1838 1839 1840
            }

            info->maxMem = dynamicProperty->val->int32 * 1024; /* Scale from megabyte to kilobyte */
        } else if (STREQ(dynamicProperty->name, "config.hardware.numCPU")) {
1841
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1842
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1843
                goto cleanup;
1844 1845 1846 1847 1848
            }

            info->nrVirtCpu = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "config.memoryAllocation.limit")) {
1849
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1850
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1851
                goto cleanup;
1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867
            }

            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;

    /* Verify the cached 'used CPU time' performance counter ID */
1868 1869 1870 1871 1872 1873
    /* FIXME: Currently no host for a vpx:// connection */
    if (priv->host != NULL) {
        if (info->state == VIR_DOMAIN_RUNNING && priv->usedCpuTimeCounterId >= 0) {
            if (esxVI_Int_Alloc(&counterId) < 0) {
                goto cleanup;
            }
1874

1875
            counterId->value = priv->usedCpuTimeCounterId;
1876

1877 1878 1879
            if (esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                goto cleanup;
            }
1880

1881 1882 1883 1884
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfo) < 0) {
                goto cleanup;
            }
1885

1886 1887 1888 1889 1890
            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);
1891

1892 1893 1894 1895 1896
                priv->usedCpuTimeCounterId = -1;
            }

            esxVI_Int_Free(&counterIdList);
            esxVI_PerfCounterInfo_Free(&perfCounterInfo);
1897 1898
        }

1899 1900 1901 1902 1903 1904 1905 1906 1907 1908
        /*
         * 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;
            }
1909

1910 1911 1912 1913
            for (perfMetricId = perfMetricIdList; perfMetricId != NULL;
                 perfMetricId = perfMetricId->_next) {
                VIR_DEBUG("perfMetricId counterId %d, instance '%s'",
                          perfMetricId->counterId->value, perfMetricId->instance);
1914

1915
                counterId = NULL;
1916

1917 1918 1919 1920 1921
                if (esxVI_Int_DeepCopy(&counterId, perfMetricId->counterId) < 0 ||
                    esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                    goto cleanup;
                }
            }
1922

1923 1924
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfoList) < 0) {
M
Matthias Bolte 已提交
1925
                goto cleanup;
1926 1927
            }

1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
            for (perfCounterInfo = perfCounterInfoList; perfCounterInfo != NULL;
                 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;
                }
1945 1946
            }

1947 1948 1949
            if (priv->usedCpuTimeCounterId < 0) {
                VIR_WARN0("Could not find 'used CPU time' performance counter");
            }
1950 1951
        }

1952 1953 1954 1955 1956 1957
        /*
         * 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);
1958

1959 1960 1961 1962 1963 1964
            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;
            }
1965

1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978
            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) {
                querySpec->entity = NULL;
                querySpec->metricId->instance = NULL;
                querySpec->format = NULL;
                goto cleanup;
            }
1979

1980 1981 1982 1983
            for (perfEntityMetricBase = perfEntityMetricBaseList;
                 perfEntityMetricBase != NULL;
                 perfEntityMetricBase = perfEntityMetricBase->_next) {
                VIR_DEBUG0("perfEntityMetric ...");
1984

1985 1986
                perfEntityMetric =
                  esxVI_PerfEntityMetric_DynamicCast(perfEntityMetricBase);
1987

1988 1989 1990
                if (perfMetricIntSeries == NULL) {
                    VIR_ERROR0(_("QueryPerf returned object with unexpected type"));
                }
1991

1992 1993
                perfMetricIntSeries =
                  esxVI_PerfMetricIntSeries_DynamicCast(perfEntityMetric->value);
1994

1995 1996 1997
                if (perfMetricIntSeries == NULL) {
                    VIR_ERROR0(_("QueryPerf returned object with unexpected type"));
                }
1998

1999 2000 2001
                for (; perfMetricIntSeries != NULL;
                     perfMetricIntSeries = perfMetricIntSeries->_next) {
                    VIR_DEBUG0("perfMetricIntSeries ...");
2002

2003 2004 2005 2006 2007
                    for (value = perfMetricIntSeries->value;
                         value != NULL;
                         value = value->_next) {
                        VIR_DEBUG("value %lld", (long long int)value->value);
                    }
2008 2009 2010
                }
            }

2011 2012 2013
            querySpec->entity = NULL;
            querySpec->metricId->instance = NULL;
            querySpec->format = NULL;
2014

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

2017 2018 2019 2020 2021
            /*
             * FIXME: Cannot map between realtive used-cpu-time and absolute
             *        info->cpuTime
             */
        }
2022 2023
    }

M
Matthias Bolte 已提交
2024 2025
    result = 0;

2026 2027 2028 2029 2030 2031 2032
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_PerfMetricId_Free(&perfMetricIdList);
    esxVI_Int_Free(&counterIdList);
    esxVI_PerfCounterInfo_Free(&perfCounterInfoList);
    esxVI_PerfQuerySpec_Free(&querySpec);
2033
    esxVI_PerfEntityMetricBase_Free(&perfEntityMetricBaseList);
2034 2035 2036 2037 2038 2039 2040 2041 2042

    return result;
}



static int
esxDomainSetVcpus(virDomainPtr domain, unsigned int nvcpus)
{
M
Matthias Bolte 已提交
2043
    int result = -1;
M
Matthias Bolte 已提交
2044
    esxPrivate *priv = domain->conn->privateData;
M
Matthias Bolte 已提交
2045
    int maxVcpus;
2046 2047 2048 2049 2050 2051
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

    if (nvcpus < 1) {
2052 2053
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Requested number of virtual CPUs must at least be 1"));
M
Matthias Bolte 已提交
2054
        return -1;
2055 2056
    }

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

M
Matthias Bolte 已提交
2061
    maxVcpus = esxDomainGetMaxVcpus(domain);
2062

M
Matthias Bolte 已提交
2063
    if (maxVcpus < 0) {
M
Matthias Bolte 已提交
2064
        return -1;
2065 2066
    }

M
Matthias Bolte 已提交
2067
    if (nvcpus > maxVcpus) {
2068
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2069 2070
                  _("Requested number of virtual CPUs is greater than max "
                    "allowable number of virtual CPUs for the domain: %d > %d"),
M
Matthias Bolte 已提交
2071
                  nvcpus, maxVcpus);
M
Matthias Bolte 已提交
2072
        return -1;
2073 2074
    }

2075
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2076
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2077
           priv->autoAnswer) < 0 ||
2078 2079
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Int_Alloc(&spec->numCPUs) < 0) {
M
Matthias Bolte 已提交
2080
        goto cleanup;
2081 2082 2083 2084
    }

    spec->numCPUs->value = nvcpus;

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

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2094
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2095
                  _("Could not set number of virtual CPUs to %d"), nvcpus);
M
Matthias Bolte 已提交
2096
        goto cleanup;
2097 2098
    }

M
Matthias Bolte 已提交
2099 2100
    result = 0;

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

    return result;
}



static int
esxDomainGetMaxVcpus(virDomainPtr domain)
{
M
Matthias Bolte 已提交
2114
    esxPrivate *priv = domain->conn->privateData;
2115 2116 2117 2118
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

M
Matthias Bolte 已提交
2119 2120
    if (priv->maxVcpus > 0) {
        return priv->maxVcpus;
2121 2122
    }

M
Matthias Bolte 已提交
2123 2124
    priv->maxVcpus = -1;

2125
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2126
        return -1;
2127 2128
    }

2129
    if (esxVI_String_AppendValueToList(&propertyNameList,
2130
                                       "capability.maxSupportedVcpus") < 0 ||
2131 2132
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
2133
        goto cleanup;
2134 2135 2136
    }

    if (hostSystem == NULL) {
2137 2138
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
2139
        goto cleanup;
2140 2141 2142 2143 2144
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "capability.maxSupportedVcpus")) {
2145
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2146
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2147
                goto cleanup;
2148 2149
            }

M
Matthias Bolte 已提交
2150
            priv->maxVcpus = dynamicProperty->val->int32;
2151 2152 2153 2154 2155 2156 2157 2158 2159 2160
            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
2161
    return priv->maxVcpus;
2162 2163 2164 2165 2166 2167 2168
}



static char *
esxDomainDumpXML(virDomainPtr domain, int flags)
{
M
Matthias Bolte 已提交
2169
    esxPrivate *priv = domain->conn->privateData;
2170 2171
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
2172
    char *vmPathName = NULL;
2173
    char *datastoreName = NULL;
M
Matthias Bolte 已提交
2174 2175
    char *directoryName = NULL;
    char *fileName = NULL;
2176
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
2177 2178 2179 2180 2181
    char *url = NULL;
    char *vmx = NULL;
    virDomainDefPtr def = NULL;
    char *xml = NULL;

2182
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2183
        return NULL;
2184 2185
    }

2186
    if (esxVI_String_AppendValueToList(&propertyNameList,
2187
                                       "config.files.vmPathName") < 0 ||
2188
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2189
                                         propertyNameList, &virtualMachine,
2190 2191 2192
                                         esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_GetStringValue(virtualMachine, "config.files.vmPathName",
                             &vmPathName, esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2193
        goto cleanup;
2194 2195
    }

2196 2197
    if (esxUtil_ParseDatastorePath(vmPathName, &datastoreName, &directoryName,
                                   &fileName) < 0) {
M
Matthias Bolte 已提交
2198
        goto cleanup;
2199 2200
    }

2201 2202
    virBufferVSprintf(&buffer, "%s://%s:%d/folder/", priv->transport,
                      domain->conn->uri->server, domain->conn->uri->port);
M
Matthias Bolte 已提交
2203 2204 2205 2206 2207 2208 2209

    if (directoryName != NULL) {
        virBufferURIEncodeString(&buffer, directoryName);
        virBufferAddChar(&buffer, '/');
    }

    virBufferURIEncodeString(&buffer, fileName);
2210
    virBufferAddLit(&buffer, "?dcPath=");
2211
    virBufferURIEncodeString(&buffer, priv->primary->datacenter->name);
2212 2213 2214 2215
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
2216
        virReportOOMError();
M
Matthias Bolte 已提交
2217
        goto cleanup;
2218 2219
    }

2220 2221
    url = virBufferContentAndReset(&buffer);

2222
    if (esxVI_Context_DownloadFile(priv->primary, url, &vmx) < 0) {
M
Matthias Bolte 已提交
2223
        goto cleanup;
2224 2225
    }

2226 2227
    def = esxVMX_ParseConfig(priv->primary, priv->caps, vmx, datastoreName,
                             directoryName, priv->primary->productVersion);
2228 2229

    if (def != NULL) {
2230
        xml = virDomainDefFormat(def, flags);
2231 2232 2233
    }

  cleanup:
M
Matthias Bolte 已提交
2234 2235 2236 2237
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

2238 2239
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2240
    VIR_FREE(datastoreName);
M
Matthias Bolte 已提交
2241 2242
    VIR_FREE(directoryName);
    VIR_FREE(fileName);
2243 2244
    VIR_FREE(url);
    VIR_FREE(vmx);
2245
    virDomainDefFree(def);
2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256

    return xml;
}



static char *
esxDomainXMLFromNative(virConnectPtr conn, const char *nativeFormat,
                       const char *nativeConfig,
                       unsigned int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2257
    esxPrivate *priv = conn->privateData;
2258 2259 2260 2261
    virDomainDefPtr def = NULL;
    char *xml = NULL;

    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2262
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2263
                  _("Unsupported config format '%s'"), nativeFormat);
2264
        return NULL;
2265 2266
    }

2267 2268
    def = esxVMX_ParseConfig(priv->primary, priv->caps, nativeConfig, "?", "?",
                             priv->primary->productVersion);
2269 2270

    if (def != NULL) {
2271
        xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
2272 2273 2274 2275 2276 2277 2278 2279 2280
    }

    virDomainDefFree(def);

    return xml;
}



M
Matthias Bolte 已提交
2281 2282 2283 2284 2285
static char *
esxDomainXMLToNative(virConnectPtr conn, const char *nativeFormat,
                     const char *domainXml,
                     unsigned int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2286
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
2287 2288 2289 2290
    virDomainDefPtr def = NULL;
    char *vmx = NULL;

    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2291
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2292
                  _("Unsupported config format '%s'"), nativeFormat);
M
Matthias Bolte 已提交
2293 2294 2295
        return NULL;
    }

2296
    def = virDomainDefParseString(priv->caps, domainXml, 0);
M
Matthias Bolte 已提交
2297 2298 2299 2300 2301

    if (def == NULL) {
        return NULL;
    }

2302 2303
    vmx = esxVMX_FormatConfig(priv->primary, priv->caps, def,
                              priv->primary->productVersion);
M
Matthias Bolte 已提交
2304 2305 2306 2307 2308 2309 2310 2311

    virDomainDefFree(def);

    return vmx;
}



2312 2313 2314
static int
esxListDefinedDomains(virConnectPtr conn, char **const names, int maxnames)
{
M
Matthias Bolte 已提交
2315
    bool success = false;
M
Matthias Bolte 已提交
2316
    esxPrivate *priv = conn->privateData;
2317 2318 2319 2320 2321 2322
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;
2323
    int i;
2324 2325

    if (names == NULL || maxnames < 0) {
2326 2327
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
2328 2329 2330 2331 2332 2333
    }

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

2334
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2335
        return -1;
2336 2337
    }

2338
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2339 2340
                                           "name\0"
                                           "runtime.powerState\0") < 0 ||
2341 2342
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2343
        goto cleanup;
2344 2345 2346 2347
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
2348
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
2349
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
2350
            goto cleanup;
2351 2352 2353 2354 2355 2356 2357 2358 2359 2360
        }

        if (powerState == esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

        for (dynamicProperty = virtualMachine->propSet;
             dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "name")) {
2361
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2362
                                             esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
2363
                    goto cleanup;
2364 2365 2366 2367 2368
                }

                names[count] = strdup(dynamicProperty->val->string);

                if (names[count] == NULL) {
2369
                    virReportOOMError();
M
Matthias Bolte 已提交
2370
                    goto cleanup;
2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382
                }

                count++;
                break;
            }
        }

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

M
Matthias Bolte 已提交
2383
    success = true;
2384

M
Matthias Bolte 已提交
2385 2386 2387 2388 2389
  cleanup:
    if (! success) {
        for (i = 0; i < count; ++i) {
            VIR_FREE(names[i]);
        }
2390

M
Matthias Bolte 已提交
2391
        count = -1;
2392 2393
    }

M
Matthias Bolte 已提交
2394 2395
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
2396

M
Matthias Bolte 已提交
2397
    return count;
2398 2399 2400 2401 2402 2403 2404
}



static int
esxNumberOfDefinedDomains(virConnectPtr conn)
{
M
Matthias Bolte 已提交
2405
    esxPrivate *priv = conn->privateData;
2406

2407
    if (esxVI_EnsureSession(priv->primary) < 0) {
2408 2409 2410
        return -1;
    }

2411
    return esxVI_LookupNumberOfDomainsByPowerState
2412
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn,
2413 2414 2415 2416 2417 2418
              esxVI_Boolean_True);
}



static int
2419
esxDomainCreateWithFlags(virDomainPtr domain, unsigned int flags)
2420
{
M
Matthias Bolte 已提交
2421
    int result = -1;
M
Matthias Bolte 已提交
2422
    esxPrivate *priv = domain->conn->privateData;
2423 2424 2425
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
2426
    int id = -1;
2427 2428 2429
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

2430 2431
    virCheckFlags(0, -1);

2432
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2433
        return -1;
2434 2435
    }

2436
    if (esxVI_String_AppendValueToList(&propertyNameList,
2437
                                       "runtime.powerState") < 0 ||
2438
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2439
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
2440
           priv->autoAnswer) < 0 ||
2441 2442
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0) {
M
Matthias Bolte 已提交
2443
        goto cleanup;
2444 2445 2446
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2447 2448
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered off"));
M
Matthias Bolte 已提交
2449
        goto cleanup;
2450 2451
    }

2452
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
2453
                             &task) < 0 ||
2454
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2455
                                    esxVI_Occurrence_RequiredItem,
2456
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2457
        goto cleanup;
2458 2459 2460
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2461
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not start domain"));
M
Matthias Bolte 已提交
2462
        goto cleanup;
2463 2464
    }

2465
    domain->id = id;
M
Matthias Bolte 已提交
2466 2467
    result = 0;

2468 2469 2470 2471 2472 2473 2474 2475
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}

2476 2477 2478 2479 2480
static int
esxDomainCreate(virDomainPtr domain)
{
    return esxDomainCreateWithFlags(domain, 0);
}
2481

M
Matthias Bolte 已提交
2482 2483 2484
static virDomainPtr
esxDomainDefineXML(virConnectPtr conn, const char *xml ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2485
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
2486 2487
    virDomainDefPtr def = NULL;
    char *vmx = NULL;
2488 2489
    int i;
    virDomainDiskDefPtr disk = NULL;
M
Matthias Bolte 已提交
2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503
    esxVI_ObjectContent *virtualMachine = NULL;
    char *datastoreName = NULL;
    char *directoryName = NULL;
    char *fileName = NULL;
    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;
    virDomainPtr domain = NULL;

2504
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2505
        return NULL;
M
Matthias Bolte 已提交
2506 2507 2508
    }

    /* Parse domain XML */
2509
    def = virDomainDefParseString(priv->caps, xml,
M
Matthias Bolte 已提交
2510 2511 2512
                                  VIR_DOMAIN_XML_INACTIVE);

    if (def == NULL) {
M
Matthias Bolte 已提交
2513
        return NULL;
M
Matthias Bolte 已提交
2514 2515 2516
    }

    /* Check if an existing domain should be edited */
2517
    if (esxVI_LookupVirtualMachineByUuid(priv->primary, def->uuid, NULL,
M
Matthias Bolte 已提交
2518
                                         &virtualMachine,
M
Matthias Bolte 已提交
2519
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
2520
        goto cleanup;
M
Matthias Bolte 已提交
2521 2522 2523 2524
    }

    if (virtualMachine != NULL) {
        /* FIXME */
2525 2526 2527
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Domain already exists, editing existing domains is not "
                    "supported yet"));
M
Matthias Bolte 已提交
2528
        goto cleanup;
M
Matthias Bolte 已提交
2529 2530 2531
    }

    /* Build VMX from domain XML */
2532 2533
    vmx = esxVMX_FormatConfig(priv->primary, priv->caps, def,
                              priv->primary->productVersion);
M
Matthias Bolte 已提交
2534 2535

    if (vmx == NULL) {
M
Matthias Bolte 已提交
2536
        goto cleanup;
M
Matthias Bolte 已提交
2537 2538
    }

2539 2540 2541 2542 2543 2544 2545
    /*
     * Build VMX datastore URL. Use the source of the first file-based harddisk
     * to deduce the datastore and path for the VMX file. Don't just use the
     * first disk, because it may be CDROM disk and ISO images are normaly not
     * located in the virtual machine's directory. This approach to deduce the
     * datastore isn't perfect but should work in the majority of cases.
     */
M
Matthias Bolte 已提交
2546
    if (def->ndisks < 1) {
2547 2548 2549
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Domain XML doesn't contain any disks, cannot deduce "
                    "datastore and path for VMX file"));
M
Matthias Bolte 已提交
2550
        goto cleanup;
2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561
    }

    for (i = 0; i < def->ndisks; ++i) {
        if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK &&
            def->disks[i]->type == VIR_DOMAIN_DISK_TYPE_FILE) {
            disk = def->disks[i];
            break;
        }
    }

    if (disk == NULL) {
2562 2563 2564
        ESX_ERROR(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 已提交
2565
        goto cleanup;
M
Matthias Bolte 已提交
2566 2567
    }

2568
    if (disk->src == NULL) {
2569 2570 2571
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("First file-based harddisk has no source, cannot deduce "
                    "datastore and path for VMX file"));
M
Matthias Bolte 已提交
2572
        goto cleanup;
M
Matthias Bolte 已提交
2573 2574
    }

2575 2576
    if (esxUtil_ParseDatastorePath(disk->src, &datastoreName, &directoryName,
                                   &fileName) < 0) {
M
Matthias Bolte 已提交
2577
        goto cleanup;
M
Matthias Bolte 已提交
2578 2579
    }

2580
    if (! virFileHasSuffix(fileName, ".vmdk")) {
2581
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2582 2583
                  _("Expecting source '%s' of first file-based harddisk to "
                    "be a VMDK image"), disk->src);
M
Matthias Bolte 已提交
2584
        goto cleanup;
M
Matthias Bolte 已提交
2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596
    }

    virBufferVSprintf(&buffer, "%s://%s:%d/folder/", priv->transport,
                      conn->uri->server, conn->uri->port);

    if (directoryName != NULL) {
        virBufferURIEncodeString(&buffer, directoryName);
        virBufferAddChar(&buffer, '/');
    }

    virBufferURIEncodeString(&buffer, def->name);
    virBufferAddLit(&buffer, ".vmx?dcPath=");
2597
    virBufferURIEncodeString(&buffer, priv->primary->datacenter->name);
M
Matthias Bolte 已提交
2598 2599 2600 2601
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
2602
        virReportOOMError();
M
Matthias Bolte 已提交
2603
        goto cleanup;
M
Matthias Bolte 已提交
2604 2605 2606 2607 2608 2609 2610
    }

    url = virBufferContentAndReset(&buffer);

    if (directoryName != NULL) {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s/%s.vmx", datastoreName,
                        directoryName, def->name) < 0) {
2611
            virReportOOMError();
M
Matthias Bolte 已提交
2612
            goto cleanup;
M
Matthias Bolte 已提交
2613 2614 2615 2616
        }
    } else {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s.vmx", datastoreName,
                        def->name) < 0) {
2617
            virReportOOMError();
M
Matthias Bolte 已提交
2618
            goto cleanup;
M
Matthias Bolte 已提交
2619 2620 2621 2622 2623 2624 2625
        }
    }

    /* Check, if VMX file already exists */
    /* FIXME */

    /* Upload VMX file */
2626
    if (esxVI_Context_UploadFile(priv->primary, url, vmx) < 0) {
M
Matthias Bolte 已提交
2627
        goto cleanup;
M
Matthias Bolte 已提交
2628 2629 2630
    }

    /* Register the domain */
2631
    if (esxVI_RegisterVM_Task(priv->primary, priv->primary->datacenter->vmFolder,
M
Matthias Bolte 已提交
2632
                              datastoreRelatedPath, NULL, esxVI_Boolean_False,
2633 2634 2635 2636
                              priv->primary->computeResource->resourcePool,
                              priv->primary->hostSystem->_reference,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, def->uuid,
2637
                                    esxVI_Occurrence_OptionalItem,
2638
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2639
        goto cleanup;
M
Matthias Bolte 已提交
2640 2641 2642
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2643
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not define domain"));
M
Matthias Bolte 已提交
2644
        goto cleanup;
M
Matthias Bolte 已提交
2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655
    }

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

    if (domain != NULL) {
        domain->id = -1;
    }

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

  cleanup:
M
Matthias Bolte 已提交
2656 2657 2658 2659
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

M
Matthias Bolte 已提交
2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677
    virDomainDefFree(def);
    VIR_FREE(vmx);
    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
    VIR_FREE(fileName);
    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);

    return domain;
}



2678 2679 2680
static int
esxDomainUndefine(virDomainPtr domain)
{
M
Matthias Bolte 已提交
2681
    int result = -1;
M
Matthias Bolte 已提交
2682
    esxPrivate *priv = domain->conn->privateData;
2683
    esxVI_Context *ctx = NULL;
2684 2685 2686 2687
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

2688 2689 2690 2691 2692 2693
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

2694
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
2695
        return -1;
2696 2697
    }

2698
    if (esxVI_String_AppendValueToList(&propertyNameList,
2699
                                       "runtime.powerState") < 0 ||
2700 2701
        esxVI_LookupVirtualMachineByUuid(ctx, domain->uuid, propertyNameList,
                                         &virtualMachine,
M
Matthias Bolte 已提交
2702
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2703
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
2704
        goto cleanup;
2705 2706 2707 2708
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended &&
        powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2709 2710
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not suspended or powered off"));
M
Matthias Bolte 已提交
2711
        goto cleanup;
2712 2713
    }

2714
    if (esxVI_UnregisterVM(ctx, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
2715
        goto cleanup;
2716 2717
    }

M
Matthias Bolte 已提交
2718 2719
    result = 0;

2720 2721 2722 2723 2724 2725 2726 2727 2728
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740
/*
 * 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:
 *
 * - reservation (VIR_DOMAIN_SCHED_FIELD_LLONG >= 0, in megaherz)
 *
2741
 *   The amount of CPU resource that is guaranteed to be available to the domain.
2742 2743 2744 2745
 *
 *
 * - limit (VIR_DOMAIN_SCHED_FIELD_LLONG >= 0, or -1, in megaherz)
 *
2746 2747
 *   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
2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758
 *   utilization of the domain is unlimited. If the limit is not set to -1, it
 *   must be greater than or equal to the reservation.
 *
 *
 * - shares (VIR_DOMAIN_SCHED_FIELD_INT >= 0, or in {-1, -2, -3}, no unit)
 *
 *   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'.
 */
2759
static char *
2760
esxDomainGetSchedulerType(virDomainPtr domain ATTRIBUTE_UNUSED, int *nparams)
2761 2762 2763 2764
{
    char *type = strdup("allocation");

    if (type == NULL) {
2765
        virReportOOMError();
2766
        return NULL;
2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779
    }

    *nparams = 3; /* reservation, limit, shares */

    return type;
}



static int
esxDomainGetSchedulerParameters(virDomainPtr domain,
                                virSchedParameterPtr params, int *nparams)
{
M
Matthias Bolte 已提交
2780
    int result = -1;
M
Matthias Bolte 已提交
2781
    esxPrivate *priv = domain->conn->privateData;
2782 2783 2784 2785 2786 2787 2788 2789
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    unsigned int mask = 0;
    int i = 0;

    if (*nparams < 3) {
2790 2791
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Parameter array must have space for 3 items"));
M
Matthias Bolte 已提交
2792
        return -1;
2793 2794
    }

2795
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2796
        return -1;
2797 2798
    }

2799
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2800 2801 2802
                                           "config.cpuAllocation.reservation\0"
                                           "config.cpuAllocation.limit\0"
                                           "config.cpuAllocation.shares\0") < 0 ||
2803
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2804
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2805
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2806
        goto cleanup;
2807 2808 2809 2810 2811 2812
    }

    for (dynamicProperty = virtualMachine->propSet;
         dynamicProperty != NULL && mask != 7 && i < 3;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.cpuAllocation.reservation") &&
M
Matthias Bolte 已提交
2813
            ! (mask & (1 << 0))) {
2814 2815 2816 2817 2818
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "reservation");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_LLONG;

2819
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2820
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
2821
                goto cleanup;
2822 2823 2824 2825 2826 2827 2828
            }

            params[i].value.l = dynamicProperty->val->int64;
            mask |= 1 << 0;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.limit") &&
M
Matthias Bolte 已提交
2829
                   ! (mask & (1 << 1))) {
2830 2831 2832 2833 2834
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "limit");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_LLONG;

2835
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2836
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
2837
                goto cleanup;
2838 2839 2840 2841 2842 2843 2844
            }

            params[i].value.l = dynamicProperty->val->int64;
            mask |= 1 << 1;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.shares") &&
M
Matthias Bolte 已提交
2845
                   ! (mask & (1 << 2))) {
2846 2847 2848 2849 2850
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "shares");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_INT;

2851
            if (esxVI_SharesInfo_CastFromAnyType(dynamicProperty->val,
2852
                                                 &sharesInfo) < 0) {
M
Matthias Bolte 已提交
2853
                goto cleanup;
2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873
            }

            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:
2874
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2875
                          _("Shares level has unknown value %d"),
2876
                          (int)sharesInfo->level);
M
Matthias Bolte 已提交
2877
                goto cleanup;
2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889
            }

            esxVI_SharesInfo_Free(&sharesInfo);

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

    *nparams = i;
M
Matthias Bolte 已提交
2890
    result = 0;
2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904

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

    return result;
}



static int
esxDomainSetSchedulerParameters(virDomainPtr domain,
                                virSchedParameterPtr params, int nparams)
{
M
Matthias Bolte 已提交
2905
    int result = -1;
M
Matthias Bolte 已提交
2906
    esxPrivate *priv = domain->conn->privateData;
2907 2908 2909 2910 2911 2912 2913
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
    int i;

2914
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2915
        return -1;
2916 2917
    }

2918
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2919
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2920
           priv->autoAnswer) < 0 ||
2921 2922
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->cpuAllocation) < 0) {
M
Matthias Bolte 已提交
2923
        goto cleanup;
2924 2925 2926 2927 2928
    }

    for (i = 0; i < nparams; ++i) {
        if (STREQ (params[i].field, "reservation") &&
            params[i].type == VIR_DOMAIN_SCHED_FIELD_LLONG) {
2929
            if (esxVI_Long_Alloc(&spec->cpuAllocation->reservation) < 0) {
M
Matthias Bolte 已提交
2930
                goto cleanup;
2931 2932 2933
            }

            if (params[i].value.l < 0) {
2934
                ESX_ERROR(VIR_ERR_INVALID_ARG,
2935 2936
                          _("Could not set reservation to %lld MHz, expecting "
                            "positive value"), params[i].value.l);
M
Matthias Bolte 已提交
2937
                goto cleanup;
2938 2939 2940 2941 2942
            }

            spec->cpuAllocation->reservation->value = params[i].value.l;
        } else if (STREQ (params[i].field, "limit") &&
                   params[i].type == VIR_DOMAIN_SCHED_FIELD_LLONG) {
2943
            if (esxVI_Long_Alloc(&spec->cpuAllocation->limit) < 0) {
M
Matthias Bolte 已提交
2944
                goto cleanup;
2945 2946 2947
            }

            if (params[i].value.l < -1) {
2948
                ESX_ERROR(VIR_ERR_INVALID_ARG,
2949 2950
                          _("Could not set limit to %lld MHz, expecting "
                            "positive value or -1 (unlimited)"),
2951
                          params[i].value.l);
M
Matthias Bolte 已提交
2952
                goto cleanup;
2953 2954 2955 2956
            }

            spec->cpuAllocation->limit->value = params[i].value.l;
        } else if (STREQ (params[i].field, "shares") &&
2957
                   params[i].type == VIR_DOMAIN_SCHED_FIELD_INT) {
2958 2959
            if (esxVI_SharesInfo_Alloc(&sharesInfo) < 0 ||
                esxVI_Int_Alloc(&sharesInfo->shares) < 0) {
M
Matthias Bolte 已提交
2960
                goto cleanup;
2961 2962 2963 2964
            }

            spec->cpuAllocation->shares = sharesInfo;

2965
            if (params[i].value.i >= 0) {
2966
                spec->cpuAllocation->shares->level = esxVI_SharesLevel_Custom;
2967
                spec->cpuAllocation->shares->shares->value = params[i].value.i;
2968
            } else {
2969
                switch (params[i].value.i) {
2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987
                  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:
2988
                    ESX_ERROR(VIR_ERR_INVALID_ARG,
2989 2990
                              _("Could not set shares to %d, expecting positive "
                                "value or -1 (low), -2 (normal) or -3 (high)"),
2991
                              params[i].value.i);
M
Matthias Bolte 已提交
2992
                    goto cleanup;
2993 2994 2995
                }
            }
        } else {
2996
            ESX_ERROR(VIR_ERR_INVALID_ARG, _("Unknown field '%s'"),
2997
                      params[i].field);
M
Matthias Bolte 已提交
2998
            goto cleanup;
2999 3000 3001
        }
    }

3002
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
3003
                              &task) < 0 ||
3004
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3005
                                    esxVI_Occurrence_RequiredItem,
3006
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3007
        goto cleanup;
3008 3009 3010
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3011 3012
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not change scheduler parameters"));
M
Matthias Bolte 已提交
3013
        goto cleanup;
3014 3015
    }

M
Matthias Bolte 已提交
3016 3017
    result = 0;

3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainMigratePrepare(virConnectPtr dconn,
                        char **cookie ATTRIBUTE_UNUSED,
                        int *cookielen ATTRIBUTE_UNUSED,
3032 3033
                        const char *uri_in ATTRIBUTE_UNUSED,
                        char **uri_out,
3034 3035 3036 3037
                        unsigned long flags ATTRIBUTE_UNUSED,
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
3038
    esxPrivate *priv = dconn->privateData;
3039 3040

    if (uri_in == NULL) {
3041 3042 3043 3044
        if (virAsprintf(uri_out, "vpxmigr://%s/%s/%s",
                        priv->vCenter->ipAddress,
                        priv->vCenter->computeResource->resourcePool->value,
                        priv->vCenter->hostSystem->_reference->value) < 0) {
3045
            virReportOOMError();
3046
            return -1;
3047 3048 3049
        }
    }

3050
    return 0;
3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063
}



static int
esxDomainMigratePerform(virDomainPtr domain,
                        const char *cookie ATTRIBUTE_UNUSED,
                        int cookielen ATTRIBUTE_UNUSED,
                        const char *uri,
                        unsigned long flags ATTRIBUTE_UNUSED,
                        const char *dname,
                        unsigned long bandwidth ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
3064
    int result = -1;
M
Matthias Bolte 已提交
3065
    esxPrivate *priv = domain->conn->privateData;
3066 3067 3068 3069
    xmlURIPtr parsedUri = NULL;
    char *saveptr;
    char *path_resourcePool;
    char *path_hostSystem;
3070
    esxVI_ObjectContent *virtualMachine = NULL;
3071 3072
    esxVI_ManagedObjectReference resourcePool;
    esxVI_ManagedObjectReference hostSystem;
3073 3074 3075 3076
    esxVI_Event *eventList = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

M
Matthias Bolte 已提交
3077
    if (priv->vCenter == NULL) {
3078 3079
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Migration not possible without a vCenter"));
M
Matthias Bolte 已提交
3080
        return -1;
3081 3082 3083
    }

    if (dname != NULL) {
3084 3085
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Renaming domains on migration not supported"));
M
Matthias Bolte 已提交
3086
        return -1;
3087 3088
    }

3089
    if (esxVI_EnsureSession(priv->vCenter) < 0) {
M
Matthias Bolte 已提交
3090
        return -1;
3091 3092
    }

3093 3094
    /* Parse migration URI */
    parsedUri = xmlParseURI(uri);
3095

3096
    if (parsedUri == NULL) {
3097
        virReportOOMError();
M
Matthias Bolte 已提交
3098
        return -1;
3099 3100
    }

3101 3102 3103
    if (parsedUri->scheme == NULL || STRCASENEQ(parsedUri->scheme, "vpxmigr")) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Only vpxmigr:// migration URIs are supported"));
M
Matthias Bolte 已提交
3104
        goto cleanup;
3105 3106
    }

3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119
    if (STRCASENEQ(priv->vCenter->ipAddress, parsedUri->server)) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Migration source and destination have to refer to "
                    "the same vCenter"));
        goto cleanup;
    }

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

    if (path_resourcePool == NULL || path_hostSystem == NULL) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Migration URI has to specify resource pool and host system"));
M
Matthias Bolte 已提交
3120
        goto cleanup;
3121 3122
    }

3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136
    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,
           priv->autoAnswer) < 0) {
M
Matthias Bolte 已提交
3137
        goto cleanup;
3138 3139 3140
    }

    /* Validate the purposed migration */
3141
    if (esxVI_ValidateMigration(priv->vCenter, virtualMachine->obj,
3142 3143
                                esxVI_VirtualMachinePowerState_Undefined, NULL,
                                &resourcePool, &hostSystem, &eventList) < 0) {
M
Matthias Bolte 已提交
3144
        goto cleanup;
3145 3146 3147 3148 3149 3150 3151 3152
    }

    if (eventList != NULL) {
        /*
         * FIXME: Need to report the complete list of events. Limit reporting
         *        to the first event for now.
         */
        if (eventList->fullFormattedMessage != NULL) {
3153
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3154 3155
                      _("Could not migrate domain, validation reported a "
                        "problem: %s"), eventList->fullFormattedMessage);
3156
        } else {
3157 3158 3159
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                      _("Could not migrate domain, validation reported a "
                        "problem"));
3160 3161
        }

M
Matthias Bolte 已提交
3162
        goto cleanup;
3163 3164 3165
    }

    /* Perform the purposed migration */
3166 3167
    if (esxVI_MigrateVM_Task(priv->vCenter, virtualMachine->obj,
                             &resourcePool, &hostSystem,
3168 3169 3170
                             esxVI_VirtualMachineMovePriority_DefaultPriority,
                             esxVI_VirtualMachinePowerState_Undefined,
                             &task) < 0 ||
3171
        esxVI_WaitForTaskCompletion(priv->vCenter, task, domain->uuid,
3172
                                    esxVI_Occurrence_RequiredItem,
3173
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3174
        goto cleanup;
3175 3176 3177
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3178 3179 3180
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not migrate domain, migration task finished with "
                    "an error"));
M
Matthias Bolte 已提交
3181
        goto cleanup;
3182 3183
    }

M
Matthias Bolte 已提交
3184 3185
    result = 0;

3186
  cleanup:
3187
    xmlFreeURI(parsedUri);
3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Event_Free(&eventList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static virDomainPtr
esxDomainMigrateFinish(virConnectPtr dconn, const char *dname,
                       const char *cookie ATTRIBUTE_UNUSED,
                       int cookielen ATTRIBUTE_UNUSED,
                       const char *uri ATTRIBUTE_UNUSED,
                       unsigned long flags ATTRIBUTE_UNUSED)
{
    return esxDomainLookupByName(dconn, dname);
}



M
Matthias Bolte 已提交
3209 3210 3211 3212
static unsigned long long
esxNodeGetFreeMemory(virConnectPtr conn)
{
    unsigned long long result = 0;
M
Matthias Bolte 已提交
3213
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
3214 3215 3216 3217 3218
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *resourcePool = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ResourcePoolResourceUsage *resourcePoolResourceUsage = NULL;

3219
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3220
        return 0;
M
Matthias Bolte 已提交
3221 3222 3223
    }

    /* Get memory usage of resource pool */
3224
    if (esxVI_String_AppendValueToList(&propertyNameList,
M
Matthias Bolte 已提交
3225
                                       "runtime.memory") < 0 ||
3226 3227
        esxVI_LookupObjectContentByType(priv->primary,
                                        priv->primary->computeResource->resourcePool,
3228 3229 3230
                                        "ResourcePool", propertyNameList,
                                        esxVI_Boolean_False,
                                        &resourcePool) < 0) {
M
Matthias Bolte 已提交
3231
        goto cleanup;
M
Matthias Bolte 已提交
3232 3233 3234 3235 3236 3237
    }

    for (dynamicProperty = resourcePool->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.memory")) {
            if (esxVI_ResourcePoolResourceUsage_CastFromAnyType
3238
                  (dynamicProperty->val, &resourcePoolResourceUsage) < 0) {
M
Matthias Bolte 已提交
3239
                goto cleanup;
M
Matthias Bolte 已提交
3240 3241 3242 3243 3244 3245 3246 3247 3248
            }

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

    if (resourcePoolResourceUsage == NULL) {
3249 3250
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve memory usage of resource pool"));
M
Matthias Bolte 已提交
3251
        goto cleanup;
M
Matthias Bolte 已提交
3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265
    }

    result = resourcePoolResourceUsage->unreservedForVm->value;

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&resourcePool);
    esxVI_ResourcePoolResourceUsage_Free(&resourcePoolResourceUsage);

    return result;
}



3266 3267 3268
static int
esxIsEncrypted(virConnectPtr conn)
{
M
Matthias Bolte 已提交
3269
    esxPrivate *priv = conn->privateData;
3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282

    if (STRCASEEQ(priv->transport, "https")) {
        return 1;
    } else {
        return 0;
    }
}



static int
esxIsSecure(virConnectPtr conn)
{
M
Matthias Bolte 已提交
3283
    esxPrivate *priv = conn->privateData;
3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296

    if (STRCASEEQ(priv->transport, "https")) {
        return 1;
    } else {
        return 0;
    }
}



static int
esxDomainIsActive(virDomainPtr domain)
{
M
Matthias Bolte 已提交
3297
    int result = -1;
M
Matthias Bolte 已提交
3298
    esxPrivate *priv = domain->conn->privateData;
3299 3300 3301 3302
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

3303
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3304
        return -1;
3305 3306
    }

3307
    if (esxVI_String_AppendValueToList(&propertyNameList,
3308
                                       "runtime.powerState") < 0 ||
3309
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
3310
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3311
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3312
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
3313
        goto cleanup;
3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339
    }

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

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

    return result;
}



static int
esxDomainIsPersistent(virDomainPtr domain ATTRIBUTE_UNUSED)
{
    /* ESX has no concept of transient domains, so all of them are persistent */
    return 1;
}



3340 3341
static virDomainSnapshotPtr
esxDomainSnapshotCreateXML(virDomainPtr domain, const char *xmlDesc,
3342
                           unsigned int flags)
3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353
{
    esxPrivate *priv = domain->conn->privateData;
    virDomainSnapshotDefPtr def = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
    virDomainSnapshotPtr snapshot = NULL;

3354 3355
    virCheckFlags(0, NULL);

3356
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3357
        return NULL;
3358 3359 3360 3361 3362
    }

    def = virDomainSnapshotDefParseString(xmlDesc, 1);

    if (def == NULL) {
M
Matthias Bolte 已提交
3363
        return NULL;
3364 3365 3366
    }

    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3367
          (priv->primary, domain->uuid, NULL, &virtualMachine,
3368
           priv->autoAnswer) < 0 ||
3369
        esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
3370 3371 3372 3373
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, def->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
3374
        goto cleanup;
3375 3376 3377 3378 3379
    }

    if (snapshotTree != NULL) {
        ESX_ERROR(VIR_ERR_OPERATION_INVALID,
                  _("Snapshot '%s' already exists"), def->name);
M
Matthias Bolte 已提交
3380
        goto cleanup;
3381 3382
    }

3383
    if (esxVI_CreateSnapshot_Task(priv->primary, virtualMachine->obj,
3384 3385 3386
                                  def->name, def->description,
                                  esxVI_Boolean_True,
                                  esxVI_Boolean_False, &task) < 0 ||
3387
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3388
                                    esxVI_Occurrence_RequiredItem,
3389
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3390
        goto cleanup;
3391 3392 3393 3394
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not create snapshot"));
M
Matthias Bolte 已提交
3395
        goto cleanup;
3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412
    }

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

  cleanup:
    virDomainSnapshotDefFree(def);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);

    return snapshot;
}



static char *
esxDomainSnapshotDumpXML(virDomainSnapshotPtr snapshot,
3413
                         unsigned int flags)
3414 3415 3416 3417 3418 3419 3420 3421 3422
{
    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;

3423 3424
    virCheckFlags(0, NULL);

M
Matthias Bolte 已提交
3425
    memset(&def, 0, sizeof (def));
3426

3427
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3428
        return NULL;
3429 3430
    }

3431
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
3432 3433 3434 3435
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3436
        goto cleanup;
3437 3438 3439 3440 3441 3442 3443 3444
    }

    def.name = snapshot->name;
    def.description = snapshotTree->description;
    def.parent = snapshotTreeParent != NULL ? snapshotTreeParent->name : NULL;

    if (esxVI_DateTime_ConvertToCalendarTime(snapshotTree->createTime,
                                             &def.creationTime) < 0) {
M
Matthias Bolte 已提交
3445
        goto cleanup;
3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463
    }

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

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

    xml = virDomainSnapshotDefFormat(uuid_string, &def, 0);

  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return xml;
}



static int
3464
esxDomainSnapshotNum(virDomainPtr domain, unsigned int flags)
3465
{
M
Matthias Bolte 已提交
3466
    int count;
3467 3468 3469
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;

3470 3471
    virCheckFlags(0, -1);

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

3476
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
3477
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
3478
        return -1;
3479 3480
    }

M
Matthias Bolte 已提交
3481
    count = esxVI_GetNumberOfSnapshotTrees(rootSnapshotTreeList);
3482 3483 3484

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

M
Matthias Bolte 已提交
3485
    return count;
3486 3487 3488 3489 3490 3491
}



static int
esxDomainSnapshotListNames(virDomainPtr domain, char **names, int nameslen,
3492
                           unsigned int flags)
3493
{
M
Matthias Bolte 已提交
3494
    int result;
3495 3496 3497
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;

3498 3499
    virCheckFlags(0, -1);

3500 3501 3502 3503 3504 3505 3506 3507 3508
    if (names == NULL || nameslen < 0) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
    }

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

3509
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3510
        return -1;
3511 3512
    }

3513
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
3514
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
3515
        return -1;
3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528
    }

    result = esxVI_GetSnapshotTreeNames(rootSnapshotTreeList, names, nameslen);

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



static virDomainSnapshotPtr
esxDomainSnapshotLookupByName(virDomainPtr domain, const char *name,
3529
                              unsigned int flags)
3530 3531 3532 3533 3534 3535 3536
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    virDomainSnapshotPtr snapshot = NULL;

3537 3538
    virCheckFlags(0, NULL);

3539
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3540
        return NULL;
3541 3542
    }

3543
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566
                                         &rootSnapshotTreeList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotTreeList, name, &snapshotTree,
                                    &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    snapshot = virGetDomainSnapshot(domain, name);

  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return snapshot;
}



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

3567
    virCheckFlags(0, -1);
3568

3569
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3570
        return -1;
3571 3572
    }

3573
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
3574 3575
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
3576
        return -1;
3577 3578 3579
    }

    if (currentSnapshotTree != NULL) {
M
Matthias Bolte 已提交
3580 3581
        esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);
        return 1;
3582 3583
    }

M
Matthias Bolte 已提交
3584
    return 0;
3585 3586 3587 3588 3589 3590 3591 3592 3593
}



static virDomainSnapshotPtr
esxDomainSnapshotCurrent(virDomainPtr domain, unsigned int flags)
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *currentSnapshotTree = NULL;
M
Matthias Bolte 已提交
3594
    virDomainSnapshotPtr snapshot = NULL;
3595

3596
    virCheckFlags(0, NULL);
3597

3598
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3599
        return NULL;
3600 3601
    }

3602
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
3603 3604
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3605
        return NULL;
3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619
    }

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

    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return snapshot;
}



static int
esxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
3620
    int result = -1;
3621 3622 3623 3624 3625 3626 3627
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

3628
    virCheckFlags(0, -1);
3629

3630
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3631
        return -1;
3632 3633
    }

3634
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
3635 3636 3637 3638
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3639
        goto cleanup;
3640 3641
    }

3642
    if (esxVI_RevertToSnapshot_Task(priv->primary, snapshotTree->snapshot, NULL,
3643
                                    &task) < 0 ||
3644
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
3645
                                    esxVI_Occurrence_RequiredItem,
3646
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3647
        goto cleanup;
3648 3649 3650 3651 3652
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not revert to snapshot '%s'"), snapshot->name);
M
Matthias Bolte 已提交
3653
        goto cleanup;
3654 3655
    }

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

3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainSnapshotDelete(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
3670
    int result = -1;
3671 3672 3673 3674 3675 3676 3677 3678
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    esxVI_Boolean removeChildren = esxVI_Boolean_False;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

3679 3680
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN, -1);

3681
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3682
        return -1;
3683 3684 3685 3686 3687 3688
    }

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

3689
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
3690 3691 3692 3693
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3694
        goto cleanup;
3695 3696
    }

3697
    if (esxVI_RemoveSnapshot_Task(priv->primary, snapshotTree->snapshot,
3698
                                  removeChildren, &task) < 0 ||
3699
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
3700
                                    esxVI_Occurrence_RequiredItem,
3701
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3702
        goto cleanup;
3703 3704 3705 3706 3707
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not delete snapshot '%s'"), snapshot->name);
M
Matthias Bolte 已提交
3708
        goto cleanup;
3709 3710
    }

M
Matthias Bolte 已提交
3711 3712
    result = 0;

3713 3714 3715 3716 3717 3718 3719 3720 3721
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



3722 3723 3724 3725 3726 3727 3728 3729
static virDriver esxDriver = {
    VIR_DRV_ESX,
    "ESX",
    esxOpen,                         /* open */
    esxClose,                        /* close */
    esxSupportsFeature,              /* supports_feature */
    esxGetType,                      /* type */
    esxGetVersion,                   /* version */
3730
    NULL,                            /* libvirtVersion (impl. in libvirt.c) */
3731 3732 3733
    esxGetHostname,                  /* hostname */
    NULL,                            /* getMaxVcpus */
    esxNodeGetInfo,                  /* nodeGetInfo */
3734
    esxGetCapabilities,              /* getCapabilities */
3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760
    esxListDomains,                  /* listDomains */
    esxNumberOfDomains,              /* numOfDomains */
    NULL,                            /* domainCreateXML */
    esxDomainLookupByID,             /* domainLookupByID */
    esxDomainLookupByUUID,           /* domainLookupByUUID */
    esxDomainLookupByName,           /* domainLookupByName */
    esxDomainSuspend,                /* domainSuspend */
    esxDomainResume,                 /* domainResume */
    esxDomainShutdown,               /* domainShutdown */
    esxDomainReboot,                 /* domainReboot */
    esxDomainDestroy,                /* domainDestroy */
    esxDomainGetOSType,              /* domainGetOSType */
    esxDomainGetMaxMemory,           /* domainGetMaxMemory */
    esxDomainSetMaxMemory,           /* domainSetMaxMemory */
    esxDomainSetMemory,              /* domainSetMemory */
    esxDomainGetInfo,                /* domainGetInfo */
    NULL,                            /* domainSave */
    NULL,                            /* domainRestore */
    NULL,                            /* domainCoreDump */
    esxDomainSetVcpus,               /* domainSetVcpus */
    NULL,                            /* domainPinVcpu */
    NULL,                            /* domainGetVcpus */
    esxDomainGetMaxVcpus,            /* domainGetMaxVcpus */
    NULL,                            /* domainGetSecurityLabel */
    NULL,                            /* nodeGetSecurityModel */
    esxDomainDumpXML,                /* domainDumpXML */
3761
    esxDomainXMLFromNative,          /* domainXMLFromNative */
M
Matthias Bolte 已提交
3762
    esxDomainXMLToNative,            /* domainXMLToNative */
3763 3764 3765
    esxListDefinedDomains,           /* listDefinedDomains */
    esxNumberOfDefinedDomains,       /* numOfDefinedDomains */
    esxDomainCreate,                 /* domainCreate */
3766
    esxDomainCreateWithFlags,        /* domainCreateWithFlags */
M
Matthias Bolte 已提交
3767
    esxDomainDefineXML,              /* domainDefineXML */
3768
    esxDomainUndefine,               /* domainUndefine */
3769
    NULL,                            /* domainAttachDevice */
3770
    NULL,                            /* domainAttachDeviceFlags */
3771
    NULL,                            /* domainDetachDevice */
3772
    NULL,                            /* domainDetachDeviceFlags */
3773
    NULL,                            /* domainUpdateDeviceFlags */
3774 3775 3776 3777 3778 3779 3780 3781 3782 3783
    NULL,                            /* domainGetAutostart */
    NULL,                            /* domainSetAutostart */
    esxDomainGetSchedulerType,       /* domainGetSchedulerType */
    esxDomainGetSchedulerParameters, /* domainGetSchedulerParameters */
    esxDomainSetSchedulerParameters, /* domainSetSchedulerParameters */
    esxDomainMigratePrepare,         /* domainMigratePrepare */
    esxDomainMigratePerform,         /* domainMigratePerform */
    esxDomainMigrateFinish,          /* domainMigrateFinish */
    NULL,                            /* domainBlockStats */
    NULL,                            /* domainInterfaceStats */
3784
    NULL,                            /* domainMemoryStats */
3785 3786
    NULL,                            /* domainBlockPeek */
    NULL,                            /* domainMemoryPeek */
3787
    NULL,                            /* domainGetBlockInfo */
3788
    NULL,                            /* nodeGetCellsFreeMemory */
M
Matthias Bolte 已提交
3789
    esxNodeGetFreeMemory,            /* nodeGetFreeMemory */
3790 3791 3792 3793 3794 3795 3796
    NULL,                            /* domainEventRegister */
    NULL,                            /* domainEventDeregister */
    NULL,                            /* domainMigratePrepare2 */
    NULL,                            /* domainMigrateFinish2 */
    NULL,                            /* nodeDeviceDettach */
    NULL,                            /* nodeDeviceReAttach */
    NULL,                            /* nodeDeviceReset */
C
Chris Lalancette 已提交
3797
    NULL,                            /* domainMigratePrepareTunnel */
3798 3799 3800 3801
    esxIsEncrypted,                  /* isEncrypted */
    esxIsSecure,                     /* isSecure */
    esxDomainIsActive,               /* domainIsActive */
    esxDomainIsPersistent,           /* domainIsPersistent */
J
Jiri Denemark 已提交
3802
    NULL,                            /* cpuCompare */
3803
    NULL,                            /* cpuBaseline */
3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820
    NULL,                            /* domainGetJobInfo */
    NULL,                            /* domainAbortJob */
    NULL,                            /* domainMigrateSetMaxDowntime */
    NULL,                            /* domainEventRegisterAny */
    NULL,                            /* domainEventDeregisterAny */
    NULL,                            /* domainManagedSave */
    NULL,                            /* domainHasManagedSaveImage */
    NULL,                            /* domainManagedSaveRemove */
    esxDomainSnapshotCreateXML,      /* domainSnapshotCreateXML */
    esxDomainSnapshotDumpXML,        /* domainSnapshotDumpXML */
    esxDomainSnapshotNum,            /* domainSnapshotNum */
    esxDomainSnapshotListNames,      /* domainSnapshotListNames */
    esxDomainSnapshotLookupByName,   /* domainSnapshotLookupByName */
    esxDomainHasCurrentSnapshot,     /* domainHasCurrentSnapshot */
    esxDomainSnapshotCurrent,        /* domainSnapshotCurrent */
    esxDomainRevertToSnapshot,       /* domainRevertToSnapshot */
    esxDomainSnapshotDelete,         /* domainSnapshotDelete */
C
Chris Lalancette 已提交
3821
    NULL,                            /* qemuDomainMonitorCommand */
3822 3823 3824 3825 3826 3827 3828
};



int
esxRegister(void)
{
3829 3830 3831 3832 3833
    if (virRegisterDriver(&esxDriver) < 0 ||
        esxInterfaceRegister() < 0 ||
        esxNetworkRegister() < 0 ||
        esxStorageRegister() < 0 ||
        esxDeviceRegister() < 0 ||
M
Matthias Bolte 已提交
3834 3835
        esxSecretRegister() < 0 ||
        esxNWFilterRegister() < 0) {
3836 3837
        return -1;
    }
3838 3839 3840

    return 0;
}