esx_driver.c 118.7 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->host) < 0) {
M
Matthias Bolte 已提交
71
        return esxVI_Boolean_Undefined;
72 73
    }

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

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

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

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

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

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

                    break;
                }
            }

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

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

    return priv->supportsLongMode;
}



143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 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 204 205
static int
esxLookupHostSystemBiosUuid(esxPrivate *priv, unsigned char *uuid)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

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

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "hardware.systemInfo.uuid") < 0 ||
        esxVI_LookupObjectContentByType(priv->host, priv->host->hostFolder,
                                        "HostSystem", propertyNameList,
                                        esxVI_Boolean_True, &hostSystem) < 0) {
        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;
}



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

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

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

    if (caps == NULL) {
224
        virReportOOMError();
225 226 227
        return NULL;
    }

228
    virCapabilitiesSetMacPrefix(caps, (unsigned char[]){ 0x00, 0x0c, 0x29 });
229 230
    virCapabilitiesAddHostMigrateTransport(caps, "esx");

231 232
    caps->hasWideScsiBus = true;

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

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

    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;
    }

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
    /* 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;
        }
    }

273 274 275 276 277 278 279 280 281 282
    return caps;

  failure:
    virCapabilitiesFree(caps);

    return NULL;
}



283
/*
M
Matthias Bolte 已提交
284
 * URI format: {esx|gsx}://[<username>@]<hostname>[:<port>]/[<query parameter> ...]
285
 *
286 287 288
 * If no port is specified the default port is set dependent on the scheme and
 * transport parameter:
 * - esx+http  80
289
 * - esx+https 443
290 291 292
 * - gsx+http  8222
 * - gsx+https 8333
 *
293 294 295 296 297
 * Optional query parameters:
 * - transport={http|https}
 * - vcenter={<vcenter>|*}
 * - no_verify={0|1}
 * - auto_answer={0|1}
M
Matthias Bolte 已提交
298
 * - proxy=[{http|socks|socks4|socks4a|socks5}://]<hostname>[:<port>]
299
 *
300 301 302
 * If no transport parameter is specified https is used.
 *
 * The vcenter parameter is only necessary for migration, because the vCenter
303 304 305 306
 * server is in charge to initiate a migration between two ESX hosts. The
 * vcenter parameter can be set to an explicity hostname or to *. If set to *,
 * 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.
307 308
 *
 * If the no_verify parameter is set to 1, this disables libcurl client checks
309
 * of the server's certificate. The default value it 0.
310 311 312 313
 *
 * 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 已提交
314 315 316 317
 *
 * 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.
318 319 320 321
 */
static virDrvOpenStatus
esxOpen(virConnectPtr conn, virConnectAuthPtr auth, int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
322
    virDrvOpenStatus result = VIR_DRV_OPEN_ERROR;
323
    esxPrivate *priv = NULL;
324
    esxUtil_ParsedQuery *parsedQuery = NULL;
M
Matthias Bolte 已提交
325 326
    char hostIpAddress[NI_MAXHOST] = "";
    char vCenterIpAddress[NI_MAXHOST] = "";
327
    char *url = NULL;
M
Matthias Bolte 已提交
328
    char *vCenter = NULL;
329 330
    char *username = NULL;
    char *password = NULL;
331 332 333
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
334

335
    /* Decline if the URI is NULL or the scheme is neither 'esx' nor 'gsx' */
336
    if (conn->uri == NULL || conn->uri->scheme == NULL ||
337 338
        (STRCASENEQ(conn->uri->scheme, "esx") &&
         STRCASENEQ(conn->uri->scheme, "gsx"))) {
339 340 341
        return VIR_DRV_OPEN_DECLINED;
    }

M
Matthias Bolte 已提交
342 343 344
    /* Decline URIs without server part, or missing auth */
    if (conn->uri->server == NULL || auth == NULL || auth->cb == NULL) {
        return VIR_DRV_OPEN_DECLINED;
345 346
    }

347 348
    if (conn->uri->path != NULL && STRNEQ(conn->uri->path, "") &&
        STRNEQ(conn->uri->path, "/")) {
M
Matthias Bolte 已提交
349
        VIR_WARN("Ignoring unexpected path '%s' in URI", conn->uri->path);
350 351 352 353
    }

    /* Allocate per-connection private data */
    if (VIR_ALLOC(priv) < 0) {
354
        virReportOOMError();
M
Matthias Bolte 已提交
355
        goto cleanup;
356 357
    }

358 359 360 361 362 363 364
    if (esxUtil_ParseQuery(&parsedQuery, conn->uri) < 0) {
        goto cleanup;
    }

    priv->transport = parsedQuery->transport;
    parsedQuery->transport = NULL;

M
Matthias Bolte 已提交
365 366
    priv->maxVcpus = -1;
    priv->supportsVMotion = esxVI_Boolean_Undefined;
367
    priv->supportsLongMode = esxVI_Boolean_Undefined;
368 369
    priv->autoAnswer = parsedQuery->autoAnswer ? esxVI_Boolean_True
                                               : esxVI_Boolean_False;
370 371
    priv->usedCpuTimeCounterId = -1;

M
Matthias Bolte 已提交
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
    /*
     * 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) {
        if (STRCASEEQ(conn->uri->scheme, "esx")) {
            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;
            }
391
        }
M
Matthias Bolte 已提交
392
    }
393

M
Matthias Bolte 已提交
394
    /* Login to host */
395
    if (esxUtil_ResolveHostname(conn->uri->server, hostIpAddress,
396
                                NI_MAXHOST) < 0) {
M
Matthias Bolte 已提交
397
        goto cleanup;
398 399
    }

M
Matthias Bolte 已提交
400 401
    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->transport,
                    conn->uri->server, conn->uri->port) < 0) {
402
        virReportOOMError();
M
Matthias Bolte 已提交
403
        goto cleanup;
M
Matthias Bolte 已提交
404 405 406 407 408 409
    }

    if (conn->uri->user != NULL) {
        username = strdup(conn->uri->user);

        if (username == NULL) {
410
            virReportOOMError();
M
Matthias Bolte 已提交
411
            goto cleanup;
412
        }
M
Matthias Bolte 已提交
413
    } else {
414
        username = virRequestUsername(auth, "root", conn->uri->server);
415

M
Matthias Bolte 已提交
416
        if (username == NULL) {
417
            ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Username request failed"));
M
Matthias Bolte 已提交
418
            goto cleanup;
419
        }
M
Matthias Bolte 已提交
420
    }
421

422
    password = virRequestPassword(auth, username, conn->uri->server);
M
Matthias Bolte 已提交
423 424

    if (password == NULL) {
425
        ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
M
Matthias Bolte 已提交
426
        goto cleanup;
M
Matthias Bolte 已提交
427 428
    }

429 430
    if (esxVI_Context_Alloc(&priv->host) < 0 ||
        esxVI_Context_Connect(priv->host, url, hostIpAddress, username,
M
Matthias Bolte 已提交
431
                              password, parsedQuery) < 0) {
M
Matthias Bolte 已提交
432
        goto cleanup;
M
Matthias Bolte 已提交
433 434 435 436 437
    }

    if (STRCASEEQ(conn->uri->scheme, "esx")) {
        if (priv->host->productVersion != esxVI_ProductVersion_ESX35 &&
            priv->host->productVersion != esxVI_ProductVersion_ESX40) {
438
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
439
                      _("%s is neither an ESX 3.5 host nor an ESX 4.0 host"),
M
Matthias Bolte 已提交
440
                      conn->uri->server);
M
Matthias Bolte 已提交
441
            goto cleanup;
442
        }
M
Matthias Bolte 已提交
443 444
    } else { /* GSX */
        if (priv->host->productVersion != esxVI_ProductVersion_GSX20) {
445
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
446
                      _("%s isn't a GSX 2.0 host"), conn->uri->server);
M
Matthias Bolte 已提交
447
            goto cleanup;
M
Matthias Bolte 已提交
448 449
        }
    }
450

451
    /* Query the host for maintenance mode and vCenter IP address */
452
    if (esxVI_String_AppendValueListToList(&propertyNameList,
453 454
                                           "runtime.inMaintenanceMode\0"
                                           "summary.managementServerIp\0") < 0 ||
455 456
        esxVI_LookupHostSystemByIp(priv->host, hostIpAddress, propertyNameList,
                                   &hostSystem) < 0) {
M
Matthias Bolte 已提交
457
        goto cleanup;
458 459 460 461 462 463
    }

    /* Warn if host is in maintenance mode */
    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.inMaintenanceMode")) {
464
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
465
                                         esxVI_Type_Boolean) < 0) {
M
Matthias Bolte 已提交
466
                goto cleanup;
467 468 469 470 471 472 473 474 475 476
            }

            if (dynamicProperty->val->boolean == esxVI_Boolean_True) {
                VIR_WARN0("The server is in maintenance mode");
            }

            break;
        }
    }

M
Matthias Bolte 已提交
477 478
    /* Login to vCenter */
    if (vCenter != NULL) {
479 480 481 482 483 484
        VIR_FREE(url);
        VIR_FREE(password);
        VIR_FREE(username);

        /* If a vCenter is specified resolve the hostname */
        if (STRNEQ(vCenter, "*") &&
485
            esxUtil_ResolveHostname(vCenter, vCenterIpAddress,
486
                                    NI_MAXHOST) < 0) {
M
Matthias Bolte 已提交
487
            goto cleanup;
488 489 490 491 492
        }

        /* Lookup the vCenter from the ESX host */
        for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
493
            if (STREQ(dynamicProperty->name, "summary.managementServerIp")) {
494
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
495
                                             esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
496
                    goto cleanup;
497 498 499 500 501 502 503 504 505
                }

                /* Get the vCenter IP address or verify the specified one */
                if (STREQ(vCenter, "*")) {
                    VIR_FREE(vCenter);

                    vCenter = strdup(dynamicProperty->val->string);

                    if (vCenter == NULL) {
506
                        virReportOOMError();
M
Matthias Bolte 已提交
507
                        goto cleanup;
508 509 510 511
                    }

                    if (virStrcpyStatic(vCenterIpAddress,
                                        dynamicProperty->val->string) == NULL) {
512
                        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
513 514 515
                                  _("vCenter IP address %s too big for "
                                    "destination"),
                                  dynamicProperty->val->string);
M
Matthias Bolte 已提交
516
                        goto cleanup;
517 518 519
                    }
                } else if (STRNEQ(vCenterIpAddress,
                           dynamicProperty->val->string)) {
520
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
521 522 523
                              _("This host is managed by a vCenter with IP "
                                "address %s, but a mismachting vCenter '%s' "
                                "(%s) has been specified"),
524 525
                              dynamicProperty->val->string, vCenter,
                              vCenterIpAddress);
M
Matthias Bolte 已提交
526
                    goto cleanup;
527 528 529 530 531 532 533
                }

                break;
            }
        }

        if (STREQ(vCenter, "*")) {
534 535
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                      _("This host is not managed by a vCenter"));
M
Matthias Bolte 已提交
536
            goto cleanup;
537 538
        }

M
Matthias Bolte 已提交
539 540
        if (virAsprintf(&url, "%s://%s/sdk", priv->transport,
                        vCenter) < 0) {
541
            virReportOOMError();
M
Matthias Bolte 已提交
542
            goto cleanup;
M
Matthias Bolte 已提交
543
        }
544

545
        if (esxVI_Context_Alloc(&priv->vCenter) < 0) {
M
Matthias Bolte 已提交
546
            goto cleanup;
547 548
        }

549
        username = virRequestUsername(auth, "administrator", vCenter);
M
Matthias Bolte 已提交
550 551

        if (username == NULL) {
552
            ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Username request failed"));
M
Matthias Bolte 已提交
553
            goto cleanup;
554 555
        }

556
        password = virRequestPassword(auth, username, vCenter);
557 558

        if (password == NULL) {
559
            ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
M
Matthias Bolte 已提交
560
            goto cleanup;
561 562
        }

563
        if (esxVI_Context_Connect(priv->vCenter, url, vCenterIpAddress,
M
Matthias Bolte 已提交
564
                                  username, password, parsedQuery) < 0) {
M
Matthias Bolte 已提交
565
            goto cleanup;
566 567
        }

M
Matthias Bolte 已提交
568 569
        if (priv->vCenter->productVersion != esxVI_ProductVersion_VPX25 &&
            priv->vCenter->productVersion != esxVI_ProductVersion_VPX40) {
570
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
571 572
                      _("%s is neither a vCenter 2.5 server nor a vCenter "
                        "4.0 server"), conn->uri->server);
M
Matthias Bolte 已提交
573
            goto cleanup;
574
        }
575 576 577
    }

    conn->privateData = priv;
578

M
Matthias Bolte 已提交
579
    /* Setup capabilities */
580
    priv->caps = esxCapsInit(priv);
581

M
Matthias Bolte 已提交
582
    if (priv->caps == NULL) {
M
Matthias Bolte 已提交
583
        goto cleanup;
584 585
    }

M
Matthias Bolte 已提交
586
    result = VIR_DRV_OPEN_SUCCESS;
587

M
Matthias Bolte 已提交
588 589
  cleanup:
    if (result == VIR_DRV_OPEN_ERROR && priv != NULL) {
590
        esxVI_Context_Free(&priv->host);
M
Matthias Bolte 已提交
591
        esxVI_Context_Free(&priv->vCenter);
592

593 594
        virCapabilitiesFree(priv->caps);

M
Matthias Bolte 已提交
595
        VIR_FREE(priv->transport);
596 597 598
        VIR_FREE(priv);
    }

599
    esxUtil_FreeParsedQuery(&parsedQuery);
M
Matthias Bolte 已提交
600 601 602 603 604 605
    VIR_FREE(url);
    VIR_FREE(vCenter);
    VIR_FREE(password);
    VIR_FREE(username);
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);
606

M
Matthias Bolte 已提交
607
    return result;
608 609 610 611 612 613 614
}



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

E
Eric Blake 已提交
618 619 620 621
    if (esxVI_EnsureSession(priv->host) < 0 ||
        esxVI_Logout(priv->host) < 0) {
        result = -1;
    }
622

M
Matthias Bolte 已提交
623
    esxVI_Context_Free(&priv->host);
624

M
Matthias Bolte 已提交
625
    if (priv->vCenter != NULL) {
E
Eric Blake 已提交
626 627 628 629
        if (esxVI_EnsureSession(priv->vCenter) < 0 ||
            esxVI_Logout(priv->vCenter) < 0) {
            result = -1;
        }
630

M
Matthias Bolte 已提交
631
        esxVI_Context_Free(&priv->vCenter);
632 633
    }

634 635
    virCapabilitiesFree(priv->caps);

636 637 638 639 640
    VIR_FREE(priv->transport);
    VIR_FREE(priv);

    conn->privateData = NULL;

E
Eric Blake 已提交
641
    return result;
642 643 644 645 646
}



static esxVI_Boolean
647
esxSupportsVMotion(esxPrivate *priv)
648 649 650 651 652
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

M
Matthias Bolte 已提交
653 654
    if (priv->supportsVMotion != esxVI_Boolean_Undefined) {
        return priv->supportsVMotion;
655 656
    }

657
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
658
        return esxVI_Boolean_Undefined;
659 660
    }

661
    if (esxVI_String_AppendValueToList(&propertyNameList,
662
                                       "capability.vmotionSupported") < 0 ||
663
        esxVI_LookupObjectContentByType(priv->host, priv->host->hostFolder,
664 665
                                        "HostSystem", propertyNameList,
                                        esxVI_Boolean_True, &hostSystem) < 0) {
M
Matthias Bolte 已提交
666
        goto cleanup;
667 668 669
    }

    if (hostSystem == NULL) {
670 671
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
672
        goto cleanup;
673 674 675 676 677
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "capability.vmotionSupported")) {
678
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
679
                                         esxVI_Type_Boolean) < 0) {
M
Matthias Bolte 已提交
680
                goto cleanup;
681 682
            }

M
Matthias Bolte 已提交
683
            priv->supportsVMotion = dynamicProperty->val->boolean;
684 685 686 687 688 689 690
            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

  cleanup:
M
Matthias Bolte 已提交
691 692 693 694
    /*
     * 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.
     */
695 696 697
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
698
    return priv->supportsVMotion;
699 700 701 702 703 704 705
}



static int
esxSupportsFeature(virConnectPtr conn, int feature)
{
M
Matthias Bolte 已提交
706
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
707
    esxVI_Boolean supportsVMotion = esxVI_Boolean_Undefined;
708 709 710

    switch (feature) {
      case VIR_DRV_FEATURE_MIGRATION_V1:
711
        supportsVMotion = esxSupportsVMotion(priv);
712

M
Matthias Bolte 已提交
713
        if (supportsVMotion == esxVI_Boolean_Undefined) {
714 715 716
            return -1;
        }

M
Matthias Bolte 已提交
717 718 719
        /* Migration is only possible via a vCenter and if VMotion is enabled */
        return priv->vCenter != NULL &&
               supportsVMotion == esxVI_Boolean_True ? 1 : 0;
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738

      default:
        return 0;
    }
}



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



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

741 742 743
    if (virParseVersionString(priv->host->service->about->version,
                              version) < 0) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
744
                  _("Could not parse version number from '%s'"),
745
                  priv->host->service->about->version);
746

747
        return -1;
748 749 750 751 752 753 754 755 756 757
    }

    return 0;
}



static char *
esxGetHostname(virConnectPtr conn)
{
M
Matthias Bolte 已提交
758
    esxPrivate *priv = conn->privateData;
759 760 761 762 763 764 765
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    const char *hostName = NULL;
    const char *domainName = NULL;
    char *complete = NULL;

766
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
767
        return NULL;
768 769 770
    }

    if (esxVI_String_AppendValueListToList
771
          (&propertyNameList,
772 773
           "config.network.dnsConfig.hostName\0"
           "config.network.dnsConfig.domainName\0") < 0 ||
774
        esxVI_LookupObjectContentByType(priv->host, priv->host->hostFolder,
775 776
                                        "HostSystem", propertyNameList,
                                        esxVI_Boolean_True, &hostSystem) < 0) {
M
Matthias Bolte 已提交
777
        goto cleanup;
778 779 780
    }

    if (hostSystem == NULL) {
781 782
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
783
        goto cleanup;
784 785 786 787 788 789
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name,
                  "config.network.dnsConfig.hostName")) {
790
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
791
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
792
                goto cleanup;
793 794 795 796 797
            }

            hostName = dynamicProperty->val->string;
        } else if (STREQ(dynamicProperty->name,
                         "config.network.dnsConfig.domainName")) {
798
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
799
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
800
                goto cleanup;
801 802 803 804 805 806 807 808
            }

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

M
Matthias Bolte 已提交
809
    if (hostName == NULL || strlen(hostName) < 1) {
810 811
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Missing or empty 'hostName' property"));
M
Matthias Bolte 已提交
812
        goto cleanup;
813 814
    }

M
Matthias Bolte 已提交
815
    if (domainName == NULL || strlen(domainName) < 1) {
816
        complete = strdup(hostName);
817

818
        if (complete == NULL) {
819
            virReportOOMError();
M
Matthias Bolte 已提交
820
            goto cleanup;
821 822 823
        }
    } else {
        if (virAsprintf(&complete, "%s.%s", hostName, domainName) < 0) {
824
            virReportOOMError();
M
Matthias Bolte 已提交
825
            goto cleanup;
826
        }
827 828 829
    }

  cleanup:
M
Matthias Bolte 已提交
830 831 832 833 834
    /*
     * 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
     */
835 836 837 838 839 840 841 842 843 844 845
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return complete;
}



static int
esxNodeGetInfo(virConnectPtr conn, virNodeInfoPtr nodeinfo)
{
M
Matthias Bolte 已提交
846
    int result = -1;
M
Matthias Bolte 已提交
847
    esxPrivate *priv = conn->privateData;
848 849 850 851 852 853 854 855 856 857 858
    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 已提交
859
    memset(nodeinfo, 0, sizeof (*nodeinfo));
860

861
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
862
        return -1;
863 864
    }

865
    if (esxVI_String_AppendValueListToList(&propertyNameList,
866 867 868 869 870 871 872
                                           "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 ||
873
        esxVI_LookupObjectContentByType(priv->host, priv->host->hostFolder,
874 875
                                        "HostSystem", propertyNameList,
                                        esxVI_Boolean_True, &hostSystem) < 0) {
M
Matthias Bolte 已提交
876
        goto cleanup;
877 878 879
    }

    if (hostSystem == NULL) {
880 881
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
882
        goto cleanup;
883 884 885 886 887
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuInfo.hz")) {
888
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
889
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
890
                goto cleanup;
891 892 893 894 895
            }

            cpuInfo_hz = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuCores")) {
896
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
897
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
898
                goto cleanup;
899 900 901 902 903
            }

            cpuInfo_numCpuCores = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuPackages")) {
904
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
905
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
906
                goto cleanup;
907 908 909 910 911
            }

            cpuInfo_numCpuPackages = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuThreads")) {
912
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
913
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
914
                goto cleanup;
915 916 917 918
            }

            cpuInfo_numCpuThreads = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name, "hardware.memorySize")) {
919
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
920
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
921
                goto cleanup;
922 923 924 925 926
            }

            memorySize = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.numaInfo.numNodes")) {
927
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
928
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
929
                goto cleanup;
930 931 932 933 934
            }

            numaInfo_numNodes = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "summary.hardware.cpuModel")) {
935
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
936
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
937
                goto cleanup;
938 939 940 941 942 943
            }

            ptr = dynamicProperty->val->string;

            /* Strip the string to fit more relevant information in 32 chars */
            while (*ptr != '\0') {
M
Matthias Bolte 已提交
944 945
                if (STRPREFIX(ptr, "  ")) {
                    memmove(ptr, ptr + 1, strlen(ptr + 1) + 1);
946
                    continue;
947
                } else if (STRPREFIX(ptr, "(R)") || STRPREFIX(ptr, "(C)")) {
M
Matthias Bolte 已提交
948
                    memmove(ptr, ptr + 3, strlen(ptr + 3) + 1);
949
                    continue;
950 951 952
                } else if (STRPREFIX(ptr, "(TM)")) {
                    memmove(ptr, ptr + 4, strlen(ptr + 4) + 1);
                    continue;
953 954 955 956 957
                }

                ++ptr;
            }

C
Chris Lalancette 已提交
958 959 960
            if (virStrncpy(nodeinfo->model, dynamicProperty->val->string,
                           sizeof(nodeinfo->model) - 1,
                           sizeof(nodeinfo->model)) == NULL) {
961
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
962
                          _("CPU Model %s too long for destination"),
C
Chris Lalancette 已提交
963
                          dynamicProperty->val->string);
M
Matthias Bolte 已提交
964
                goto cleanup;
C
Chris Lalancette 已提交
965
            }
966 967 968 969 970 971 972
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    nodeinfo->memory = memorySize / 1024; /* Scale from bytes to kilobytes */
    nodeinfo->cpus = cpuInfo_numCpuCores;
973
    nodeinfo->mhz = cpuInfo_hz / (1000 * 1000); /* Scale from hz to mhz */
974 975 976 977 978 979 980 981 982
    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 已提交
983 984
    result = 0;

985 986 987 988 989 990 991 992 993
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



994 995 996
static char *
esxGetCapabilities(virConnectPtr conn)
{
M
Matthias Bolte 已提交
997
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
998
    char *xml = virCapabilitiesFormatXML(priv->caps);
999 1000

    if (xml == NULL) {
1001
        virReportOOMError();
1002 1003 1004 1005 1006 1007 1008 1009
        return NULL;
    }

    return xml;
}



1010 1011 1012
static int
esxListDomains(virConnectPtr conn, int *ids, int maxids)
{
M
Matthias Bolte 已提交
1013
    bool success = false;
M
Matthias Bolte 已提交
1014
    esxPrivate *priv = conn->privateData;
1015 1016 1017 1018 1019 1020 1021
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;

    if (ids == NULL || maxids < 0) {
1022 1023
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
1024 1025 1026 1027 1028 1029
    }

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

1030
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1031
        return -1;
1032 1033
    }

1034
    if (esxVI_String_AppendValueToList(&propertyNameList,
1035
                                       "runtime.powerState") < 0 ||
1036
        esxVI_LookupObjectContentByType(priv->host, priv->host->vmFolder,
1037 1038 1039
                                        "VirtualMachine", propertyNameList,
                                        esxVI_Boolean_True,
                                        &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1040
        goto cleanup;
1041 1042 1043 1044
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
1045
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1046
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1047
            goto cleanup;
1048 1049 1050 1051 1052 1053 1054 1055 1056
        }

        if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

        if (esxUtil_ParseVirtualMachineIDString(virtualMachine->obj->value,
                                                &ids[count]) < 0 ||
            ids[count] <= 0) {
1057
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1058
                      _("Failed to parse positive integer from '%s'"),
1059
                      virtualMachine->obj->value);
M
Matthias Bolte 已提交
1060
            goto cleanup;
1061 1062 1063 1064 1065 1066 1067 1068 1069
        }

        count++;

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

M
Matthias Bolte 已提交
1070 1071
    success = true;

1072 1073 1074 1075
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
1076
    return success ? count : -1;
1077 1078 1079 1080 1081 1082 1083
}



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

1086
    if (esxVI_EnsureSession(priv->host) < 0) {
1087 1088 1089
        return -1;
    }

1090
    return esxVI_LookupNumberOfDomainsByPowerState
1091
             (priv->host, esxVI_VirtualMachinePowerState_PoweredOn,
1092 1093 1094 1095 1096 1097 1098 1099
              esxVI_Boolean_False);
}



static virDomainPtr
esxDomainLookupByID(virConnectPtr conn, int id)
{
M
Matthias Bolte 已提交
1100
    esxPrivate *priv = conn->privateData;
1101 1102 1103 1104
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
M
Matthias Bolte 已提交
1105 1106 1107
    int id_candidate = -1;
    char *name_candidate = NULL;
    unsigned char uuid_candidate[VIR_UUID_BUFLEN];
1108 1109
    virDomainPtr domain = NULL;

1110
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1111
        return NULL;
1112 1113
    }

1114
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1115
                                           "configStatus\0"
1116 1117
                                           "name\0"
                                           "runtime.powerState\0"
1118
                                           "config.uuid\0") < 0 ||
1119
        esxVI_LookupObjectContentByType(priv->host, priv->host->vmFolder,
1120 1121 1122
                                        "VirtualMachine", propertyNameList,
                                        esxVI_Boolean_True,
                                        &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1123
        goto cleanup;
1124 1125 1126 1127
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
1128
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1129
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1130
            goto cleanup;
1131 1132 1133 1134 1135 1136 1137
        }

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

M
Matthias Bolte 已提交
1138
        VIR_FREE(name_candidate);
1139

1140
        if (esxVI_GetVirtualMachineIdentity(virtualMachine,
M
Matthias Bolte 已提交
1141 1142
                                            &id_candidate, &name_candidate,
                                            uuid_candidate) < 0) {
M
Matthias Bolte 已提交
1143
            goto cleanup;
1144 1145
        }

M
Matthias Bolte 已提交
1146
        if (id != id_candidate) {
1147 1148 1149
            continue;
        }

M
Matthias Bolte 已提交
1150
        domain = virGetDomain(conn, name_candidate, uuid_candidate);
1151 1152

        if (domain == NULL) {
M
Matthias Bolte 已提交
1153
            goto cleanup;
1154 1155 1156 1157 1158 1159 1160 1161
        }

        domain->id = id;

        break;
    }

    if (domain == NULL) {
1162
        ESX_ERROR(VIR_ERR_NO_DOMAIN, _("No domain with ID %d"), id);
1163 1164 1165 1166 1167
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
M
Matthias Bolte 已提交
1168
    VIR_FREE(name_candidate);
1169 1170 1171 1172 1173 1174 1175 1176 1177

    return domain;
}



static virDomainPtr
esxDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
M
Matthias Bolte 已提交
1178
    esxPrivate *priv = conn->privateData;
1179 1180 1181
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1182 1183
    int id = -1;
    char *name = NULL;
1184 1185
    virDomainPtr domain = NULL;

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

1190
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1191
                                           "name\0"
1192
                                           "runtime.powerState\0") < 0 ||
1193 1194
        esxVI_LookupVirtualMachineByUuid(priv->host, uuid, propertyNameList,
                                         &virtualMachine,
M
Matthias Bolte 已提交
1195
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1196 1197
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, &name, NULL) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1198
        goto cleanup;
1199 1200
    }

1201
    domain = virGetDomain(conn, name, uuid);
1202 1203

    if (domain == NULL) {
M
Matthias Bolte 已提交
1204
        goto cleanup;
1205
    }
1206

1207 1208 1209 1210 1211
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1212 1213 1214 1215
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1216 1217
    esxVI_ObjectContent_Free(&virtualMachine);
    VIR_FREE(name);
1218 1219 1220 1221 1222 1223 1224 1225 1226

    return domain;
}



static virDomainPtr
esxDomainLookupByName(virConnectPtr conn, const char *name)
{
M
Matthias Bolte 已提交
1227
    esxPrivate *priv = conn->privateData;
1228 1229 1230
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1231 1232
    int id = -1;
    unsigned char uuid[VIR_UUID_BUFLEN];
1233 1234
    virDomainPtr domain = NULL;

1235
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1236
        return NULL;
1237 1238
    }

1239
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1240
                                           "configStatus\0"
1241
                                           "runtime.powerState\0"
1242
                                           "config.uuid\0") < 0 ||
1243 1244 1245
        esxVI_LookupVirtualMachineByName(priv->host, name, propertyNameList,
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
1246
        goto cleanup;
1247 1248
    }

1249
    if (virtualMachine == NULL) {
1250
        ESX_ERROR(VIR_ERR_NO_DOMAIN, _("No domain with name '%s'"), name);
M
Matthias Bolte 已提交
1251
        goto cleanup;
1252
    }
1253 1254


M
Matthias Bolte 已提交
1255 1256 1257
    if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, uuid) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
1258
    }
1259

1260
    domain = virGetDomain(conn, name, uuid);
1261

1262
    if (domain == NULL) {
M
Matthias Bolte 已提交
1263
        goto cleanup;
1264 1265
    }

1266 1267 1268 1269 1270
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1271 1272 1273 1274
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1275
    esxVI_ObjectContent_Free(&virtualMachine);
1276 1277 1278 1279 1280 1281 1282 1283 1284

    return domain;
}



static int
esxDomainSuspend(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1285
    int result = -1;
M
Matthias Bolte 已提交
1286
    esxPrivate *priv = domain->conn->privateData;
1287 1288 1289 1290 1291 1292
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

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

1297
    if (esxVI_String_AppendValueToList(&propertyNameList,
1298
                                       "runtime.powerState") < 0 ||
1299
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1300 1301 1302
          (priv->host, domain->uuid, propertyNameList, &virtualMachine,
           priv->autoAnswer) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1303
        goto cleanup;
1304 1305 1306
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1307 1308
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1309
        goto cleanup;
1310 1311
    }

1312 1313 1314
    if (esxVI_SuspendVM_Task(priv->host, virtualMachine->obj, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
1315
        goto cleanup;
1316 1317 1318
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1319
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not suspend domain"));
M
Matthias Bolte 已提交
1320
        goto cleanup;
1321 1322
    }

M
Matthias Bolte 已提交
1323 1324
    result = 0;

1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainResume(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1338
    int result = -1;
M
Matthias Bolte 已提交
1339
    esxPrivate *priv = domain->conn->privateData;
1340 1341 1342 1343 1344 1345
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1346
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1347
        return -1;
1348 1349
    }

1350
    if (esxVI_String_AppendValueToList(&propertyNameList,
1351
                                       "runtime.powerState") < 0 ||
1352
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1353 1354 1355
          (priv->host, domain->uuid, propertyNameList, &virtualMachine,
           priv->autoAnswer) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1356
        goto cleanup;
1357 1358 1359
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended) {
1360
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not suspended"));
M
Matthias Bolte 已提交
1361
        goto cleanup;
1362 1363
    }

1364 1365
    if (esxVI_PowerOnVM_Task(priv->host, virtualMachine->obj, NULL,
                             &task) < 0 ||
1366 1367
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
1368
        goto cleanup;
1369 1370 1371
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1372
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not resume domain"));
M
Matthias Bolte 已提交
1373
        goto cleanup;
1374 1375
    }

M
Matthias Bolte 已提交
1376 1377
    result = 0;

1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainShutdown(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1391
    int result = -1;
M
Matthias Bolte 已提交
1392
    esxPrivate *priv = domain->conn->privateData;
1393 1394 1395 1396
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1397
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1398
        return -1;
1399 1400
    }

1401
    if (esxVI_String_AppendValueToList(&propertyNameList,
1402
                                       "runtime.powerState") < 0 ||
1403 1404
        esxVI_LookupVirtualMachineByUuid(priv->host, domain->uuid,
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1405
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1406
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1407
        goto cleanup;
1408 1409 1410
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1411 1412
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1413
        goto cleanup;
1414 1415
    }

1416
    if (esxVI_ShutdownGuest(priv->host, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1417
        goto cleanup;
1418 1419
    }

M
Matthias Bolte 已提交
1420 1421
    result = 0;

1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
esxDomainReboot(virDomainPtr domain, unsigned int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
1434
    int result = -1;
M
Matthias Bolte 已提交
1435
    esxPrivate *priv = domain->conn->privateData;
1436 1437 1438 1439
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1440
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1441
        return -1;
1442 1443
    }

1444
    if (esxVI_String_AppendValueToList(&propertyNameList,
1445
                                       "runtime.powerState") < 0 ||
1446 1447
        esxVI_LookupVirtualMachineByUuid(priv->host, domain->uuid,
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1448
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1449
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1450
        goto cleanup;
1451 1452 1453
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1454 1455
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1456
        goto cleanup;
1457 1458
    }

1459
    if (esxVI_RebootGuest(priv->host, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1460
        goto cleanup;
1461 1462
    }

M
Matthias Bolte 已提交
1463 1464
    result = 0;

1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
esxDomainDestroy(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1477
    int result = -1;
M
Matthias Bolte 已提交
1478
    esxPrivate *priv = domain->conn->privateData;
1479
    esxVI_Context *ctx = NULL;
1480 1481 1482 1483 1484 1485
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1486 1487 1488 1489 1490 1491
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

1492
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
1493
        return -1;
1494 1495
    }

1496
    if (esxVI_String_AppendValueToList(&propertyNameList,
1497
                                       "runtime.powerState") < 0 ||
1498
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1499
          (ctx, domain->uuid, propertyNameList, &virtualMachine,
1500
           priv->autoAnswer) < 0 ||
1501
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1502
        goto cleanup;
1503 1504 1505
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1506 1507
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1508
        goto cleanup;
1509 1510
    }

1511 1512 1513
    if (esxVI_PowerOffVM_Task(ctx, virtualMachine->obj, &task) < 0 ||
        esxVI_WaitForTaskCompletion(ctx, task, domain->uuid, priv->autoAnswer,
                                    &taskInfoState) < 0) {
M
Matthias Bolte 已提交
1514
        goto cleanup;
1515 1516 1517
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1518
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not destroy domain"));
M
Matthias Bolte 已提交
1519
        goto cleanup;
1520 1521
    }

M
Matthias Bolte 已提交
1522 1523
    result = 0;

1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static char *
1535
esxDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED)
1536
{
1537 1538 1539
    char *osType = strdup("hvm");

    if (osType == NULL) {
1540
        virReportOOMError();
1541 1542 1543 1544
        return NULL;
    }

    return osType;
1545 1546 1547 1548 1549 1550 1551
}



static unsigned long
esxDomainGetMaxMemory(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1552
    esxPrivate *priv = domain->conn->privateData;
1553 1554 1555 1556 1557
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    unsigned long memoryMB = 0;

1558
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1559
        return 0;
1560 1561
    }

1562
    if (esxVI_String_AppendValueToList(&propertyNameList,
1563
                                       "config.hardware.memoryMB") < 0 ||
1564 1565
        esxVI_LookupVirtualMachineByUuid(priv->host, domain->uuid,
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1566
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
1567
        goto cleanup;
1568 1569 1570 1571 1572
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
1573
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1574
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1575
                goto cleanup;
1576 1577 1578
            }

            if (dynamicProperty->val->int32 < 0) {
1579 1580
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                          _("Got invalid memory size %d"),
1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
                          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 已提交
1604
    int result = -1;
M
Matthias Bolte 已提交
1605
    esxPrivate *priv = domain->conn->privateData;
1606 1607 1608 1609 1610
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1611
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1612
        return -1;
1613 1614
    }

1615
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1616
          (priv->host, domain->uuid, NULL, &virtualMachine,
1617
           priv->autoAnswer) < 0 ||
1618 1619
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Long_Alloc(&spec->memoryMB) < 0) {
M
Matthias Bolte 已提交
1620
        goto cleanup;
1621 1622 1623 1624 1625
    }

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

1626 1627 1628 1629
    if (esxVI_ReconfigVM_Task(priv->host, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
1630
        goto cleanup;
1631 1632 1633
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1634
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1635
                  _("Could not set max-memory to %lu kilobytes"), memory);
M
Matthias Bolte 已提交
1636
        goto cleanup;
1637 1638
    }

M
Matthias Bolte 已提交
1639 1640
    result = 0;

1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
  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 已提交
1654
    int result = -1;
M
Matthias Bolte 已提交
1655
    esxPrivate *priv = domain->conn->privateData;
1656 1657 1658 1659 1660
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1661
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1662
        return -1;
1663 1664
    }

1665
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1666
          (priv->host, domain->uuid, NULL, &virtualMachine,
1667
           priv->autoAnswer) < 0 ||
1668 1669 1670
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0 ||
        esxVI_Long_Alloc(&spec->memoryAllocation->limit) < 0) {
M
Matthias Bolte 已提交
1671
        goto cleanup;
1672 1673 1674 1675 1676
    }

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

1677 1678 1679 1680
    if (esxVI_ReconfigVM_Task(priv->host, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
1681
        goto cleanup;
1682 1683 1684
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1685
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1686
                  _("Could not set memory to %lu kilobytes"), memory);
M
Matthias Bolte 已提交
1687
        goto cleanup;
1688 1689
    }

M
Matthias Bolte 已提交
1690 1691
    result = 0;

1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
  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 已提交
1705
    int result = -1;
M
Matthias Bolte 已提交
1706
    esxPrivate *priv = domain->conn->privateData;
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
    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;
1719 1720
    esxVI_PerfEntityMetricBase *perfEntityMetricBase = NULL;
    esxVI_PerfEntityMetricBase *perfEntityMetricBaseList = NULL;
1721 1722 1723 1724
    esxVI_PerfEntityMetric *perfEntityMetric = NULL;
    esxVI_PerfMetricIntSeries *perfMetricIntSeries = NULL;
    esxVI_Long *value = NULL;

M
Matthias Bolte 已提交
1725 1726
    memset(info, 0, sizeof (*info));

1727
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1728
        return -1;
1729 1730
    }

1731
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1732 1733 1734 1735
                                           "runtime.powerState\0"
                                           "config.hardware.memoryMB\0"
                                           "config.hardware.numCPU\0"
                                           "config.memoryAllocation.limit\0") < 0 ||
1736 1737
        esxVI_LookupVirtualMachineByUuid(priv->host, domain->uuid,
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1738
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
1739
        goto cleanup;
1740 1741 1742 1743 1744 1745 1746 1747
    }

    info->state = VIR_DOMAIN_NOSTATE;

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

1752 1753
            info->state = esxVI_VirtualMachinePowerState_ConvertToLibvirt
                            (powerState);
1754
        } else if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
1755
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1756
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1757
                goto cleanup;
1758 1759 1760 1761
            }

            info->maxMem = dynamicProperty->val->int32 * 1024; /* Scale from megabyte to kilobyte */
        } else if (STREQ(dynamicProperty->name, "config.hardware.numCPU")) {
1762
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1763
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1764
                goto cleanup;
1765 1766 1767 1768 1769
            }

            info->nrVirtCpu = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "config.memoryAllocation.limit")) {
1770
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1771
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1772
                goto cleanup;
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
            }

            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 */
    if (info->state == VIR_DOMAIN_RUNNING && priv->usedCpuTimeCounterId >= 0) {
1790
        if (esxVI_Int_Alloc(&counterId) < 0) {
M
Matthias Bolte 已提交
1791
            goto cleanup;
1792 1793 1794 1795
        }

        counterId->value = priv->usedCpuTimeCounterId;

1796
        if (esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
M
Matthias Bolte 已提交
1797
            goto cleanup;
1798 1799
        }

1800
        if (esxVI_QueryPerfCounter(priv->host, counterIdList,
1801
                                   &perfCounterInfo) < 0) {
M
Matthias Bolte 已提交
1802
            goto cleanup;
1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822
        }

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

            priv->usedCpuTimeCounterId = -1;
        }

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

    /*
     * 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) {
1823 1824 1825
        if (esxVI_QueryAvailablePerfMetric(priv->host, virtualMachine->obj,
                                           NULL, NULL, NULL,
                                           &perfMetricIdList) < 0) {
M
Matthias Bolte 已提交
1826
            goto cleanup;
1827 1828 1829 1830 1831 1832 1833 1834 1835
        }

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

            counterId = NULL;

1836 1837
            if (esxVI_Int_DeepCopy(&counterId, perfMetricId->counterId) < 0 ||
                esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
M
Matthias Bolte 已提交
1838
                goto cleanup;
1839 1840 1841
            }
        }

1842
        if (esxVI_QueryPerfCounter(priv->host, counterIdList,
1843
                                   &perfCounterInfoList) < 0) {
M
Matthias Bolte 已提交
1844
            goto cleanup;
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
        }

        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;
            }
        }

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

    /*
     * 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);

1878 1879 1880 1881
        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) {
M
Matthias Bolte 已提交
1882
            goto cleanup;
1883 1884 1885 1886 1887 1888 1889 1890
        }

        querySpec->entity = virtualMachine->obj;
        querySpec->maxSample->value = 1;
        querySpec->metricId->counterId->value = priv->usedCpuTimeCounterId;
        querySpec->metricId->instance = (char *)"";
        querySpec->format = (char *)"normal";

1891 1892
        if (esxVI_QueryPerf(priv->host, querySpec,
                            &perfEntityMetricBaseList) < 0) {
1893 1894 1895
            querySpec->entity = NULL;
            querySpec->metricId->instance = NULL;
            querySpec->format = NULL;
M
Matthias Bolte 已提交
1896
            goto cleanup;
1897 1898
        }

1899 1900 1901
        for (perfEntityMetricBase = perfEntityMetricBaseList;
             perfEntityMetricBase != NULL;
             perfEntityMetricBase = perfEntityMetricBase->_next) {
1902 1903
            VIR_DEBUG0("perfEntityMetric ...");

1904 1905 1906 1907
            perfEntityMetric =
              esxVI_PerfEntityMetric_DynamicCast(perfEntityMetricBase);

            if (perfMetricIntSeries == NULL) {
1908
                VIR_ERROR0(_("QueryPerf returned object with unexpected type"));
1909 1910
            }

1911 1912 1913 1914
            perfMetricIntSeries =
              esxVI_PerfMetricIntSeries_DynamicCast(perfEntityMetric->value);

            if (perfMetricIntSeries == NULL) {
1915
                VIR_ERROR0(_("QueryPerf returned object with unexpected type"));
1916 1917 1918
            }

            for (; perfMetricIntSeries != NULL;
1919 1920 1921 1922 1923 1924
                 perfMetricIntSeries = perfMetricIntSeries->_next) {
                VIR_DEBUG0("perfMetricIntSeries ...");

                for (value = perfMetricIntSeries->value;
                     value != NULL;
                     value = value->_next) {
1925
                    VIR_DEBUG("value %lld", (long long int)value->value);
1926 1927 1928 1929 1930 1931 1932 1933 1934
                }
            }
        }

        querySpec->entity = NULL;
        querySpec->metricId->instance = NULL;
        querySpec->format = NULL;

        VIR_DEBUG("usedCpuTimeCounterId %d END", priv->usedCpuTimeCounterId);
M
Matthias Bolte 已提交
1935 1936 1937 1938 1939

        /*
         * FIXME: Cannot map between realtive used-cpu-time and absolute
         *        info->cpuTime
         */
1940 1941
    }

M
Matthias Bolte 已提交
1942 1943
    result = 0;

1944 1945 1946 1947 1948 1949 1950
  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);
1951
    esxVI_PerfEntityMetricBase_Free(&perfEntityMetricBaseList);
1952 1953 1954 1955 1956 1957 1958 1959 1960

    return result;
}



static int
esxDomainSetVcpus(virDomainPtr domain, unsigned int nvcpus)
{
M
Matthias Bolte 已提交
1961
    int result = -1;
M
Matthias Bolte 已提交
1962
    esxPrivate *priv = domain->conn->privateData;
M
Matthias Bolte 已提交
1963
    int maxVcpus;
1964 1965 1966 1967 1968 1969
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

    if (nvcpus < 1) {
1970 1971
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Requested number of virtual CPUs must at least be 1"));
M
Matthias Bolte 已提交
1972
        return -1;
1973 1974
    }

1975
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1976
        return -1;
1977 1978
    }

M
Matthias Bolte 已提交
1979
    maxVcpus = esxDomainGetMaxVcpus(domain);
1980

M
Matthias Bolte 已提交
1981
    if (maxVcpus < 0) {
M
Matthias Bolte 已提交
1982
        return -1;
1983 1984
    }

M
Matthias Bolte 已提交
1985
    if (nvcpus > maxVcpus) {
1986
        ESX_ERROR(VIR_ERR_INVALID_ARG,
1987 1988
                  _("Requested number of virtual CPUs is greater than max "
                    "allowable number of virtual CPUs for the domain: %d > %d"),
M
Matthias Bolte 已提交
1989
                  nvcpus, maxVcpus);
M
Matthias Bolte 已提交
1990
        return -1;
1991 1992
    }

1993
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1994
          (priv->host, domain->uuid, NULL, &virtualMachine,
1995
           priv->autoAnswer) < 0 ||
1996 1997
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Int_Alloc(&spec->numCPUs) < 0) {
M
Matthias Bolte 已提交
1998
        goto cleanup;
1999 2000 2001 2002
    }

    spec->numCPUs->value = nvcpus;

2003 2004 2005 2006
    if (esxVI_ReconfigVM_Task(priv->host, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2007
        goto cleanup;
2008 2009 2010
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2011
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2012
                  _("Could not set number of virtual CPUs to %d"), nvcpus);
M
Matthias Bolte 已提交
2013
        goto cleanup;
2014 2015
    }

M
Matthias Bolte 已提交
2016 2017
    result = 0;

2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainGetMaxVcpus(virDomainPtr domain)
{
M
Matthias Bolte 已提交
2031
    esxPrivate *priv = domain->conn->privateData;
2032 2033 2034 2035
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

M
Matthias Bolte 已提交
2036 2037
    if (priv->maxVcpus > 0) {
        return priv->maxVcpus;
2038 2039
    }

M
Matthias Bolte 已提交
2040 2041
    priv->maxVcpus = -1;

2042
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
2043
        return -1;
2044 2045
    }

2046
    if (esxVI_String_AppendValueToList(&propertyNameList,
2047
                                       "capability.maxSupportedVcpus") < 0 ||
2048 2049 2050
        esxVI_LookupObjectContentByType(priv->host, priv->host->hostFolder,
                                        "HostSystem", propertyNameList,
                                        esxVI_Boolean_True, &hostSystem) < 0) {
M
Matthias Bolte 已提交
2051
        goto cleanup;
2052 2053 2054
    }

    if (hostSystem == NULL) {
2055 2056
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
2057
        goto cleanup;
2058 2059 2060 2061 2062
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "capability.maxSupportedVcpus")) {
2063
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2064
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2065
                goto cleanup;
2066 2067
            }

M
Matthias Bolte 已提交
2068
            priv->maxVcpus = dynamicProperty->val->int32;
2069 2070 2071 2072 2073 2074 2075 2076 2077 2078
            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

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

M
Matthias Bolte 已提交
2079
    return priv->maxVcpus;
2080 2081 2082 2083 2084 2085 2086
}



static char *
esxDomainDumpXML(virDomainPtr domain, int flags)
{
M
Matthias Bolte 已提交
2087
    esxPrivate *priv = domain->conn->privateData;
2088 2089 2090 2091 2092
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    const char *vmPathName = NULL;
    char *datastoreName = NULL;
M
Matthias Bolte 已提交
2093 2094
    char *directoryName = NULL;
    char *fileName = NULL;
2095
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
2096 2097 2098 2099 2100
    char *url = NULL;
    char *vmx = NULL;
    virDomainDefPtr def = NULL;
    char *xml = NULL;

2101
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
2102
        return NULL;
2103 2104
    }

2105
    if (esxVI_String_AppendValueToList(&propertyNameList,
2106
                                       "config.files.vmPathName") < 0 ||
2107 2108
        esxVI_LookupVirtualMachineByUuid(priv->host, domain->uuid,
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2109
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2110
        goto cleanup;
2111 2112 2113 2114 2115
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.files.vmPathName")) {
2116
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2117
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
2118
                goto cleanup;
2119 2120 2121 2122 2123 2124 2125
            }

            vmPathName = dynamicProperty->val->string;
            break;
        }
    }

2126 2127
    if (esxUtil_ParseDatastoreRelatedPath(vmPathName, &datastoreName,
                                          &directoryName, &fileName) < 0) {
M
Matthias Bolte 已提交
2128
        goto cleanup;
2129 2130
    }

2131 2132
    virBufferVSprintf(&buffer, "%s://%s:%d/folder/", priv->transport,
                      domain->conn->uri->server, domain->conn->uri->port);
M
Matthias Bolte 已提交
2133 2134 2135 2136 2137 2138 2139

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

    virBufferURIEncodeString(&buffer, fileName);
2140 2141 2142 2143 2144 2145
    virBufferAddLit(&buffer, "?dcPath=");
    virBufferURIEncodeString(&buffer, priv->host->datacenter->value);
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
2146
        virReportOOMError();
M
Matthias Bolte 已提交
2147
        goto cleanup;
2148 2149
    }

2150 2151
    url = virBufferContentAndReset(&buffer);

2152
    if (esxVI_Context_DownloadFile(priv->host, url, &vmx) < 0) {
M
Matthias Bolte 已提交
2153
        goto cleanup;
2154 2155
    }

2156 2157
    def = esxVMX_ParseConfig(priv->host, priv->caps, vmx, datastoreName,
                             directoryName, priv->host->productVersion);
2158 2159

    if (def != NULL) {
2160
        xml = virDomainDefFormat(def, flags);
2161 2162 2163
    }

  cleanup:
M
Matthias Bolte 已提交
2164 2165 2166 2167
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

2168 2169
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2170
    VIR_FREE(datastoreName);
M
Matthias Bolte 已提交
2171 2172
    VIR_FREE(directoryName);
    VIR_FREE(fileName);
2173 2174
    VIR_FREE(url);
    VIR_FREE(vmx);
2175
    virDomainDefFree(def);
2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186

    return xml;
}



static char *
esxDomainXMLFromNative(virConnectPtr conn, const char *nativeFormat,
                       const char *nativeConfig,
                       unsigned int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2187
    esxPrivate *priv = conn->privateData;
2188 2189 2190 2191
    virDomainDefPtr def = NULL;
    char *xml = NULL;

    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2192
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2193
                  _("Unsupported config format '%s'"), nativeFormat);
2194
        return NULL;
2195 2196
    }

2197
    def = esxVMX_ParseConfig(priv->host, priv->caps, nativeConfig, "?", "?",
2198
                             priv->host->productVersion);
2199 2200

    if (def != NULL) {
2201
        xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
2202 2203 2204 2205 2206 2207 2208 2209 2210
    }

    virDomainDefFree(def);

    return xml;
}



M
Matthias Bolte 已提交
2211 2212 2213 2214 2215
static char *
esxDomainXMLToNative(virConnectPtr conn, const char *nativeFormat,
                     const char *domainXml,
                     unsigned int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2216
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
2217 2218 2219 2220
    virDomainDefPtr def = NULL;
    char *vmx = NULL;

    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2221
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2222
                  _("Unsupported config format '%s'"), nativeFormat);
M
Matthias Bolte 已提交
2223 2224 2225
        return NULL;
    }

2226
    def = virDomainDefParseString(priv->caps, domainXml, 0);
M
Matthias Bolte 已提交
2227 2228 2229 2230 2231

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

2232 2233
    vmx = esxVMX_FormatConfig(priv->host, priv->caps, def,
                              priv->host->productVersion);
M
Matthias Bolte 已提交
2234 2235 2236 2237 2238 2239 2240 2241

    virDomainDefFree(def);

    return vmx;
}



2242 2243 2244
static int
esxListDefinedDomains(virConnectPtr conn, char **const names, int maxnames)
{
M
Matthias Bolte 已提交
2245
    bool success = false;
M
Matthias Bolte 已提交
2246
    esxPrivate *priv = conn->privateData;
2247 2248 2249 2250 2251 2252
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;
2253
    int i;
2254 2255

    if (names == NULL || maxnames < 0) {
2256 2257
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
2258 2259 2260 2261 2262 2263
    }

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

2264
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
2265
        return -1;
2266 2267
    }

2268
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2269 2270
                                           "name\0"
                                           "runtime.powerState\0") < 0 ||
2271
        esxVI_LookupObjectContentByType(priv->host, priv->host->vmFolder,
2272 2273 2274
                                        "VirtualMachine", propertyNameList,
                                        esxVI_Boolean_True,
                                        &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2275
        goto cleanup;
2276 2277 2278 2279
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
2280
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
2281
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
2282
            goto cleanup;
2283 2284 2285 2286 2287 2288 2289 2290 2291 2292
        }

        if (powerState == esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

        for (dynamicProperty = virtualMachine->propSet;
             dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "name")) {
2293
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2294
                                             esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
2295
                    goto cleanup;
2296 2297 2298 2299 2300
                }

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

                if (names[count] == NULL) {
2301
                    virReportOOMError();
M
Matthias Bolte 已提交
2302
                    goto cleanup;
2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314
                }

                count++;
                break;
            }
        }

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

M
Matthias Bolte 已提交
2315
    success = true;
2316

M
Matthias Bolte 已提交
2317 2318 2319 2320 2321
  cleanup:
    if (! success) {
        for (i = 0; i < count; ++i) {
            VIR_FREE(names[i]);
        }
2322

M
Matthias Bolte 已提交
2323
        count = -1;
2324 2325
    }

M
Matthias Bolte 已提交
2326 2327
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
2328

M
Matthias Bolte 已提交
2329
    return count;
2330 2331 2332 2333 2334 2335 2336
}



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

2339
    if (esxVI_EnsureSession(priv->host) < 0) {
2340 2341 2342
        return -1;
    }

2343
    return esxVI_LookupNumberOfDomainsByPowerState
2344
             (priv->host, esxVI_VirtualMachinePowerState_PoweredOn,
2345 2346 2347 2348 2349 2350
              esxVI_Boolean_True);
}



static int
2351
esxDomainCreateWithFlags(virDomainPtr domain, unsigned int flags)
2352
{
M
Matthias Bolte 已提交
2353
    int result = -1;
M
Matthias Bolte 已提交
2354
    esxPrivate *priv = domain->conn->privateData;
2355 2356 2357 2358 2359 2360
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

2361 2362
    virCheckFlags(0, -1);

2363
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
2364
        return -1;
2365 2366
    }

2367
    if (esxVI_String_AppendValueToList(&propertyNameList,
2368
                                       "runtime.powerState") < 0 ||
2369
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2370 2371 2372
          (priv->host, domain->uuid, propertyNameList, &virtualMachine,
           priv->autoAnswer) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine,
2373
                                          &powerState) < 0) {
M
Matthias Bolte 已提交
2374
        goto cleanup;
2375 2376 2377
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2378 2379
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered off"));
M
Matthias Bolte 已提交
2380
        goto cleanup;
2381 2382
    }

2383 2384
    if (esxVI_PowerOnVM_Task(priv->host, virtualMachine->obj, NULL,
                             &task) < 0 ||
2385 2386
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2387
        goto cleanup;
2388 2389 2390
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2391
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not start domain"));
M
Matthias Bolte 已提交
2392
        goto cleanup;
2393 2394
    }

M
Matthias Bolte 已提交
2395 2396
    result = 0;

2397 2398 2399 2400 2401 2402 2403 2404
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}

2405 2406 2407 2408 2409
static int
esxDomainCreate(virDomainPtr domain)
{
    return esxDomainCreateWithFlags(domain, 0);
}
2410

M
Matthias Bolte 已提交
2411 2412 2413
static virDomainPtr
esxDomainDefineXML(virConnectPtr conn, const char *xml ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2414
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
2415 2416
    virDomainDefPtr def = NULL;
    char *vmx = NULL;
2417 2418
    int i;
    virDomainDiskDefPtr disk = NULL;
M
Matthias Bolte 已提交
2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432
    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;

2433
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
2434
        return NULL;
M
Matthias Bolte 已提交
2435 2436 2437
    }

    /* Parse domain XML */
2438
    def = virDomainDefParseString(priv->caps, xml,
M
Matthias Bolte 已提交
2439 2440 2441
                                  VIR_DOMAIN_XML_INACTIVE);

    if (def == NULL) {
M
Matthias Bolte 已提交
2442
        return NULL;
M
Matthias Bolte 已提交
2443 2444 2445
    }

    /* Check if an existing domain should be edited */
2446
    if (esxVI_LookupVirtualMachineByUuid(priv->host, def->uuid, NULL,
M
Matthias Bolte 已提交
2447
                                         &virtualMachine,
M
Matthias Bolte 已提交
2448
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
2449
        goto cleanup;
M
Matthias Bolte 已提交
2450 2451 2452 2453
    }

    if (virtualMachine != NULL) {
        /* FIXME */
2454 2455 2456
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Domain already exists, editing existing domains is not "
                    "supported yet"));
M
Matthias Bolte 已提交
2457
        goto cleanup;
M
Matthias Bolte 已提交
2458 2459 2460
    }

    /* Build VMX from domain XML */
2461 2462
    vmx = esxVMX_FormatConfig(priv->host, priv->caps, def,
                              priv->host->productVersion);
M
Matthias Bolte 已提交
2463 2464

    if (vmx == NULL) {
M
Matthias Bolte 已提交
2465
        goto cleanup;
M
Matthias Bolte 已提交
2466 2467
    }

2468 2469 2470 2471 2472 2473 2474
    /*
     * 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 已提交
2475
    if (def->ndisks < 1) {
2476 2477 2478
        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 已提交
2479
        goto cleanup;
2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490
    }

    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) {
2491 2492 2493
        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 已提交
2494
        goto cleanup;
M
Matthias Bolte 已提交
2495 2496
    }

2497
    if (disk->src == NULL) {
2498 2499 2500
        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 已提交
2501
        goto cleanup;
M
Matthias Bolte 已提交
2502 2503
    }

2504
    if (esxUtil_ParseDatastoreRelatedPath(disk->src, &datastoreName,
2505
                                          &directoryName, &fileName) < 0) {
M
Matthias Bolte 已提交
2506
        goto cleanup;
M
Matthias Bolte 已提交
2507 2508
    }

2509
    if (! virFileHasSuffix(fileName, ".vmdk")) {
2510
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2511 2512
                  _("Expecting source '%s' of first file-based harddisk to "
                    "be a VMDK image"), disk->src);
M
Matthias Bolte 已提交
2513
        goto cleanup;
M
Matthias Bolte 已提交
2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530
    }

    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=");
    virBufferURIEncodeString(&buffer, priv->host->datacenter->value);
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
2531
        virReportOOMError();
M
Matthias Bolte 已提交
2532
        goto cleanup;
M
Matthias Bolte 已提交
2533 2534 2535 2536 2537 2538 2539
    }

    url = virBufferContentAndReset(&buffer);

    if (directoryName != NULL) {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s/%s.vmx", datastoreName,
                        directoryName, def->name) < 0) {
2540
            virReportOOMError();
M
Matthias Bolte 已提交
2541
            goto cleanup;
M
Matthias Bolte 已提交
2542 2543 2544 2545
        }
    } else {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s.vmx", datastoreName,
                        def->name) < 0) {
2546
            virReportOOMError();
M
Matthias Bolte 已提交
2547
            goto cleanup;
M
Matthias Bolte 已提交
2548 2549 2550 2551
        }
    }

    /* Get resource pool */
2552 2553
    if (esxVI_String_AppendValueToList(&propertyNameList, "parent") < 0 ||
        esxVI_LookupHostSystemByIp(priv->host, priv->host->ipAddress,
M
Matthias Bolte 已提交
2554
                                   propertyNameList, &hostSystem) < 0) {
M
Matthias Bolte 已提交
2555
        goto cleanup;
M
Matthias Bolte 已提交
2556 2557
    }

2558
    if (esxVI_LookupResourcePoolByHostSystem(priv->host, hostSystem,
2559
                                             &resourcePool) < 0) {
M
Matthias Bolte 已提交
2560
        goto cleanup;
M
Matthias Bolte 已提交
2561 2562 2563 2564 2565 2566
    }

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

    /* Upload VMX file */
2567
    if (esxVI_Context_UploadFile(priv->host, url, vmx) < 0) {
M
Matthias Bolte 已提交
2568
        goto cleanup;
M
Matthias Bolte 已提交
2569 2570 2571
    }

    /* Register the domain */
2572
    if (esxVI_RegisterVM_Task(priv->host, priv->host->vmFolder,
M
Matthias Bolte 已提交
2573 2574
                              datastoreRelatedPath, NULL, esxVI_Boolean_False,
                              resourcePool, hostSystem->obj, &task) < 0 ||
2575 2576
        esxVI_WaitForTaskCompletion(priv->host, task, def->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2577
        goto cleanup;
M
Matthias Bolte 已提交
2578 2579 2580
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2581
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not define domain"));
M
Matthias Bolte 已提交
2582
        goto cleanup;
M
Matthias Bolte 已提交
2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593
    }

    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 已提交
2594 2595 2596 2597
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

M
Matthias Bolte 已提交
2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615
    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;
}



2616 2617 2618
static int
esxDomainUndefine(virDomainPtr domain)
{
M
Matthias Bolte 已提交
2619
    int result = -1;
M
Matthias Bolte 已提交
2620
    esxPrivate *priv = domain->conn->privateData;
2621
    esxVI_Context *ctx = NULL;
2622 2623 2624 2625
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

2626 2627 2628 2629 2630 2631
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

2632
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
2633
        return -1;
2634 2635
    }

2636
    if (esxVI_String_AppendValueToList(&propertyNameList,
2637
                                       "runtime.powerState") < 0 ||
2638 2639
        esxVI_LookupVirtualMachineByUuid(ctx, domain->uuid, propertyNameList,
                                         &virtualMachine,
M
Matthias Bolte 已提交
2640
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2641
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
2642
        goto cleanup;
2643 2644 2645 2646
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended &&
        powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2647 2648
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not suspended or powered off"));
M
Matthias Bolte 已提交
2649
        goto cleanup;
2650 2651
    }

2652
    if (esxVI_UnregisterVM(ctx, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
2653
        goto cleanup;
2654 2655
    }

M
Matthias Bolte 已提交
2656 2657
    result = 0;

2658 2659 2660 2661 2662 2663 2664 2665 2666
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678
/*
 * 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)
 *
2679
 *   The amount of CPU resource that is guaranteed to be available to the domain.
2680 2681 2682 2683
 *
 *
 * - limit (VIR_DOMAIN_SCHED_FIELD_LLONG >= 0, or -1, in megaherz)
 *
2684 2685
 *   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
2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696
 *   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'.
 */
2697
static char *
2698
esxDomainGetSchedulerType(virDomainPtr domain ATTRIBUTE_UNUSED, int *nparams)
2699 2700 2701 2702
{
    char *type = strdup("allocation");

    if (type == NULL) {
2703
        virReportOOMError();
2704
        return NULL;
2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717
    }

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

    return type;
}



static int
esxDomainGetSchedulerParameters(virDomainPtr domain,
                                virSchedParameterPtr params, int *nparams)
{
M
Matthias Bolte 已提交
2718
    int result = -1;
M
Matthias Bolte 已提交
2719
    esxPrivate *priv = domain->conn->privateData;
2720 2721 2722 2723 2724 2725 2726 2727
    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) {
2728 2729
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Parameter array must have space for 3 items"));
M
Matthias Bolte 已提交
2730
        return -1;
2731 2732
    }

2733
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
2734
        return -1;
2735 2736
    }

2737
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2738 2739 2740
                                           "config.cpuAllocation.reservation\0"
                                           "config.cpuAllocation.limit\0"
                                           "config.cpuAllocation.shares\0") < 0 ||
2741 2742
        esxVI_LookupVirtualMachineByUuid(priv->host, domain->uuid,
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2743
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2744
        goto cleanup;
2745 2746 2747 2748 2749 2750
    }

    for (dynamicProperty = virtualMachine->propSet;
         dynamicProperty != NULL && mask != 7 && i < 3;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.cpuAllocation.reservation") &&
M
Matthias Bolte 已提交
2751
            ! (mask & (1 << 0))) {
2752 2753 2754 2755 2756
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "reservation");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_LLONG;

2757
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2758
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
2759
                goto cleanup;
2760 2761 2762 2763 2764 2765 2766
            }

            params[i].value.l = dynamicProperty->val->int64;
            mask |= 1 << 0;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.limit") &&
M
Matthias Bolte 已提交
2767
                   ! (mask & (1 << 1))) {
2768 2769 2770 2771 2772
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "limit");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_LLONG;

2773
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2774
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
2775
                goto cleanup;
2776 2777 2778 2779 2780 2781 2782
            }

            params[i].value.l = dynamicProperty->val->int64;
            mask |= 1 << 1;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.shares") &&
M
Matthias Bolte 已提交
2783
                   ! (mask & (1 << 2))) {
2784 2785 2786 2787 2788
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "shares");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_INT;

2789
            if (esxVI_SharesInfo_CastFromAnyType(dynamicProperty->val,
2790
                                                 &sharesInfo) < 0) {
M
Matthias Bolte 已提交
2791
                goto cleanup;
2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811
            }

            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:
2812
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2813
                          _("Shares level has unknown value %d"),
2814
                          (int)sharesInfo->level);
M
Matthias Bolte 已提交
2815
                goto cleanup;
2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827
            }

            esxVI_SharesInfo_Free(&sharesInfo);

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

    *nparams = i;
M
Matthias Bolte 已提交
2828
    result = 0;
2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842

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

    return result;
}



static int
esxDomainSetSchedulerParameters(virDomainPtr domain,
                                virSchedParameterPtr params, int nparams)
{
M
Matthias Bolte 已提交
2843
    int result = -1;
M
Matthias Bolte 已提交
2844
    esxPrivate *priv = domain->conn->privateData;
2845 2846 2847 2848 2849 2850 2851
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
    int i;

2852
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
2853
        return -1;
2854 2855
    }

2856
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2857
          (priv->host, domain->uuid, NULL, &virtualMachine,
2858
           priv->autoAnswer) < 0 ||
2859 2860
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->cpuAllocation) < 0) {
M
Matthias Bolte 已提交
2861
        goto cleanup;
2862 2863 2864 2865 2866
    }

    for (i = 0; i < nparams; ++i) {
        if (STREQ (params[i].field, "reservation") &&
            params[i].type == VIR_DOMAIN_SCHED_FIELD_LLONG) {
2867
            if (esxVI_Long_Alloc(&spec->cpuAllocation->reservation) < 0) {
M
Matthias Bolte 已提交
2868
                goto cleanup;
2869 2870 2871
            }

            if (params[i].value.l < 0) {
2872
                ESX_ERROR(VIR_ERR_INVALID_ARG,
2873 2874
                          _("Could not set reservation to %lld MHz, expecting "
                            "positive value"), params[i].value.l);
M
Matthias Bolte 已提交
2875
                goto cleanup;
2876 2877 2878 2879 2880
            }

            spec->cpuAllocation->reservation->value = params[i].value.l;
        } else if (STREQ (params[i].field, "limit") &&
                   params[i].type == VIR_DOMAIN_SCHED_FIELD_LLONG) {
2881
            if (esxVI_Long_Alloc(&spec->cpuAllocation->limit) < 0) {
M
Matthias Bolte 已提交
2882
                goto cleanup;
2883 2884 2885
            }

            if (params[i].value.l < -1) {
2886
                ESX_ERROR(VIR_ERR_INVALID_ARG,
2887 2888
                          _("Could not set limit to %lld MHz, expecting "
                            "positive value or -1 (unlimited)"),
2889
                          params[i].value.l);
M
Matthias Bolte 已提交
2890
                goto cleanup;
2891 2892 2893 2894
            }

            spec->cpuAllocation->limit->value = params[i].value.l;
        } else if (STREQ (params[i].field, "shares") &&
2895
                   params[i].type == VIR_DOMAIN_SCHED_FIELD_INT) {
2896 2897
            if (esxVI_SharesInfo_Alloc(&sharesInfo) < 0 ||
                esxVI_Int_Alloc(&sharesInfo->shares) < 0) {
M
Matthias Bolte 已提交
2898
                goto cleanup;
2899 2900 2901 2902
            }

            spec->cpuAllocation->shares = sharesInfo;

2903
            if (params[i].value.i >= 0) {
2904
                spec->cpuAllocation->shares->level = esxVI_SharesLevel_Custom;
2905
                spec->cpuAllocation->shares->shares->value = params[i].value.i;
2906
            } else {
2907
                switch (params[i].value.i) {
2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925
                  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:
2926
                    ESX_ERROR(VIR_ERR_INVALID_ARG,
2927 2928
                              _("Could not set shares to %d, expecting positive "
                                "value or -1 (low), -2 (normal) or -3 (high)"),
2929
                              params[i].value.i);
M
Matthias Bolte 已提交
2930
                    goto cleanup;
2931 2932 2933
                }
            }
        } else {
2934
            ESX_ERROR(VIR_ERR_INVALID_ARG, _("Unknown field '%s'"),
2935
                      params[i].field);
M
Matthias Bolte 已提交
2936
            goto cleanup;
2937 2938 2939
        }
    }

2940 2941 2942 2943
    if (esxVI_ReconfigVM_Task(priv->host, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2944
        goto cleanup;
2945 2946 2947
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2948 2949
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not change scheduler parameters"));
M
Matthias Bolte 已提交
2950
        goto cleanup;
2951 2952
    }

M
Matthias Bolte 已提交
2953 2954
    result = 0;

2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973
  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,
                        const char *uri_in, char **uri_out,
                        unsigned long flags ATTRIBUTE_UNUSED,
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2974
    int result = -1;
2975
    esxUtil_ParsedQuery *parsedQuery = NULL;
2976 2977

    if (uri_in == NULL) {
2978
        if (esxUtil_ParseQuery(&parsedQuery, dconn->uri) < 0) {
2979 2980 2981
            return -1;
        }

2982
        if (virAsprintf(uri_out, "%s://%s:%d/sdk", parsedQuery->transport,
2983
                        dconn->uri->server, dconn->uri->port) < 0) {
2984
            virReportOOMError();
M
Matthias Bolte 已提交
2985
            goto cleanup;
2986 2987 2988
        }
    }

M
Matthias Bolte 已提交
2989 2990
    result = 0;

2991
  cleanup:
2992
    esxUtil_FreeParsedQuery(&parsedQuery);
2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007

    return result;
}



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 已提交
3008
    int result = -1;
M
Matthias Bolte 已提交
3009
    esxPrivate *priv = domain->conn->privateData;
3010
    xmlURIPtr xmlUri = NULL;
M
Matthias Bolte 已提交
3011
    char hostIpAddress[NI_MAXHOST] = "";
3012 3013 3014 3015 3016 3017 3018 3019
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_ManagedObjectReference *resourcePool = NULL;
    esxVI_Event *eventList = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

M
Matthias Bolte 已提交
3020
    if (priv->vCenter == NULL) {
3021 3022
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Migration not possible without a vCenter"));
M
Matthias Bolte 已提交
3023
        return -1;
3024 3025 3026
    }

    if (dname != NULL) {
3027 3028
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Renaming domains on migration not supported"));
M
Matthias Bolte 已提交
3029
        return -1;
3030 3031
    }

3032
    if (esxVI_EnsureSession(priv->vCenter) < 0) {
M
Matthias Bolte 已提交
3033
        return -1;
3034 3035 3036 3037 3038 3039
    }

    /* Parse the destination URI and resolve the hostname */
    xmlUri = xmlParseURI(uri);

    if (xmlUri == NULL) {
3040
        virReportOOMError();
M
Matthias Bolte 已提交
3041
        return -1;
3042 3043
    }

3044
    if (esxUtil_ResolveHostname(xmlUri->server, hostIpAddress,
3045
                                NI_MAXHOST) < 0) {
M
Matthias Bolte 已提交
3046
        goto cleanup;
3047 3048 3049
    }

    /* Lookup VirtualMachine, HostSystem and ResourcePool */
3050
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3051
          (priv->vCenter, domain->uuid, NULL, &virtualMachine,
3052
           priv->autoAnswer) < 0 ||
3053 3054
        esxVI_String_AppendValueToList(&propertyNameList, "parent") < 0 ||
        esxVI_LookupHostSystemByIp(priv->vCenter, hostIpAddress,
M
Matthias Bolte 已提交
3055
                                   propertyNameList, &hostSystem) < 0) {
M
Matthias Bolte 已提交
3056
        goto cleanup;
3057 3058
    }

3059 3060
    if (esxVI_LookupResourcePoolByHostSystem(priv->vCenter, hostSystem,
                                             &resourcePool) < 0) {
M
Matthias Bolte 已提交
3061
        goto cleanup;
3062 3063 3064
    }

    /* Validate the purposed migration */
3065
    if (esxVI_ValidateMigration(priv->vCenter, virtualMachine->obj,
3066 3067 3068
                                esxVI_VirtualMachinePowerState_Undefined,
                                NULL, resourcePool, hostSystem->obj,
                                &eventList) < 0) {
M
Matthias Bolte 已提交
3069
        goto cleanup;
3070 3071 3072 3073 3074 3075 3076 3077
    }

    if (eventList != NULL) {
        /*
         * FIXME: Need to report the complete list of events. Limit reporting
         *        to the first event for now.
         */
        if (eventList->fullFormattedMessage != NULL) {
3078
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3079 3080
                      _("Could not migrate domain, validation reported a "
                        "problem: %s"), eventList->fullFormattedMessage);
3081
        } else {
3082 3083 3084
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                      _("Could not migrate domain, validation reported a "
                        "problem"));
3085 3086
        }

M
Matthias Bolte 已提交
3087
        goto cleanup;
3088 3089 3090
    }

    /* Perform the purposed migration */
3091
    if (esxVI_MigrateVM_Task(priv->vCenter, virtualMachine->obj, resourcePool,
3092 3093 3094 3095
                             hostSystem->obj,
                             esxVI_VirtualMachineMovePriority_DefaultPriority,
                             esxVI_VirtualMachinePowerState_Undefined,
                             &task) < 0 ||
3096 3097
        esxVI_WaitForTaskCompletion(priv->vCenter, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3098
        goto cleanup;
3099 3100 3101
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3102 3103 3104
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not migrate domain, migration task finished with "
                    "an error"));
M
Matthias Bolte 已提交
3105
        goto cleanup;
3106 3107
    }

M
Matthias Bolte 已提交
3108 3109
    result = 0;

3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135
  cleanup:
    xmlFreeURI(xmlUri);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_ManagedObjectReference_Free(&resourcePool);
    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 已提交
3136 3137 3138 3139
static unsigned long long
esxNodeGetFreeMemory(virConnectPtr conn)
{
    unsigned long long result = 0;
M
Matthias Bolte 已提交
3140
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
3141 3142 3143 3144 3145 3146 3147
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_ManagedObjectReference *managedObjectReference = NULL;
    esxVI_ObjectContent *resourcePool = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ResourcePoolResourceUsage *resourcePoolResourceUsage = NULL;

3148
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3149
        return 0;
M
Matthias Bolte 已提交
3150 3151 3152
    }

    /* Lookup host system with its resource pool */
3153 3154
    if (esxVI_String_AppendValueToList(&propertyNameList, "parent") < 0 ||
        esxVI_LookupHostSystemByIp(priv->host, priv->host->ipAddress,
M
Matthias Bolte 已提交
3155
                                   propertyNameList, &hostSystem) < 0) {
M
Matthias Bolte 已提交
3156
        goto cleanup;
M
Matthias Bolte 已提交
3157 3158
    }

3159
    if (esxVI_LookupResourcePoolByHostSystem(priv->host, hostSystem,
3160
                                             &managedObjectReference) < 0) {
M
Matthias Bolte 已提交
3161
        goto cleanup;
M
Matthias Bolte 已提交
3162 3163 3164 3165 3166
    }

    esxVI_String_Free(&propertyNameList);

    /* Get memory usage of resource pool */
3167
    if (esxVI_String_AppendValueToList(&propertyNameList,
M
Matthias Bolte 已提交
3168
                                       "runtime.memory") < 0 ||
3169
        esxVI_LookupObjectContentByType(priv->host, managedObjectReference,
3170 3171 3172
                                        "ResourcePool", propertyNameList,
                                        esxVI_Boolean_False,
                                        &resourcePool) < 0) {
M
Matthias Bolte 已提交
3173
        goto cleanup;
M
Matthias Bolte 已提交
3174 3175 3176 3177 3178 3179
    }

    for (dynamicProperty = resourcePool->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.memory")) {
            if (esxVI_ResourcePoolResourceUsage_CastFromAnyType
3180
                  (dynamicProperty->val, &resourcePoolResourceUsage) < 0) {
M
Matthias Bolte 已提交
3181
                goto cleanup;
M
Matthias Bolte 已提交
3182 3183 3184 3185 3186 3187 3188 3189 3190
            }

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

    if (resourcePoolResourceUsage == NULL) {
3191 3192
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve memory usage of resource pool"));
M
Matthias Bolte 已提交
3193
        goto cleanup;
M
Matthias Bolte 已提交
3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209
    }

    result = resourcePoolResourceUsage->unreservedForVm->value;

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

    return result;
}



3210 3211 3212
static int
esxIsEncrypted(virConnectPtr conn)
{
M
Matthias Bolte 已提交
3213
    esxPrivate *priv = conn->privateData;
3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226

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



static int
esxIsSecure(virConnectPtr conn)
{
M
Matthias Bolte 已提交
3227
    esxPrivate *priv = conn->privateData;
3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240

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



static int
esxDomainIsActive(virDomainPtr domain)
{
M
Matthias Bolte 已提交
3241
    int result = -1;
M
Matthias Bolte 已提交
3242
    esxPrivate *priv = domain->conn->privateData;
3243 3244 3245 3246
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

3247
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3248
        return -1;
3249 3250
    }

3251
    if (esxVI_String_AppendValueToList(&propertyNameList,
3252
                                       "runtime.powerState") < 0 ||
3253 3254
        esxVI_LookupVirtualMachineByUuid(priv->host, domain->uuid,
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3255
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3256
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
3257
        goto cleanup;
3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283
    }

    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;
}



3284 3285
static virDomainSnapshotPtr
esxDomainSnapshotCreateXML(virDomainPtr domain, const char *xmlDesc,
3286
                           unsigned int flags)
3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297
{
    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;

3298 3299
    virCheckFlags(0, NULL);

3300
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3301
        return NULL;
3302 3303 3304 3305 3306
    }

    def = virDomainSnapshotDefParseString(xmlDesc, 1);

    if (def == NULL) {
M
Matthias Bolte 已提交
3307
        return NULL;
3308 3309 3310 3311 3312 3313 3314 3315 3316 3317
    }

    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->host, domain->uuid, NULL, &virtualMachine,
           priv->autoAnswer) < 0 ||
        esxVI_LookupRootSnapshotTreeList(priv->host, domain->uuid,
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, def->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
3318
        goto cleanup;
3319 3320 3321 3322 3323
    }

    if (snapshotTree != NULL) {
        ESX_ERROR(VIR_ERR_OPERATION_INVALID,
                  _("Snapshot '%s' already exists"), def->name);
M
Matthias Bolte 已提交
3324
        goto cleanup;
3325 3326 3327 3328 3329 3330 3331 3332
    }

    if (esxVI_CreateSnapshot_Task(priv->host, virtualMachine->obj,
                                  def->name, def->description,
                                  esxVI_Boolean_True,
                                  esxVI_Boolean_False, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3333
        goto cleanup;
3334 3335 3336 3337
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not create snapshot"));
M
Matthias Bolte 已提交
3338
        goto cleanup;
3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355
    }

    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,
3356
                         unsigned int flags)
3357 3358 3359 3360 3361 3362 3363 3364 3365
{
    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;

3366 3367
    virCheckFlags(0, NULL);

M
Matthias Bolte 已提交
3368
    memset(&def, 0, sizeof (def));
3369 3370

    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3371
        return NULL;
3372 3373 3374 3375 3376 3377 3378
    }

    if (esxVI_LookupRootSnapshotTreeList(priv->host, snapshot->domain->uuid,
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3379
        goto cleanup;
3380 3381 3382 3383 3384 3385 3386 3387
    }

    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 已提交
3388
        goto cleanup;
3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406
    }

    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
3407
esxDomainSnapshotNum(virDomainPtr domain, unsigned int flags)
3408
{
M
Matthias Bolte 已提交
3409
    int count;
3410 3411 3412
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;

3413 3414
    virCheckFlags(0, -1);

3415
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3416
        return -1;
3417 3418 3419 3420
    }

    if (esxVI_LookupRootSnapshotTreeList(priv->host, domain->uuid,
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
3421
        return -1;
3422 3423
    }

M
Matthias Bolte 已提交
3424
    count = esxVI_GetNumberOfSnapshotTrees(rootSnapshotTreeList);
3425 3426 3427

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

M
Matthias Bolte 已提交
3428
    return count;
3429 3430 3431 3432 3433 3434
}



static int
esxDomainSnapshotListNames(virDomainPtr domain, char **names, int nameslen,
3435
                           unsigned int flags)
3436
{
M
Matthias Bolte 已提交
3437
    int result;
3438 3439 3440
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;

3441 3442
    virCheckFlags(0, -1);

3443 3444 3445 3446 3447 3448 3449 3450 3451 3452
    if (names == NULL || nameslen < 0) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
    }

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

    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3453
        return -1;
3454 3455 3456 3457
    }

    if (esxVI_LookupRootSnapshotTreeList(priv->host, domain->uuid,
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
3458
        return -1;
3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471
    }

    result = esxVI_GetSnapshotTreeNames(rootSnapshotTreeList, names, nameslen);

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



static virDomainSnapshotPtr
esxDomainSnapshotLookupByName(virDomainPtr domain, const char *name,
3472
                              unsigned int flags)
3473 3474 3475 3476 3477 3478 3479
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    virDomainSnapshotPtr snapshot = NULL;

3480 3481
    virCheckFlags(0, NULL);

3482
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3483
        return NULL;
3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509
    }

    if (esxVI_LookupRootSnapshotTreeList(priv->host, domain->uuid,
                                         &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;

3510
    virCheckFlags(0, -1);
3511 3512

    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3513
        return -1;
3514 3515 3516 3517 3518
    }

    if (esxVI_LookupCurrentSnapshotTree(priv->host, domain->uuid,
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
3519
        return -1;
3520 3521 3522
    }

    if (currentSnapshotTree != NULL) {
M
Matthias Bolte 已提交
3523 3524
        esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);
        return 1;
3525 3526
    }

M
Matthias Bolte 已提交
3527
    return 0;
3528 3529 3530 3531 3532 3533 3534 3535 3536
}



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

3539
    virCheckFlags(0, NULL);
3540 3541

    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3542
        return NULL;
3543 3544 3545 3546 3547
    }

    if (esxVI_LookupCurrentSnapshotTree(priv->host, domain->uuid,
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3548
        return NULL;
3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562
    }

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

    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return snapshot;
}



static int
esxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
3563
    int result = -1;
3564 3565 3566 3567 3568 3569 3570
    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;

3571
    virCheckFlags(0, -1);
3572 3573

    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3574
        return -1;
3575 3576 3577 3578 3579 3580 3581
    }

    if (esxVI_LookupRootSnapshotTreeList(priv->host, snapshot->domain->uuid,
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3582
        goto cleanup;
3583 3584 3585 3586 3587 3588
    }

    if (esxVI_RevertToSnapshot_Task(priv->host, snapshotTree->snapshot, NULL,
                                    &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, snapshot->domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3589
        goto cleanup;
3590 3591 3592 3593 3594
    }

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

M
Matthias Bolte 已提交
3598 3599
    result = 0;

3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainSnapshotDelete(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
3612
    int result = -1;
3613 3614 3615 3616 3617 3618 3619 3620
    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;

3621 3622
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN, -1);

3623
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3624
        return -1;
3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635
    }

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

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

    if (esxVI_RemoveSnapshot_Task(priv->host, snapshotTree->snapshot,
                                  removeChildren, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, snapshot->domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3643
        goto cleanup;
3644 3645 3646 3647 3648
    }

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

M
Matthias Bolte 已提交
3652 3653
    result = 0;

3654 3655 3656 3657 3658 3659 3660 3661 3662
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



3663 3664 3665 3666 3667 3668 3669 3670
static virDriver esxDriver = {
    VIR_DRV_ESX,
    "ESX",
    esxOpen,                         /* open */
    esxClose,                        /* close */
    esxSupportsFeature,              /* supports_feature */
    esxGetType,                      /* type */
    esxGetVersion,                   /* version */
3671
    NULL,                            /* libvirtVersion (impl. in libvirt.c) */
3672 3673 3674
    esxGetHostname,                  /* hostname */
    NULL,                            /* getMaxVcpus */
    esxNodeGetInfo,                  /* nodeGetInfo */
3675
    esxGetCapabilities,              /* getCapabilities */
3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701
    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 */
3702
    esxDomainXMLFromNative,          /* domainXMLFromNative */
M
Matthias Bolte 已提交
3703
    esxDomainXMLToNative,            /* domainXMLToNative */
3704 3705 3706
    esxListDefinedDomains,           /* listDefinedDomains */
    esxNumberOfDefinedDomains,       /* numOfDefinedDomains */
    esxDomainCreate,                 /* domainCreate */
3707
    esxDomainCreateWithFlags,        /* domainCreateWithFlags */
M
Matthias Bolte 已提交
3708
    esxDomainDefineXML,              /* domainDefineXML */
3709
    esxDomainUndefine,               /* domainUndefine */
3710
    NULL,                            /* domainAttachDevice */
3711
    NULL,                            /* domainAttachDeviceFlags */
3712
    NULL,                            /* domainDetachDevice */
3713
    NULL,                            /* domainDetachDeviceFlags */
3714
    NULL,                            /* domainUpdateDeviceFlags */
3715 3716 3717 3718 3719 3720 3721 3722 3723 3724
    NULL,                            /* domainGetAutostart */
    NULL,                            /* domainSetAutostart */
    esxDomainGetSchedulerType,       /* domainGetSchedulerType */
    esxDomainGetSchedulerParameters, /* domainGetSchedulerParameters */
    esxDomainSetSchedulerParameters, /* domainSetSchedulerParameters */
    esxDomainMigratePrepare,         /* domainMigratePrepare */
    esxDomainMigratePerform,         /* domainMigratePerform */
    esxDomainMigrateFinish,          /* domainMigrateFinish */
    NULL,                            /* domainBlockStats */
    NULL,                            /* domainInterfaceStats */
3725
    NULL,                            /* domainMemoryStats */
3726 3727
    NULL,                            /* domainBlockPeek */
    NULL,                            /* domainMemoryPeek */
3728
    NULL,                            /* domainGetBlockInfo */
3729
    NULL,                            /* nodeGetCellsFreeMemory */
M
Matthias Bolte 已提交
3730
    esxNodeGetFreeMemory,            /* nodeGetFreeMemory */
3731 3732 3733 3734 3735 3736 3737
    NULL,                            /* domainEventRegister */
    NULL,                            /* domainEventDeregister */
    NULL,                            /* domainMigratePrepare2 */
    NULL,                            /* domainMigrateFinish2 */
    NULL,                            /* nodeDeviceDettach */
    NULL,                            /* nodeDeviceReAttach */
    NULL,                            /* nodeDeviceReset */
C
Chris Lalancette 已提交
3738
    NULL,                            /* domainMigratePrepareTunnel */
3739 3740 3741 3742
    esxIsEncrypted,                  /* isEncrypted */
    esxIsSecure,                     /* isSecure */
    esxDomainIsActive,               /* domainIsActive */
    esxDomainIsPersistent,           /* domainIsPersistent */
J
Jiri Denemark 已提交
3743
    NULL,                            /* cpuCompare */
3744
    NULL,                            /* cpuBaseline */
3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761
    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 */
3762 3763 3764 3765 3766 3767 3768
};



int
esxRegister(void)
{
3769 3770 3771 3772 3773
    if (virRegisterDriver(&esxDriver) < 0 ||
        esxInterfaceRegister() < 0 ||
        esxNetworkRegister() < 0 ||
        esxStorageRegister() < 0 ||
        esxDeviceRegister() < 0 ||
M
Matthias Bolte 已提交
3774 3775
        esxSecretRegister() < 0 ||
        esxNWFilterRegister() < 0) {
3776 3777
        return -1;
    }
3778 3779 3780

    return 0;
}