esx_driver.c 117.6 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 63 64 65 66 67 68 69
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_HostCpuIdInfo *hostCpuIdInfoList = NULL;
    esxVI_HostCpuIdInfo *hostCpuIdInfo = NULL;
    char edxLongModeBit = '?';
    char edxFirstBit = '?';

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

70
    if (esxVI_EnsureSession(priv->host) < 0) {
71 72 73
        goto failure;
    }

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) {
79 80 81 82
        goto failure;
    }

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

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

            for (hostCpuIdInfo = hostCpuIdInfoList; hostCpuIdInfo != NULL;
                 hostCpuIdInfo = hostCpuIdInfo->_next) {
                if (hostCpuIdInfo->level->value == -2147483647) { /* 0x80000001 */
99 100
#define _SKIP4 "%*c%*c%*c%*c"
#define _SKIP12 _SKIP4":"_SKIP4":"_SKIP4
101 102 103 104 105

                    /* Expected format: "--X-:----:----:----:----:----:----:----" */
                    if (sscanf(hostCpuIdInfo->edx,
                               "%*c%*c%c%*c:"_SKIP12":"_SKIP12":%*c%*c%*c%c",
                               &edxLongModeBit, &edxFirstBit) != 2) {
106
                        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
107 108 109
                                  _("HostSystem property 'hardware.cpuFeature[].edx' "
                                    "with value '%s' doesn't have expected format "
                                    "'----:----:----:----:----:----:----:----'"),
110 111 112 113
                                  hostCpuIdInfo->edx);
                        goto failure;
                    }

114 115
#undef _SKIP4
#undef _SKIP12
116 117 118 119 120 121

                    if (edxLongModeBit == '1') {
                        priv->supportsLongMode = esxVI_Boolean_True;
                    } else if (edxLongModeBit == '0') {
                        priv->supportsLongMode = esxVI_Boolean_False;
                    } else {
122
                        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
123 124 125 126
                                  _("Bit 29 (Long Mode) of HostSystem property "
                                    "'hardware.cpuFeature[].edx' with value '%s' "
                                    "has unexpected value '%c', expecting '0' "
                                    "or '1'"), hostCpuIdInfo->edx, edxLongModeBit);
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
                        goto failure;
                    }

                    break;
                }
            }

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

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

    return priv->supportsLongMode;

  failure:
    priv->supportsLongMode = esxVI_Boolean_Undefined;

    goto cleanup;
}



155
static virCapsPtr
156
esxCapsInit(esxPrivate *priv)
157
{
158
    esxVI_Boolean supportsLongMode = esxSupportsLongMode(priv);
159 160 161
    virCapsPtr caps = NULL;
    virCapsGuestPtr guest = NULL;

162 163 164 165 166 167 168 169 170
    if (supportsLongMode == esxVI_Boolean_Undefined) {
        return NULL;
    }

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

    if (caps == NULL) {
173
        virReportOOMError();
174 175 176
        return NULL;
    }

177
    virCapabilitiesSetMacPrefix(caps, (unsigned char[]){ 0x00, 0x0c, 0x29 });
178 179
    virCapabilitiesAddHostMigrateTransport(caps, "esx");

180 181 182
    /* i686 */
    guest = virCapabilitiesAddGuest(caps, "hvm", "i686", 32, NULL, NULL, 0,
                                    NULL);
183 184 185 186 187 188 189 190 191 192 193 194 195 196

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

197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
    /* 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;
        }
    }

216 217 218 219 220 221 222 223 224 225
    return caps;

  failure:
    virCapabilitiesFree(caps);

    return NULL;
}



226
/*
227
 * URI format: {esx|gsx}://[<user>@]<server>[:<port>]/[<query parameter> ...]
228
 *
229 230 231
 * If no port is specified the default port is set dependent on the scheme and
 * transport parameter:
 * - esx+http  80
232
 * - esx+https 443
233 234 235
 * - gsx+http  8222
 * - gsx+https 8333
 *
236 237 238 239 240 241
 * Optional query parameters:
 * - transport={http|https}
 * - vcenter={<vcenter>|*}
 * - no_verify={0|1}
 * - auto_answer={0|1}
 *
242 243 244
 * If no transport parameter is specified https is used.
 *
 * The vcenter parameter is only necessary for migration, because the vCenter
245 246 247 248
 * 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.
249 250
 *
 * If the no_verify parameter is set to 1, this disables libcurl client checks
251
 * of the server's certificate. The default value it 0.
252 253 254 255
 *
 * 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.
256 257 258 259
 */
static virDrvOpenStatus
esxOpen(virConnectPtr conn, virConnectAuthPtr auth, int flags ATTRIBUTE_UNUSED)
{
260
    virDrvOpenStatus result = VIR_DRV_OPEN_SUCCESS;
261
    esxPrivate *priv = NULL;
M
Matthias Bolte 已提交
262 263
    char hostIpAddress[NI_MAXHOST] = "";
    char vCenterIpAddress[NI_MAXHOST] = "";
264
    char *url = NULL;
M
Matthias Bolte 已提交
265
    char *vCenter = NULL;
266
    int noVerify = 0; // boolean
267
    int autoAnswer = 0; // boolean
268 269
    char *username = NULL;
    char *password = NULL;
270 271 272
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
273

274
    /* Decline if the URI is NULL or the scheme is neither 'esx' nor 'gsx' */
275
    if (conn->uri == NULL || conn->uri->scheme == NULL ||
276 277
        (STRCASENEQ(conn->uri->scheme, "esx") &&
         STRCASENEQ(conn->uri->scheme, "gsx"))) {
278 279 280
        return VIR_DRV_OPEN_DECLINED;
    }

M
Matthias Bolte 已提交
281 282 283
    /* Decline URIs without server part, or missing auth */
    if (conn->uri->server == NULL || auth == NULL || auth->cb == NULL) {
        return VIR_DRV_OPEN_DECLINED;
284 285
    }

286 287
    if (conn->uri->path != NULL && STRNEQ(conn->uri->path, "") &&
        STRNEQ(conn->uri->path, "/")) {
M
Matthias Bolte 已提交
288
        VIR_WARN("Ignoring unexpected path '%s' in URI", conn->uri->path);
289 290 291 292
    }

    /* Allocate per-connection private data */
    if (VIR_ALLOC(priv) < 0) {
293
        virReportOOMError();
294 295 296
        goto failure;
    }

M
Matthias Bolte 已提交
297 298
    priv->maxVcpus = -1;
    priv->supportsVMotion = esxVI_Boolean_Undefined;
299
    priv->supportsLongMode = esxVI_Boolean_Undefined;
300
    priv->autoAnswer = esxVI_Boolean_False;
301 302
    priv->usedCpuTimeCounterId = -1;

303
    if (esxUtil_ParseQuery(conn->uri, &priv->transport, &vCenter, &noVerify,
304
                           &autoAnswer) < 0) {
M
Matthias Bolte 已提交
305 306 307
        goto failure;
    }

308 309 310 311
    if (autoAnswer) {
        priv->autoAnswer = esxVI_Boolean_True;
    }

M
Matthias Bolte 已提交
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
    /*
     * 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;
            }
331
        }
M
Matthias Bolte 已提交
332
    }
333

M
Matthias Bolte 已提交
334
    /* Login to host */
335
    if (esxUtil_ResolveHostname(conn->uri->server, hostIpAddress,
336 337 338 339
                                NI_MAXHOST) < 0) {
        goto failure;
    }

M
Matthias Bolte 已提交
340 341
    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->transport,
                    conn->uri->server, conn->uri->port) < 0) {
342
        virReportOOMError();
M
Matthias Bolte 已提交
343 344 345 346 347 348 349
        goto failure;
    }

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

        if (username == NULL) {
350
            virReportOOMError();
351 352
            goto failure;
        }
M
Matthias Bolte 已提交
353
    } else {
354
        username = virRequestUsername(auth, "root", conn->uri->server);
355

M
Matthias Bolte 已提交
356
        if (username == NULL) {
357
            ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Username request failed"));
358 359
            goto failure;
        }
M
Matthias Bolte 已提交
360
    }
361

362
    if (esxVI_Context_Alloc(&priv->host) < 0) {
M
Matthias Bolte 已提交
363 364
        goto failure;
    }
365

366
    password = virRequestPassword(auth, username, conn->uri->server);
M
Matthias Bolte 已提交
367 368

    if (password == NULL) {
369
        ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
M
Matthias Bolte 已提交
370 371 372
        goto failure;
    }

373 374
    if (esxVI_Context_Connect(priv->host, url, hostIpAddress, username,
                              password, noVerify) < 0) {
M
Matthias Bolte 已提交
375 376 377 378 379 380
        goto failure;
    }

    if (STRCASEEQ(conn->uri->scheme, "esx")) {
        if (priv->host->productVersion != esxVI_ProductVersion_ESX35 &&
            priv->host->productVersion != esxVI_ProductVersion_ESX40) {
381
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
382
                      _("%s is neither an ESX 3.5 host nor an ESX 4.0 host"),
M
Matthias Bolte 已提交
383
                      conn->uri->server);
384 385
            goto failure;
        }
M
Matthias Bolte 已提交
386 387
    } else { /* GSX */
        if (priv->host->productVersion != esxVI_ProductVersion_GSX20) {
388
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
389
                      _("%s isn't a GSX 2.0 host"), conn->uri->server);
M
Matthias Bolte 已提交
390 391 392
            goto failure;
        }
    }
393

394
    /* Query the host for maintenance mode and vCenter IP address */
395
    if (esxVI_String_AppendValueListToList(&propertyNameList,
396 397
                                           "runtime.inMaintenanceMode\0"
                                           "summary.managementServerIp\0") < 0 ||
398 399
        esxVI_LookupHostSystemByIp(priv->host, hostIpAddress, propertyNameList,
                                   &hostSystem) < 0) {
400 401 402 403 404 405 406
        goto failure;
    }

    /* Warn if host is in maintenance mode */
    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.inMaintenanceMode")) {
407
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
408 409 410 411 412 413 414 415 416 417 418 419
                                         esxVI_Type_Boolean) < 0) {
                goto failure;
            }

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

            break;
        }
    }

M
Matthias Bolte 已提交
420 421
    /* Login to vCenter */
    if (vCenter != NULL) {
422 423 424 425 426 427
        VIR_FREE(url);
        VIR_FREE(password);
        VIR_FREE(username);

        /* If a vCenter is specified resolve the hostname */
        if (STRNEQ(vCenter, "*") &&
428
            esxUtil_ResolveHostname(vCenter, vCenterIpAddress,
429 430 431 432 433 434 435
                                    NI_MAXHOST) < 0) {
            goto failure;
        }

        /* Lookup the vCenter from the ESX host */
        for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
436
            if (STREQ(dynamicProperty->name, "summary.managementServerIp")) {
437
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
438 439 440 441 442 443 444 445 446 447 448
                                             esxVI_Type_String) < 0) {
                    goto failure;
                }

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

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

                    if (vCenter == NULL) {
449
                        virReportOOMError();
450 451 452 453 454
                        goto failure;
                    }

                    if (virStrcpyStatic(vCenterIpAddress,
                                        dynamicProperty->val->string) == NULL) {
455
                        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
456 457 458
                                  _("vCenter IP address %s too big for "
                                    "destination"),
                                  dynamicProperty->val->string);
459 460 461 462
                        goto failure;
                    }
                } else if (STRNEQ(vCenterIpAddress,
                           dynamicProperty->val->string)) {
463
                    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
464 465 466
                              _("This host is managed by a vCenter with IP "
                                "address %s, but a mismachting vCenter '%s' "
                                "(%s) has been specified"),
467 468 469 470 471 472 473 474 475 476
                              dynamicProperty->val->string, vCenter,
                              vCenterIpAddress);
                    goto failure;
                }

                break;
            }
        }

        if (STREQ(vCenter, "*")) {
477 478
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                      _("This host is not managed by a vCenter"));
479 480 481
            goto failure;
        }

M
Matthias Bolte 已提交
482 483
        if (virAsprintf(&url, "%s://%s/sdk", priv->transport,
                        vCenter) < 0) {
484
            virReportOOMError();
M
Matthias Bolte 已提交
485 486
            goto failure;
        }
487

488
        if (esxVI_Context_Alloc(&priv->vCenter) < 0) {
M
Matthias Bolte 已提交
489
            goto failure;
490 491
        }

492
        username = virRequestUsername(auth, "administrator", vCenter);
M
Matthias Bolte 已提交
493 494

        if (username == NULL) {
495
            ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Username request failed"));
496 497 498
            goto failure;
        }

499
        password = virRequestPassword(auth, username, vCenter);
500 501

        if (password == NULL) {
502
            ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
503 504 505
            goto failure;
        }

506 507
        if (esxVI_Context_Connect(priv->vCenter, url, vCenterIpAddress,
                                  username, password, noVerify) < 0) {
508 509 510
            goto failure;
        }

M
Matthias Bolte 已提交
511 512
        if (priv->vCenter->productVersion != esxVI_ProductVersion_VPX25 &&
            priv->vCenter->productVersion != esxVI_ProductVersion_VPX40) {
513
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
514 515
                      _("%s is neither a vCenter 2.5 server nor a vCenter "
                        "4.0 server"), conn->uri->server);
M
Matthias Bolte 已提交
516
            goto failure;
517
        }
518 519 520
    }

    conn->privateData = priv;
521

M
Matthias Bolte 已提交
522
    /* Setup capabilities */
523
    priv->caps = esxCapsInit(priv);
524

M
Matthias Bolte 已提交
525 526
    if (priv->caps == NULL) {
        goto failure;
527 528
    }

529
  cleanup:
530
    VIR_FREE(url);
M
Matthias Bolte 已提交
531
    VIR_FREE(vCenter);
532 533
    VIR_FREE(password);
    VIR_FREE(username);
534 535
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);
536

537 538 539
    return result;

  failure:
540 541
    if (priv != NULL) {
        esxVI_Context_Free(&priv->host);
M
Matthias Bolte 已提交
542
        esxVI_Context_Free(&priv->vCenter);
543

544 545
        virCapabilitiesFree(priv->caps);

M
Matthias Bolte 已提交
546
        VIR_FREE(priv->transport);
547 548 549
        VIR_FREE(priv);
    }

550 551 552
    result = VIR_DRV_OPEN_ERROR;

    goto cleanup;
553 554 555 556 557 558 559
}



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

E
Eric Blake 已提交
563 564 565 566
    if (esxVI_EnsureSession(priv->host) < 0 ||
        esxVI_Logout(priv->host) < 0) {
        result = -1;
    }
567

M
Matthias Bolte 已提交
568
    esxVI_Context_Free(&priv->host);
569

M
Matthias Bolte 已提交
570
    if (priv->vCenter != NULL) {
E
Eric Blake 已提交
571 572 573 574
        if (esxVI_EnsureSession(priv->vCenter) < 0 ||
            esxVI_Logout(priv->vCenter) < 0) {
            result = -1;
        }
575

M
Matthias Bolte 已提交
576
        esxVI_Context_Free(&priv->vCenter);
577 578
    }

579 580
    virCapabilitiesFree(priv->caps);

581 582 583 584 585
    VIR_FREE(priv->transport);
    VIR_FREE(priv);

    conn->privateData = NULL;

E
Eric Blake 已提交
586
    return result;
587 588 589 590 591
}



static esxVI_Boolean
592
esxSupportsVMotion(esxPrivate *priv)
593 594 595 596 597
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

M
Matthias Bolte 已提交
598 599
    if (priv->supportsVMotion != esxVI_Boolean_Undefined) {
        return priv->supportsVMotion;
600 601
    }

602
    if (esxVI_EnsureSession(priv->host) < 0) {
603 604 605
        goto failure;
    }

606
    if (esxVI_String_AppendValueToList(&propertyNameList,
607
                                       "capability.vmotionSupported") < 0 ||
608
        esxVI_LookupObjectContentByType(priv->host, priv->host->hostFolder,
609 610
                                        "HostSystem", propertyNameList,
                                        esxVI_Boolean_True, &hostSystem) < 0) {
611 612 613 614
        goto failure;
    }

    if (hostSystem == NULL) {
615 616
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
617 618 619 620 621 622
        goto failure;
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "capability.vmotionSupported")) {
623
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
624 625 626 627
                                         esxVI_Type_Boolean) < 0) {
                goto failure;
            }

M
Matthias Bolte 已提交
628
            priv->supportsVMotion = dynamicProperty->val->boolean;
629 630 631 632 633 634 635 636 637 638
            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

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

M
Matthias Bolte 已提交
639
    return priv->supportsVMotion;
640 641

  failure:
M
Matthias Bolte 已提交
642
    priv->supportsVMotion = esxVI_Boolean_Undefined;
643 644 645 646 647 648 649 650 651

    goto cleanup;
}



static int
esxSupportsFeature(virConnectPtr conn, int feature)
{
M
Matthias Bolte 已提交
652
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
653
    esxVI_Boolean supportsVMotion = esxVI_Boolean_Undefined;
654 655 656

    switch (feature) {
      case VIR_DRV_FEATURE_MIGRATION_V1:
657
        supportsVMotion = esxSupportsVMotion(priv);
658

M
Matthias Bolte 已提交
659
        if (supportsVMotion == esxVI_Boolean_Undefined) {
660 661 662
            return -1;
        }

M
Matthias Bolte 已提交
663 664 665
        /* Migration is only possible via a vCenter and if VMotion is enabled */
        return priv->vCenter != NULL &&
               supportsVMotion == esxVI_Boolean_True ? 1 : 0;
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684

      default:
        return 0;
    }
}



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



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

687 688 689
    if (virParseVersionString(priv->host->service->about->version,
                              version) < 0) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
690
                  _("Could not parse version number from '%s'"),
691
                  priv->host->service->about->version);
692

693
        return -1;
694 695 696 697 698 699 700 701 702 703
    }

    return 0;
}



static char *
esxGetHostname(virConnectPtr conn)
{
M
Matthias Bolte 已提交
704
    esxPrivate *priv = conn->privateData;
705 706 707 708 709 710 711
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    const char *hostName = NULL;
    const char *domainName = NULL;
    char *complete = NULL;

712
    if (esxVI_EnsureSession(priv->host) < 0) {
713 714 715 716
        goto failure;
    }

    if (esxVI_String_AppendValueListToList
717
          (&propertyNameList,
718 719
           "config.network.dnsConfig.hostName\0"
           "config.network.dnsConfig.domainName\0") < 0 ||
720
        esxVI_LookupObjectContentByType(priv->host, priv->host->hostFolder,
721 722
                                        "HostSystem", propertyNameList,
                                        esxVI_Boolean_True, &hostSystem) < 0) {
723 724 725 726
        goto failure;
    }

    if (hostSystem == NULL) {
727 728
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
729 730 731 732 733 734 735
        goto failure;
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name,
                  "config.network.dnsConfig.hostName")) {
736
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
737 738 739 740 741 742 743
                                         esxVI_Type_String) < 0) {
                goto failure;
            }

            hostName = dynamicProperty->val->string;
        } else if (STREQ(dynamicProperty->name,
                         "config.network.dnsConfig.domainName")) {
744
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
745 746 747 748 749 750 751 752 753 754
                                         esxVI_Type_String) < 0) {
                goto failure;
            }

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

M
Matthias Bolte 已提交
755
    if (hostName == NULL || strlen(hostName) < 1) {
756 757
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Missing or empty 'hostName' property"));
758 759 760
        goto failure;
    }

M
Matthias Bolte 已提交
761
    if (domainName == NULL || strlen(domainName) < 1) {
762
        complete = strdup(hostName);
763

764
        if (complete == NULL) {
765
            virReportOOMError();
766 767 768 769
            goto failure;
        }
    } else {
        if (virAsprintf(&complete, "%s.%s", hostName, domainName) < 0) {
770
            virReportOOMError();
771 772
            goto failure;
        }
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
    }

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

    return complete;

  failure:
    VIR_FREE(complete);

    goto cleanup;
}



static int
esxNodeGetInfo(virConnectPtr conn, virNodeInfoPtr nodeinfo)
{
    int result = 0;
M
Matthias Bolte 已提交
793
    esxPrivate *priv = conn->privateData;
794 795 796 797 798 799 800 801 802 803 804
    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 已提交
805
    memset(nodeinfo, 0, sizeof(virNodeInfo));
806

807
    if (esxVI_EnsureSession(priv->host) < 0) {
808 809 810
        goto failure;
    }

811
    if (esxVI_String_AppendValueListToList(&propertyNameList,
812 813 814 815 816 817 818
                                           "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 ||
819
        esxVI_LookupObjectContentByType(priv->host, priv->host->hostFolder,
820 821
                                        "HostSystem", propertyNameList,
                                        esxVI_Boolean_True, &hostSystem) < 0) {
822 823 824 825
        goto failure;
    }

    if (hostSystem == NULL) {
826 827
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
828 829 830 831 832 833
        goto failure;
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuInfo.hz")) {
834
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
835 836 837 838 839 840 841
                                         esxVI_Type_Long) < 0) {
                goto failure;
            }

            cpuInfo_hz = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuCores")) {
842
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
843 844 845 846 847 848 849
                                         esxVI_Type_Short) < 0) {
                goto failure;
            }

            cpuInfo_numCpuCores = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuPackages")) {
850
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
851 852 853 854 855 856 857
                                         esxVI_Type_Short) < 0) {
                goto failure;
            }

            cpuInfo_numCpuPackages = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuThreads")) {
858
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
859 860 861 862 863 864
                                         esxVI_Type_Short) < 0) {
                goto failure;
            }

            cpuInfo_numCpuThreads = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name, "hardware.memorySize")) {
865
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
866 867 868 869 870 871 872
                                         esxVI_Type_Long) < 0) {
                goto failure;
            }

            memorySize = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.numaInfo.numNodes")) {
873
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
874 875 876 877 878 879 880
                                         esxVI_Type_Int) < 0) {
                goto failure;
            }

            numaInfo_numNodes = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "summary.hardware.cpuModel")) {
881
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
882 883 884 885 886 887 888 889
                                         esxVI_Type_String) < 0) {
                goto failure;
            }

            ptr = dynamicProperty->val->string;

            /* Strip the string to fit more relevant information in 32 chars */
            while (*ptr != '\0') {
M
Matthias Bolte 已提交
890 891
                if (STRPREFIX(ptr, "  ")) {
                    memmove(ptr, ptr + 1, strlen(ptr + 1) + 1);
892
                    continue;
893
                } else if (STRPREFIX(ptr, "(R)") || STRPREFIX(ptr, "(C)")) {
M
Matthias Bolte 已提交
894
                    memmove(ptr, ptr + 3, strlen(ptr + 3) + 1);
895
                    continue;
896 897 898
                } else if (STRPREFIX(ptr, "(TM)")) {
                    memmove(ptr, ptr + 4, strlen(ptr + 4) + 1);
                    continue;
899 900 901 902 903
                }

                ++ptr;
            }

C
Chris Lalancette 已提交
904 905 906
            if (virStrncpy(nodeinfo->model, dynamicProperty->val->string,
                           sizeof(nodeinfo->model) - 1,
                           sizeof(nodeinfo->model)) == NULL) {
907
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
908
                          _("CPU Model %s too long for destination"),
C
Chris Lalancette 已提交
909 910 911
                          dynamicProperty->val->string);
                goto failure;
            }
912 913 914 915 916 917 918
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    nodeinfo->memory = memorySize / 1024; /* Scale from bytes to kilobytes */
    nodeinfo->cpus = cpuInfo_numCpuCores;
919
    nodeinfo->mhz = cpuInfo_hz / (1000 * 1000); /* Scale from hz to mhz */
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
    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;

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

    return result;

  failure:
    result = -1;

    goto cleanup;
}



943 944 945
static char *
esxGetCapabilities(virConnectPtr conn)
{
M
Matthias Bolte 已提交
946
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
947
    char *xml = virCapabilitiesFormatXML(priv->caps);
948 949

    if (xml == NULL) {
950
        virReportOOMError();
951 952 953 954 955 956 957 958
        return NULL;
    }

    return xml;
}



959 960 961
static int
esxListDomains(virConnectPtr conn, int *ids, int maxids)
{
M
Matthias Bolte 已提交
962
    esxPrivate *priv = conn->privateData;
963 964 965 966 967 968 969
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;

    if (ids == NULL || maxids < 0) {
970 971
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
972 973 974 975 976 977
    }

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

978
    if (esxVI_EnsureSession(priv->host) < 0) {
979 980 981
        goto failure;
    }

982
    if (esxVI_String_AppendValueToList(&propertyNameList,
983
                                       "runtime.powerState") < 0 ||
984
        esxVI_LookupObjectContentByType(priv->host, priv->host->vmFolder,
985 986 987
                                        "VirtualMachine", propertyNameList,
                                        esxVI_Boolean_True,
                                        &virtualMachineList) < 0) {
988 989 990 991 992
        goto failure;
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
993
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
994 995 996 997 998 999 1000 1001 1002 1003 1004
                                              &powerState) < 0) {
            goto failure;
        }

        if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

        if (esxUtil_ParseVirtualMachineIDString(virtualMachine->obj->value,
                                                &ids[count]) < 0 ||
            ids[count] <= 0) {
1005
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1006
                      _("Failed to parse positive integer from '%s'"),
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
                      virtualMachine->obj->value);
            goto failure;
        }

        count++;

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

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

    return count;

  failure:
    count = -1;

    goto cleanup;
}



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

1037
    if (esxVI_EnsureSession(priv->host) < 0) {
1038 1039 1040
        return -1;
    }

1041
    return esxVI_LookupNumberOfDomainsByPowerState
1042
             (priv->host, esxVI_VirtualMachinePowerState_PoweredOn,
1043 1044 1045 1046 1047 1048 1049 1050
              esxVI_Boolean_False);
}



static virDomainPtr
esxDomainLookupByID(virConnectPtr conn, int id)
{
M
Matthias Bolte 已提交
1051
    esxPrivate *priv = conn->privateData;
1052 1053 1054 1055
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
M
Matthias Bolte 已提交
1056 1057 1058
    int id_candidate = -1;
    char *name_candidate = NULL;
    unsigned char uuid_candidate[VIR_UUID_BUFLEN];
1059 1060
    virDomainPtr domain = NULL;

1061
    if (esxVI_EnsureSession(priv->host) < 0) {
1062 1063 1064
        goto failure;
    }

1065
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1066
                                           "configStatus\0"
1067 1068
                                           "name\0"
                                           "runtime.powerState\0"
1069
                                           "config.uuid\0") < 0 ||
1070
        esxVI_LookupObjectContentByType(priv->host, priv->host->vmFolder,
1071 1072 1073
                                        "VirtualMachine", propertyNameList,
                                        esxVI_Boolean_True,
                                        &virtualMachineList) < 0) {
1074 1075 1076 1077 1078
        goto failure;
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
1079
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1080 1081 1082 1083 1084 1085 1086 1087 1088
                                              &powerState) < 0) {
            goto failure;
        }

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

M
Matthias Bolte 已提交
1089
        VIR_FREE(name_candidate);
1090

1091
        if (esxVI_GetVirtualMachineIdentity(virtualMachine,
M
Matthias Bolte 已提交
1092 1093
                                            &id_candidate, &name_candidate,
                                            uuid_candidate) < 0) {
1094 1095 1096
            goto failure;
        }

M
Matthias Bolte 已提交
1097
        if (id != id_candidate) {
1098 1099 1100
            continue;
        }

M
Matthias Bolte 已提交
1101
        domain = virGetDomain(conn, name_candidate, uuid_candidate);
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112

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

        domain->id = id;

        break;
    }

    if (domain == NULL) {
1113
        ESX_ERROR(VIR_ERR_NO_DOMAIN, _("No domain with ID %d"), id);
1114 1115 1116 1117 1118
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
M
Matthias Bolte 已提交
1119
    VIR_FREE(name_candidate);
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133

    return domain;

  failure:
    domain = NULL;

    goto cleanup;
}



static virDomainPtr
esxDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
M
Matthias Bolte 已提交
1134
    esxPrivate *priv = conn->privateData;
1135 1136 1137
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1138 1139
    int id = -1;
    char *name = NULL;
1140 1141
    virDomainPtr domain = NULL;

1142
    if (esxVI_EnsureSession(priv->host) < 0) {
1143 1144 1145
        goto failure;
    }

1146
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1147
                                           "name\0"
1148
                                           "runtime.powerState\0") < 0 ||
1149 1150
        esxVI_LookupVirtualMachineByUuid(priv->host, uuid, propertyNameList,
                                         &virtualMachine,
M
Matthias Bolte 已提交
1151
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1152 1153
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, &name, NULL) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
1154 1155 1156
        goto failure;
    }

1157
    domain = virGetDomain(conn, name, uuid);
1158 1159

    if (domain == NULL) {
1160 1161
        goto failure;
    }
1162

1163 1164 1165 1166 1167
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1168 1169 1170 1171
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1172 1173
    esxVI_ObjectContent_Free(&virtualMachine);
    VIR_FREE(name);
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187

    return domain;

  failure:
    domain = NULL;

    goto cleanup;
}



static virDomainPtr
esxDomainLookupByName(virConnectPtr conn, const char *name)
{
M
Matthias Bolte 已提交
1188
    esxPrivate *priv = conn->privateData;
1189 1190 1191
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1192 1193
    int id = -1;
    unsigned char uuid[VIR_UUID_BUFLEN];
1194 1195
    virDomainPtr domain = NULL;

1196
    if (esxVI_EnsureSession(priv->host) < 0) {
1197 1198 1199
        goto failure;
    }

1200
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1201
                                           "configStatus\0"
1202
                                           "runtime.powerState\0"
1203
                                           "config.uuid\0") < 0 ||
1204 1205 1206
        esxVI_LookupVirtualMachineByName(priv->host, name, propertyNameList,
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
1207 1208 1209
        goto failure;
    }

1210
    if (virtualMachine == NULL) {
1211
        ESX_ERROR(VIR_ERR_NO_DOMAIN, _("No domain with name '%s'"), name);
1212 1213
        goto failure;
    }
1214 1215


1216 1217 1218
    if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, uuid) < 0) {
        goto failure;
    }
M
Matthias Bolte 已提交
1219

1220 1221 1222 1223
    if (esxVI_GetVirtualMachinePowerState(virtualMachine,
                                          &powerState) < 0) {
        goto failure;
    }
1224

1225
    domain = virGetDomain(conn, name, uuid);
1226

1227 1228
    if (domain == NULL) {
        goto failure;
1229 1230
    }

1231 1232 1233 1234 1235
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1236 1237 1238 1239
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1240
    esxVI_ObjectContent_Free(&virtualMachine);
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255

    return domain;

  failure:
    domain = NULL;

    goto cleanup;
}



static int
esxDomainSuspend(virDomainPtr domain)
{
    int result = 0;
M
Matthias Bolte 已提交
1256
    esxPrivate *priv = domain->conn->privateData;
1257 1258 1259 1260 1261 1262
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1263
    if (esxVI_EnsureSession(priv->host) < 0) {
1264 1265 1266
        goto failure;
    }

1267
    if (esxVI_String_AppendValueToList(&propertyNameList,
1268
                                       "runtime.powerState") < 0 ||
1269
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1270 1271 1272
          (priv->host, domain->uuid, propertyNameList, &virtualMachine,
           priv->autoAnswer) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
1273 1274 1275 1276
        goto failure;
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1277 1278
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
1279 1280 1281
        goto failure;
    }

1282 1283 1284
    if (esxVI_SuspendVM_Task(priv->host, virtualMachine->obj, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
1285 1286 1287 1288
        goto failure;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1289
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not suspend domain"));
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
        goto failure;
    }

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

    return result;

  failure:
    result = -1;

    goto cleanup;
}



static int
esxDomainResume(virDomainPtr domain)
{
    int result = 0;
M
Matthias Bolte 已提交
1312
    esxPrivate *priv = domain->conn->privateData;
1313 1314 1315 1316 1317 1318
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1319
    if (esxVI_EnsureSession(priv->host) < 0) {
1320 1321 1322
        goto failure;
    }

1323
    if (esxVI_String_AppendValueToList(&propertyNameList,
1324
                                       "runtime.powerState") < 0 ||
1325
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1326 1327 1328
          (priv->host, domain->uuid, propertyNameList, &virtualMachine,
           priv->autoAnswer) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
1329 1330 1331 1332
        goto failure;
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended) {
1333
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not suspended"));
1334 1335 1336
        goto failure;
    }

1337 1338
    if (esxVI_PowerOnVM_Task(priv->host, virtualMachine->obj, NULL,
                             &task) < 0 ||
1339 1340
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
1341 1342 1343 1344
        goto failure;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1345
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not resume domain"));
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
        goto failure;
    }

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

    return result;

  failure:
    result = -1;

    goto cleanup;
}



static int
esxDomainShutdown(virDomainPtr domain)
{
    int result = 0;
M
Matthias Bolte 已提交
1368
    esxPrivate *priv = domain->conn->privateData;
1369 1370 1371 1372
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1373
    if (esxVI_EnsureSession(priv->host) < 0) {
1374 1375 1376
        goto failure;
    }

1377
    if (esxVI_String_AppendValueToList(&propertyNameList,
1378
                                       "runtime.powerState") < 0 ||
1379 1380
        esxVI_LookupVirtualMachineByUuid(priv->host, domain->uuid,
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1381
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1382
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
1383 1384 1385 1386
        goto failure;
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1387 1388
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
1389 1390 1391
        goto failure;
    }

1392
    if (esxVI_ShutdownGuest(priv->host, virtualMachine->obj) < 0) {
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
        goto failure;
    }

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

    return result;

  failure:
    result = -1;

    goto cleanup;
}



static int
esxDomainReboot(virDomainPtr domain, unsigned int flags ATTRIBUTE_UNUSED)
{
    int result = 0;
M
Matthias Bolte 已提交
1414
    esxPrivate *priv = domain->conn->privateData;
1415 1416 1417 1418
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1419
    if (esxVI_EnsureSession(priv->host) < 0) {
1420 1421 1422
        goto failure;
    }

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

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1433 1434
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
1435 1436 1437
        goto failure;
    }

1438
    if (esxVI_RebootGuest(priv->host, virtualMachine->obj) < 0) {
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
        goto failure;
    }

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

    return result;

  failure:
    result = -1;

    goto cleanup;
}



static int
esxDomainDestroy(virDomainPtr domain)
{
    int result = 0;
M
Matthias Bolte 已提交
1460
    esxPrivate *priv = domain->conn->privateData;
1461
    esxVI_Context *ctx = NULL;
1462 1463 1464 1465 1466 1467
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1468 1469 1470 1471 1472 1473
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

1474
    if (esxVI_EnsureSession(ctx) < 0) {
1475 1476 1477
        goto failure;
    }

1478
    if (esxVI_String_AppendValueToList(&propertyNameList,
1479
                                       "runtime.powerState") < 0 ||
1480
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1481
          (ctx, domain->uuid, propertyNameList, &virtualMachine,
1482
           priv->autoAnswer) < 0 ||
1483
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
1484 1485 1486 1487
        goto failure;
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1488 1489
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
1490 1491 1492
        goto failure;
    }

1493 1494 1495
    if (esxVI_PowerOffVM_Task(ctx, virtualMachine->obj, &task) < 0 ||
        esxVI_WaitForTaskCompletion(ctx, task, domain->uuid, priv->autoAnswer,
                                    &taskInfoState) < 0) {
1496 1497 1498 1499
        goto failure;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1500
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not destroy domain"));
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
        goto failure;
    }

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

    return result;

  failure:
    result = -1;

    goto cleanup;
}



static char *
1520
esxDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED)
1521
{
1522 1523 1524
    char *osType = strdup("hvm");

    if (osType == NULL) {
1525
        virReportOOMError();
1526 1527 1528 1529
        return NULL;
    }

    return osType;
1530 1531 1532 1533 1534 1535 1536
}



static unsigned long
esxDomainGetMaxMemory(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1537
    esxPrivate *priv = domain->conn->privateData;
1538 1539 1540 1541 1542
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    unsigned long memoryMB = 0;

1543
    if (esxVI_EnsureSession(priv->host) < 0) {
1544 1545 1546
        goto failure;
    }

1547
    if (esxVI_String_AppendValueToList(&propertyNameList,
1548
                                       "config.hardware.memoryMB") < 0 ||
1549 1550
        esxVI_LookupVirtualMachineByUuid(priv->host, domain->uuid,
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1551
                                         esxVI_Occurrence_RequiredItem) < 0) {
1552 1553 1554 1555 1556 1557
        goto failure;
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
1558
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1559 1560 1561 1562 1563
                                         esxVI_Type_Int) < 0) {
                goto failure;
            }

            if (dynamicProperty->val->int32 < 0) {
1564 1565
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                          _("Got invalid memory size %d"),
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
                          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 */

  failure:
    memoryMB = 0;

    goto cleanup;
}



static int
esxDomainSetMaxMemory(virDomainPtr domain, unsigned long memory)
{
    int result = 0;
M
Matthias Bolte 已提交
1595
    esxPrivate *priv = domain->conn->privateData;
1596 1597 1598 1599 1600
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1601
    if (esxVI_EnsureSession(priv->host) < 0) {
1602 1603 1604
        goto failure;
    }

1605
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1606
          (priv->host, domain->uuid, NULL, &virtualMachine,
1607
           priv->autoAnswer) < 0 ||
1608 1609
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Long_Alloc(&spec->memoryMB) < 0) {
1610 1611 1612 1613 1614 1615
        goto failure;
    }

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

1616 1617 1618 1619
    if (esxVI_ReconfigVM_Task(priv->host, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
1620 1621 1622 1623
        goto failure;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1624
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1625
                  _("Could not set max-memory to %lu kilobytes"), memory);
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
        goto failure;
    }

  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);

    return result;

  failure:
    result = -1;

    goto cleanup;
}



static int
esxDomainSetMemory(virDomainPtr domain, unsigned long memory)
{
    int result = 0;
M
Matthias Bolte 已提交
1648
    esxPrivate *priv = domain->conn->privateData;
1649 1650 1651 1652 1653
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1654
    if (esxVI_EnsureSession(priv->host) < 0) {
1655 1656 1657
        goto failure;
    }

1658
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1659
          (priv->host, domain->uuid, NULL, &virtualMachine,
1660
           priv->autoAnswer) < 0 ||
1661 1662 1663
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0 ||
        esxVI_Long_Alloc(&spec->memoryAllocation->limit) < 0) {
1664 1665 1666 1667 1668 1669
        goto failure;
    }

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

1670 1671 1672 1673
    if (esxVI_ReconfigVM_Task(priv->host, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
1674 1675 1676 1677
        goto failure;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1678
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1679
                  _("Could not set memory to %lu kilobytes"), memory);
1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
        goto failure;
    }

  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);

    return result;

  failure:
    result = -1;

    goto cleanup;
}



static int
esxDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info)
{
    int result = 0;
M
Matthias Bolte 已提交
1702
    esxPrivate *priv = domain->conn->privateData;
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
    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;
1715 1716
    esxVI_PerfEntityMetricBase *perfEntityMetricBase = NULL;
    esxVI_PerfEntityMetricBase *perfEntityMetricBaseList = NULL;
1717 1718 1719 1720
    esxVI_PerfEntityMetric *perfEntityMetric = NULL;
    esxVI_PerfMetricIntSeries *perfMetricIntSeries = NULL;
    esxVI_Long *value = NULL;

1721
    if (esxVI_EnsureSession(priv->host) < 0) {
1722 1723 1724
        goto failure;
    }

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

    info->state = VIR_DOMAIN_NOSTATE;
    info->maxMem = 0;
    info->memory = 0;
    info->nrVirtCpu = 0;
    info->cpuTime = 0; /* FIXME */

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.powerState")) {
            if (esxVI_VirtualMachinePowerState_CastFromAnyType
1746
                  (dynamicProperty->val, &powerState) < 0) {
1747 1748 1749
                goto failure;
            }

1750 1751
            info->state = esxVI_VirtualMachinePowerState_ConvertToLibvirt
                            (powerState);
1752
        } else if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
1753
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1754 1755 1756 1757 1758 1759
                                         esxVI_Type_Int) < 0) {
                goto failure;
            }

            info->maxMem = dynamicProperty->val->int32 * 1024; /* Scale from megabyte to kilobyte */
        } else if (STREQ(dynamicProperty->name, "config.hardware.numCPU")) {
1760
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1761 1762 1763 1764 1765 1766 1767
                                         esxVI_Type_Int) < 0) {
                goto failure;
            }

            info->nrVirtCpu = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "config.memoryAllocation.limit")) {
1768
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787
                                         esxVI_Type_Long) < 0) {
                goto failure;
            }

            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) {
1788
        if (esxVI_Int_Alloc(&counterId) < 0) {
1789 1790 1791 1792 1793
            goto failure;
        }

        counterId->value = priv->usedCpuTimeCounterId;

1794
        if (esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
1795 1796 1797
            goto failure;
        }

1798
        if (esxVI_QueryPerfCounter(priv->host, counterIdList,
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
                                   &perfCounterInfo) < 0) {
            goto failure;
        }

        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) {
1821 1822 1823
        if (esxVI_QueryAvailablePerfMetric(priv->host, virtualMachine->obj,
                                           NULL, NULL, NULL,
                                           &perfMetricIdList) < 0) {
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833
            goto failure;
        }

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

            counterId = NULL;

1834 1835
            if (esxVI_Int_DeepCopy(&counterId, perfMetricId->counterId) < 0 ||
                esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
1836 1837 1838 1839
                goto failure;
            }
        }

1840
        if (esxVI_QueryPerfCounter(priv->host, counterIdList,
1841 1842 1843 1844 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
                                   &perfCounterInfoList) < 0) {
            goto failure;
        }

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

1876 1877 1878 1879
        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) {
1880 1881 1882 1883 1884 1885 1886 1887 1888
            goto failure;
        }

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

1889 1890
        if (esxVI_QueryPerf(priv->host, querySpec,
                            &perfEntityMetricBaseList) < 0) {
1891 1892 1893 1894 1895 1896
            querySpec->entity = NULL;
            querySpec->metricId->instance = NULL;
            querySpec->format = NULL;
            goto failure;
        }

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

1902 1903 1904 1905 1906 1907 1908
            perfEntityMetric =
              esxVI_PerfEntityMetric_DynamicCast(perfEntityMetricBase);

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

1909 1910 1911 1912 1913 1914 1915 1916
            perfMetricIntSeries =
              esxVI_PerfMetricIntSeries_DynamicCast(perfEntityMetric->value);

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

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

                for (value = perfMetricIntSeries->value;
                     value != NULL;
                     value = value->_next) {
1923
                    VIR_DEBUG("value %lld", (long long int)value->value);
1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
                }
            }
        }

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

        VIR_DEBUG("usedCpuTimeCounterId %d END", priv->usedCpuTimeCounterId);
    }

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

    return result;

  failure:
    result = -1;

    goto cleanup;
}



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

    if (nvcpus < 1) {
1966 1967
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Requested number of virtual CPUs must at least be 1"));
1968 1969 1970
        goto failure;
    }

1971
    if (esxVI_EnsureSession(priv->host) < 0) {
1972 1973 1974
        goto failure;
    }

M
Matthias Bolte 已提交
1975
    maxVcpus = esxDomainGetMaxVcpus(domain);
1976

M
Matthias Bolte 已提交
1977
    if (maxVcpus < 0) {
1978 1979 1980
        goto failure;
    }

M
Matthias Bolte 已提交
1981
    if (nvcpus > maxVcpus) {
1982
        ESX_ERROR(VIR_ERR_INVALID_ARG,
1983 1984
                  _("Requested number of virtual CPUs is greater than max "
                    "allowable number of virtual CPUs for the domain: %d > %d"),
M
Matthias Bolte 已提交
1985
                  nvcpus, maxVcpus);
1986 1987 1988
        goto failure;
    }

1989
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1990
          (priv->host, domain->uuid, NULL, &virtualMachine,
1991
           priv->autoAnswer) < 0 ||
1992 1993
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Int_Alloc(&spec->numCPUs) < 0) {
1994 1995 1996 1997 1998
        goto failure;
    }

    spec->numCPUs->value = nvcpus;

1999 2000 2001 2002
    if (esxVI_ReconfigVM_Task(priv->host, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
2003 2004 2005 2006
        goto failure;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2007
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2008
                  _("Could not set number of virtual CPUs to %d"), nvcpus);
2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
        goto failure;
    }

  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);

    return result;

  failure:
    result = -1;

    goto cleanup;
}



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

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

2039
    if (esxVI_EnsureSession(priv->host) < 0) {
2040 2041 2042
        goto failure;
    }

2043
    if (esxVI_String_AppendValueToList(&propertyNameList,
2044
                                       "capability.maxSupportedVcpus") < 0 ||
2045 2046 2047
        esxVI_LookupObjectContentByType(priv->host, priv->host->hostFolder,
                                        "HostSystem", propertyNameList,
                                        esxVI_Boolean_True, &hostSystem) < 0) {
2048 2049 2050 2051
        goto failure;
    }

    if (hostSystem == NULL) {
2052 2053
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
2054 2055 2056 2057 2058 2059
        goto failure;
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "capability.maxSupportedVcpus")) {
2060
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2061 2062 2063 2064
                                         esxVI_Type_Int) < 0) {
                goto failure;
            }

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

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

M
Matthias Bolte 已提交
2076
    return priv->maxVcpus;
2077 2078

  failure:
M
Matthias Bolte 已提交
2079
    priv->maxVcpus = -1;
2080 2081 2082 2083 2084 2085 2086 2087 2088

    goto cleanup;
}



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

2103
    if (esxVI_EnsureSession(priv->host) < 0) {
2104 2105 2106
        goto failure;
    }

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

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.files.vmPathName")) {
2118
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2119 2120 2121 2122 2123 2124 2125 2126 2127
                                         esxVI_Type_String) < 0) {
                goto failure;
            }

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

2128 2129
    if (esxUtil_ParseDatastoreRelatedPath(vmPathName, &datastoreName,
                                          &directoryName, &fileName) < 0) {
2130 2131 2132
        goto failure;
    }

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

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

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

    if (virBufferError(&buffer)) {
2148
        virReportOOMError();
2149 2150 2151
        goto failure;
    }

2152 2153
    url = virBufferContentAndReset(&buffer);

2154
    if (esxVI_Context_DownloadFile(priv->host, url, &vmx) < 0) {
2155 2156 2157
        goto failure;
    }

2158 2159
    def = esxVMX_ParseConfig(priv->host, vmx, datastoreName, directoryName,
                             priv->host->apiVersion);
2160 2161

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

  cleanup:
2166 2167
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2168
    VIR_FREE(datastoreName);
M
Matthias Bolte 已提交
2169 2170
    VIR_FREE(directoryName);
    VIR_FREE(fileName);
2171 2172
    VIR_FREE(url);
    VIR_FREE(vmx);
2173
    virDomainDefFree(def);
2174 2175 2176 2177

    return xml;

  failure:
2178
    virBufferFreeAndReset(&buffer);
2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190
    VIR_FREE(xml);

    goto cleanup;
}



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

    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2196
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2197
                  _("Unsupported config format '%s'"), nativeFormat);
2198
        return NULL;
2199 2200
    }

2201
    def = esxVMX_ParseConfig(priv->host, nativeConfig, "?", "?",
M
Matthias Bolte 已提交
2202
                             priv->host->apiVersion);
2203 2204

    if (def != NULL) {
2205
        xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
2206 2207 2208 2209 2210 2211 2212 2213 2214
    }

    virDomainDefFree(def);

    return xml;
}



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

    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2225
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2226
                  _("Unsupported config format '%s'"), nativeFormat);
M
Matthias Bolte 已提交
2227 2228 2229
        return NULL;
    }

2230
    def = virDomainDefParseString(priv->caps, domainXml, 0);
M
Matthias Bolte 已提交
2231 2232 2233 2234 2235

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

2236
    vmx = esxVMX_FormatConfig(priv->host, def, priv->host->apiVersion);
M
Matthias Bolte 已提交
2237 2238 2239 2240 2241 2242 2243 2244

    virDomainDefFree(def);

    return vmx;
}



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

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

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

2266
    if (esxVI_EnsureSession(priv->host) < 0) {
2267 2268 2269
        goto failure;
    }

2270
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2271 2272
                                           "name\0"
                                           "runtime.powerState\0") < 0 ||
2273
        esxVI_LookupObjectContentByType(priv->host, priv->host->vmFolder,
2274 2275 2276
                                        "VirtualMachine", propertyNameList,
                                        esxVI_Boolean_True,
                                        &virtualMachineList) < 0) {
2277 2278 2279 2280 2281
        goto failure;
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
2282
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294
                                              &powerState) < 0) {
            goto failure;
        }

        if (powerState == esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

        for (dynamicProperty = virtualMachine->propSet;
             dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "name")) {
2295
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2296 2297 2298 2299 2300 2301 2302
                                             esxVI_Type_String) < 0) {
                    goto failure;
                }

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

                if (names[count] == NULL) {
2303
                    virReportOOMError();
2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323
                    goto failure;
                }

                count++;
                break;
            }
        }

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

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

    return count;

  failure:
2324 2325 2326 2327
    for (i = 0; i < count; ++i) {
        VIR_FREE(names[i]);
    }

2328 2329 2330 2331 2332 2333 2334 2335 2336 2337
    count = -1;

    goto cleanup;
}



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

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

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



static int
esxDomainCreate(virDomainPtr domain)
{
    int result = 0;
M
Matthias Bolte 已提交
2355
    esxPrivate *priv = domain->conn->privateData;
2356 2357 2358 2359 2360 2361
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

2362
    if (esxVI_EnsureSession(priv->host) < 0) {
2363 2364 2365
        goto failure;
    }

2366
    if (esxVI_String_AppendValueToList(&propertyNameList,
2367
                                       "runtime.powerState") < 0 ||
2368
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2369 2370 2371
          (priv->host, domain->uuid, propertyNameList, &virtualMachine,
           priv->autoAnswer) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine,
2372 2373 2374 2375 2376
                                          &powerState) < 0) {
        goto failure;
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2377 2378
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered off"));
2379 2380 2381
        goto failure;
    }

2382 2383
    if (esxVI_PowerOnVM_Task(priv->host, virtualMachine->obj, NULL,
                             &task) < 0 ||
2384 2385
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
2386 2387 2388 2389
        goto failure;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2390
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not start domain"));
2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408
        goto failure;
    }

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

    return result;

  failure:
    result = -1;

    goto cleanup;
}



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

2431
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
2432 2433 2434 2435
        goto failure;
    }

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

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

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

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

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

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

2465 2466 2467 2468 2469 2470 2471
    /*
     * 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 已提交
2472
    if (def->ndisks < 1) {
2473 2474 2475
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Domain XML doesn't contain any disks, cannot deduce "
                    "datastore and path for VMX file"));
2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
        goto failure;
    }

    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) {
2488 2489 2490
        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 已提交
2491 2492 2493
        goto failure;
    }

2494
    if (disk->src == NULL) {
2495 2496 2497
        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 已提交
2498 2499 2500
        goto failure;
    }

2501
    if (esxUtil_ParseDatastoreRelatedPath(disk->src, &datastoreName,
2502
                                          &directoryName, &fileName) < 0) {
M
Matthias Bolte 已提交
2503 2504 2505
        goto failure;
    }

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

    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)) {
2528
        virReportOOMError();
M
Matthias Bolte 已提交
2529 2530 2531 2532 2533 2534 2535 2536
        goto failure;
    }

    url = virBufferContentAndReset(&buffer);

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

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

2555
    if (esxVI_LookupResourcePoolByHostSystem(priv->host, hostSystem,
2556
                                             &resourcePool) < 0) {
M
Matthias Bolte 已提交
2557 2558 2559 2560 2561 2562 2563
        goto failure;
    }

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

    /* Upload VMX file */
2564
    if (esxVI_Context_UploadFile(priv->host, url, vmx) < 0) {
M
Matthias Bolte 已提交
2565 2566 2567 2568
        goto failure;
    }

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

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2578
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not define domain"));
M
Matthias Bolte 已提交
2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606
        goto failure;
    }

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

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

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

  cleanup:
    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;

  failure:
2607 2608
    virBufferFreeAndReset(&buffer);

M
Matthias Bolte 已提交
2609 2610 2611 2612 2613 2614 2615
    domain = NULL;

    goto cleanup;
}



2616 2617 2618 2619
static int
esxDomainUndefine(virDomainPtr domain)
{
    int result = 0;
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) {
2633 2634 2635
        goto failure;
    }

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) {
2642 2643 2644 2645 2646
        goto failure;
    }

    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"));
2649 2650 2651
        goto failure;
    }

2652
    if (esxVI_UnregisterVM(ctx, virtualMachine->obj) < 0) {
2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669
        goto failure;
    }

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

    return result;

  failure:
    result = -1;

    goto cleanup;
}



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

    if (type == NULL) {
2706
        virReportOOMError();
2707
        return NULL;
2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721
    }

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

    return type;
}



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

2736
    if (esxVI_EnsureSession(priv->host) < 0) {
2737 2738 2739
        goto failure;
    }

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

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

            params[i].type = VIR_DOMAIN_SCHED_FIELD_LLONG;

2760
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2761 2762 2763 2764 2765 2766 2767 2768 2769
                                         esxVI_Type_Long) < 0) {
                goto failure;
            }

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

            params[i].type = VIR_DOMAIN_SCHED_FIELD_LLONG;

2776
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2777 2778 2779 2780 2781 2782 2783 2784 2785
                                         esxVI_Type_Long) < 0) {
                goto failure;
            }

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

            params[i].type = VIR_DOMAIN_SCHED_FIELD_INT;

2792
            if (esxVI_SharesInfo_CastFromAnyType(dynamicProperty->val,
2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814
                                                 &sharesInfo) < 0) {
                goto failure;
            }

            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:
2815
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2816
                          _("Shares level has unknown value %d"),
2817
                          (int)sharesInfo->level);
2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850
                goto failure;
            }

            esxVI_SharesInfo_Free(&sharesInfo);

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

    *nparams = i;

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

    return result;

  failure:
    result = -1;

    goto cleanup;
}



static int
esxDomainSetSchedulerParameters(virDomainPtr domain,
                                virSchedParameterPtr params, int nparams)
{
    int result = 0;
M
Matthias Bolte 已提交
2851
    esxPrivate *priv = domain->conn->privateData;
2852 2853 2854 2855 2856 2857 2858
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
    int i;

2859
    if (esxVI_EnsureSession(priv->host) < 0) {
2860 2861 2862
        goto failure;
    }

2863
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2864
          (priv->host, domain->uuid, NULL, &virtualMachine,
2865
           priv->autoAnswer) < 0 ||
2866 2867
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->cpuAllocation) < 0) {
2868 2869 2870 2871 2872 2873
        goto failure;
    }

    for (i = 0; i < nparams; ++i) {
        if (STREQ (params[i].field, "reservation") &&
            params[i].type == VIR_DOMAIN_SCHED_FIELD_LLONG) {
2874
            if (esxVI_Long_Alloc(&spec->cpuAllocation->reservation) < 0) {
2875 2876 2877 2878
                goto failure;
            }

            if (params[i].value.l < 0) {
2879
                ESX_ERROR(VIR_ERR_INVALID_ARG,
2880 2881
                          _("Could not set reservation to %lld MHz, expecting "
                            "positive value"), params[i].value.l);
2882 2883 2884 2885 2886 2887
                goto failure;
            }

            spec->cpuAllocation->reservation->value = params[i].value.l;
        } else if (STREQ (params[i].field, "limit") &&
                   params[i].type == VIR_DOMAIN_SCHED_FIELD_LLONG) {
2888
            if (esxVI_Long_Alloc(&spec->cpuAllocation->limit) < 0) {
2889 2890 2891 2892
                goto failure;
            }

            if (params[i].value.l < -1) {
2893
                ESX_ERROR(VIR_ERR_INVALID_ARG,
2894 2895
                          _("Could not set limit to %lld MHz, expecting "
                            "positive value or -1 (unlimited)"),
2896 2897 2898 2899 2900 2901
                          params[i].value.l);
                goto failure;
            }

            spec->cpuAllocation->limit->value = params[i].value.l;
        } else if (STREQ (params[i].field, "shares") &&
2902
                   params[i].type == VIR_DOMAIN_SCHED_FIELD_INT) {
2903 2904
            if (esxVI_SharesInfo_Alloc(&sharesInfo) < 0 ||
                esxVI_Int_Alloc(&sharesInfo->shares) < 0) {
2905 2906 2907 2908 2909
                goto failure;
            }

            spec->cpuAllocation->shares = sharesInfo;

2910
            if (params[i].value.i >= 0) {
2911
                spec->cpuAllocation->shares->level = esxVI_SharesLevel_Custom;
2912
                spec->cpuAllocation->shares->shares->value = params[i].value.i;
2913
            } else {
2914
                switch (params[i].value.i) {
2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932
                  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:
2933
                    ESX_ERROR(VIR_ERR_INVALID_ARG,
2934 2935
                              _("Could not set shares to %d, expecting positive "
                                "value or -1 (low), -2 (normal) or -3 (high)"),
2936 2937 2938 2939 2940
                              params[i].value.i);
                    goto failure;
                }
            }
        } else {
2941
            ESX_ERROR(VIR_ERR_INVALID_ARG, _("Unknown field '%s'"),
2942
                      params[i].field);
2943 2944 2945 2946
            goto failure;
        }
    }

2947 2948 2949 2950
    if (esxVI_ReconfigVM_Task(priv->host, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
2951 2952 2953 2954
        goto failure;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2955 2956
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not change scheduler parameters"));
2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987
        goto failure;
    }

  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);

    return result;

  failure:
    result = -1;

    goto cleanup;
}



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)
{
    int result = 0;
    char *transport = NULL;

    if (uri_in == NULL) {
2988
        if (esxUtil_ParseQuery(dconn->uri, &transport, NULL, NULL, NULL) < 0) {
2989 2990 2991
            return -1;
        }

2992 2993
        if (virAsprintf(uri_out, "%s://%s:%d/sdk", transport,
                        dconn->uri->server, dconn->uri->port) < 0) {
2994
            virReportOOMError();
2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021
            goto failure;
        }
    }

  cleanup:
    VIR_FREE(transport);

    return result;

  failure:
    result = -1;

    goto cleanup;
}



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)
{
    int result = 0;
M
Matthias Bolte 已提交
3022
    esxPrivate *priv = domain->conn->privateData;
3023
    xmlURIPtr xmlUri = NULL;
M
Matthias Bolte 已提交
3024
    char hostIpAddress[NI_MAXHOST] = "";
3025 3026 3027 3028 3029 3030 3031 3032
    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 已提交
3033
    if (priv->vCenter == NULL) {
3034 3035
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Migration not possible without a vCenter"));
3036 3037 3038 3039
        goto failure;
    }

    if (dname != NULL) {
3040 3041
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Renaming domains on migration not supported"));
3042 3043 3044
        goto failure;
    }

3045
    if (esxVI_EnsureSession(priv->vCenter) < 0) {
3046 3047 3048 3049 3050 3051 3052
        goto failure;
    }

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

    if (xmlUri == NULL) {
3053
        virReportOOMError();
3054 3055 3056
        goto failure;
    }

3057
    if (esxUtil_ResolveHostname(xmlUri->server, hostIpAddress,
3058 3059 3060 3061 3062
                                NI_MAXHOST) < 0) {
        goto failure;
    }

    /* Lookup VirtualMachine, HostSystem and ResourcePool */
3063
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3064
          (priv->vCenter, domain->uuid, NULL, &virtualMachine,
3065
           priv->autoAnswer) < 0 ||
3066 3067
        esxVI_String_AppendValueToList(&propertyNameList, "parent") < 0 ||
        esxVI_LookupHostSystemByIp(priv->vCenter, hostIpAddress,
M
Matthias Bolte 已提交
3068
                                   propertyNameList, &hostSystem) < 0) {
3069 3070 3071
        goto failure;
    }

3072 3073
    if (esxVI_LookupResourcePoolByHostSystem(priv->vCenter, hostSystem,
                                             &resourcePool) < 0) {
3074 3075 3076 3077
        goto failure;
    }

    /* Validate the purposed migration */
3078
    if (esxVI_ValidateMigration(priv->vCenter, virtualMachine->obj,
3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090
                                esxVI_VirtualMachinePowerState_Undefined,
                                NULL, resourcePool, hostSystem->obj,
                                &eventList) < 0) {
        goto failure;
    }

    if (eventList != NULL) {
        /*
         * FIXME: Need to report the complete list of events. Limit reporting
         *        to the first event for now.
         */
        if (eventList->fullFormattedMessage != NULL) {
3091
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3092 3093
                      _("Could not migrate domain, validation reported a "
                        "problem: %s"), eventList->fullFormattedMessage);
3094
        } else {
3095 3096 3097
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                      _("Could not migrate domain, validation reported a "
                        "problem"));
3098 3099 3100 3101 3102 3103
        }

        goto failure;
    }

    /* Perform the purposed migration */
3104
    if (esxVI_MigrateVM_Task(priv->vCenter, virtualMachine->obj, resourcePool,
3105 3106 3107 3108
                             hostSystem->obj,
                             esxVI_VirtualMachineMovePriority_DefaultPriority,
                             esxVI_VirtualMachinePowerState_Undefined,
                             &task) < 0 ||
3109 3110
        esxVI_WaitForTaskCompletion(priv->vCenter, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
3111 3112 3113 3114
        goto failure;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3115 3116 3117
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not migrate domain, migration task finished with "
                    "an error"));
3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151
        goto failure;
    }

  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;

  failure:
    result = -1;

    goto cleanup;
}



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 已提交
3152 3153 3154 3155
static unsigned long long
esxNodeGetFreeMemory(virConnectPtr conn)
{
    unsigned long long result = 0;
M
Matthias Bolte 已提交
3156
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
3157 3158 3159 3160 3161 3162 3163
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_ManagedObjectReference *managedObjectReference = NULL;
    esxVI_ObjectContent *resourcePool = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ResourcePoolResourceUsage *resourcePoolResourceUsage = NULL;

3164
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3165 3166 3167 3168
        goto failure;
    }

    /* Lookup host system with its resource pool */
3169 3170
    if (esxVI_String_AppendValueToList(&propertyNameList, "parent") < 0 ||
        esxVI_LookupHostSystemByIp(priv->host, priv->host->ipAddress,
M
Matthias Bolte 已提交
3171 3172 3173 3174
                                   propertyNameList, &hostSystem) < 0) {
        goto failure;
    }

3175
    if (esxVI_LookupResourcePoolByHostSystem(priv->host, hostSystem,
3176
                                             &managedObjectReference) < 0) {
M
Matthias Bolte 已提交
3177 3178 3179 3180 3181 3182
        goto failure;
    }

    esxVI_String_Free(&propertyNameList);

    /* Get memory usage of resource pool */
3183
    if (esxVI_String_AppendValueToList(&propertyNameList,
M
Matthias Bolte 已提交
3184
                                       "runtime.memory") < 0 ||
3185
        esxVI_LookupObjectContentByType(priv->host, managedObjectReference,
3186 3187 3188
                                        "ResourcePool", propertyNameList,
                                        esxVI_Boolean_False,
                                        &resourcePool) < 0) {
M
Matthias Bolte 已提交
3189 3190 3191 3192 3193 3194 3195
        goto failure;
    }

    for (dynamicProperty = resourcePool->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.memory")) {
            if (esxVI_ResourcePoolResourceUsage_CastFromAnyType
3196
                  (dynamicProperty->val, &resourcePoolResourceUsage) < 0) {
M
Matthias Bolte 已提交
3197 3198 3199 3200 3201 3202 3203 3204 3205 3206
                goto failure;
            }

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

    if (resourcePoolResourceUsage == NULL) {
3207 3208
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve memory usage of resource pool"));
M
Matthias Bolte 已提交
3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230
        goto failure;
    }

    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;

  failure:
    result = 0;

    goto cleanup;
}



3231 3232 3233
static int
esxIsEncrypted(virConnectPtr conn)
{
M
Matthias Bolte 已提交
3234
    esxPrivate *priv = conn->privateData;
3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247

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



static int
esxIsSecure(virConnectPtr conn)
{
M
Matthias Bolte 已提交
3248
    esxPrivate *priv = conn->privateData;
3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262

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



static int
esxDomainIsActive(virDomainPtr domain)
{
    int result = 0;
M
Matthias Bolte 已提交
3263
    esxPrivate *priv = domain->conn->privateData;
3264 3265 3266 3267
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

3268
    if (esxVI_EnsureSession(priv->host) < 0) {
3269 3270 3271
        goto failure;
    }

3272
    if (esxVI_String_AppendValueToList(&propertyNameList,
3273
                                       "runtime.powerState") < 0 ||
3274 3275
        esxVI_LookupVirtualMachineByUuid(priv->host, domain->uuid,
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3276
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3277
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309
        goto failure;
    }

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

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

    return result;

  failure:
    result = -1;

    goto cleanup;
}



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



3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 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 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728
static virDomainSnapshotPtr
esxDomainSnapshotCreateXML(virDomainPtr domain, const char *xmlDesc,
                           unsigned int flags ATTRIBUTE_UNUSED)
{
    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;

    if (esxVI_EnsureSession(priv->host) < 0) {
        goto failure;
    }

    def = virDomainSnapshotDefParseString(xmlDesc, 1);

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

    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) {
        goto failure;
    }

    if (snapshotTree != NULL) {
        ESX_ERROR(VIR_ERR_OPERATION_INVALID,
                  _("Snapshot '%s' already exists"), def->name);
        goto failure;
    }

    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) {
        goto failure;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not create snapshot"));
        goto failure;
    }

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

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

    return snapshot;

  failure:
    domain = NULL;

    goto cleanup;
}



static char *
esxDomainSnapshotDumpXML(virDomainSnapshotPtr snapshot,
                         unsigned int flags ATTRIBUTE_UNUSED)
{
    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;

    memset(&def, 0, sizeof (virDomainSnapshotDef));

    if (esxVI_EnsureSession(priv->host) < 0) {
        goto failure;
    }

    if (esxVI_LookupRootSnapshotTreeList(priv->host, snapshot->domain->uuid,
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto failure;
    }

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

    if (esxVI_DateTime_ConvertToCalendarTime(snapshotTree->createTime,
                                             &def.creationTime) < 0) {
        goto failure;
    }

    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;

  failure:
    VIR_FREE(xml);

    goto cleanup;
}



static int
esxDomainSnapshotNum(virDomainPtr domain, unsigned int flags ATTRIBUTE_UNUSED)
{
    int result = 0;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;

    if (esxVI_EnsureSession(priv->host) < 0) {
        goto failure;
    }

    if (esxVI_LookupRootSnapshotTreeList(priv->host, domain->uuid,
                                         &rootSnapshotTreeList) < 0) {
        goto failure;
    }

    result = esxVI_GetNumberOfSnapshotTrees(rootSnapshotTreeList);

  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;

  failure:
    result = -1;

    goto cleanup;
}



static int
esxDomainSnapshotListNames(virDomainPtr domain, char **names, int nameslen,
                           unsigned int flags ATTRIBUTE_UNUSED)
{
    int result = 0;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;

    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) {
        goto failure;
    }

    if (esxVI_LookupRootSnapshotTreeList(priv->host, domain->uuid,
                                         &rootSnapshotTreeList) < 0) {
        goto failure;
    }

    result = esxVI_GetSnapshotTreeNames(rootSnapshotTreeList, names, nameslen);

  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;

  failure:
    result = -1;

    goto cleanup;
}



static virDomainSnapshotPtr
esxDomainSnapshotLookupByName(virDomainPtr domain, const char *name,
                              unsigned int flags ATTRIBUTE_UNUSED)
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    virDomainSnapshotPtr snapshot = NULL;

    if (esxVI_EnsureSession(priv->host) < 0) {
        goto cleanup;
    }

    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)
{
    int result = 0;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *currentSnapshotTree = NULL;

    if (flags != 0) {
        ESX_ERROR(VIR_ERR_INVALID_ARG,
                  _("Unsupported flags (0x%x) passed to %s"),
                  flags, __FUNCTION__);
        return -1;
    }

    if (esxVI_EnsureSession(priv->host) < 0) {
        goto failure;
    }

    if (esxVI_LookupCurrentSnapshotTree(priv->host, domain->uuid,
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_OptionalItem) < 0) {
        goto failure;
    }

    if (currentSnapshotTree != NULL) {
        result = 1;
    }

  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return result;

  failure:
    result = -1;

    goto cleanup;
}



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

    if (flags != 0) {
        ESX_ERROR(VIR_ERR_INVALID_ARG,
                  _("Unsupported flags (0x%x) passed to %s"),
                  flags, __FUNCTION__);
        return NULL;
    }

    if (esxVI_EnsureSession(priv->host) < 0) {
        goto cleanup;
    }

    if (esxVI_LookupCurrentSnapshotTree(priv->host, domain->uuid,
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

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

  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return snapshot;
}



static int
esxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot, unsigned int flags)
{
    int result = 0;
    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;

    if (flags != 0) {
        ESX_ERROR(VIR_ERR_INVALID_ARG,
                  _("Unsupported flags (0x%x) passed to %s"),
                  flags, __FUNCTION__);
        return -1;
    }

    if (esxVI_EnsureSession(priv->host) < 0) {
        goto failure;
    }

    if (esxVI_LookupRootSnapshotTreeList(priv->host, snapshot->domain->uuid,
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto failure;
    }

    if (esxVI_RevertToSnapshot_Task(priv->host, snapshotTree->snapshot, NULL,
                                    &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, snapshot->domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
        goto failure;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not revert to snapshot '%s'"), snapshot->name);
        goto failure;
    }

  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;

  failure:
    result = -1;

    goto cleanup;
}



static int
esxDomainSnapshotDelete(virDomainSnapshotPtr snapshot, unsigned int flags)
{
    int result = 0;
    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;

    if (esxVI_EnsureSession(priv->host) < 0) {
        goto failure;
    }

    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) {
        goto failure;
    }

    if (esxVI_RemoveSnapshot_Task(priv->host, snapshotTree->snapshot,
                                  removeChildren, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, snapshot->domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
        goto failure;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not delete snapshot '%s'"), snapshot->name);
        goto failure;
    }

  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;

  failure:
    result = -1;

    goto cleanup;
}



3729 3730 3731 3732 3733 3734 3735 3736
static virDriver esxDriver = {
    VIR_DRV_ESX,
    "ESX",
    esxOpen,                         /* open */
    esxClose,                        /* close */
    esxSupportsFeature,              /* supports_feature */
    esxGetType,                      /* type */
    esxGetVersion,                   /* version */
3737
    NULL,                            /* libvirtVersion (impl. in libvirt.c) */
3738 3739 3740
    esxGetHostname,                  /* hostname */
    NULL,                            /* getMaxVcpus */
    esxNodeGetInfo,                  /* nodeGetInfo */
3741
    esxGetCapabilities,              /* getCapabilities */
3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767
    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 */
3768
    esxDomainXMLFromNative,          /* domainXMLFromNative */
M
Matthias Bolte 已提交
3769
    esxDomainXMLToNative,            /* domainXMLToNative */
3770 3771 3772
    esxListDefinedDomains,           /* listDefinedDomains */
    esxNumberOfDefinedDomains,       /* numOfDefinedDomains */
    esxDomainCreate,                 /* domainCreate */
M
Matthias Bolte 已提交
3773
    esxDomainDefineXML,              /* domainDefineXML */
3774
    esxDomainUndefine,               /* domainUndefine */
3775
    NULL,                            /* domainAttachDevice */
3776
    NULL,                            /* domainAttachDeviceFlags */
3777
    NULL,                            /* domainDetachDevice */
3778
    NULL,                            /* domainDetachDeviceFlags */
3779
    NULL,                            /* domainUpdateDeviceFlags */
3780 3781 3782 3783 3784 3785 3786 3787 3788 3789
    NULL,                            /* domainGetAutostart */
    NULL,                            /* domainSetAutostart */
    esxDomainGetSchedulerType,       /* domainGetSchedulerType */
    esxDomainGetSchedulerParameters, /* domainGetSchedulerParameters */
    esxDomainSetSchedulerParameters, /* domainSetSchedulerParameters */
    esxDomainMigratePrepare,         /* domainMigratePrepare */
    esxDomainMigratePerform,         /* domainMigratePerform */
    esxDomainMigrateFinish,          /* domainMigrateFinish */
    NULL,                            /* domainBlockStats */
    NULL,                            /* domainInterfaceStats */
3790
    NULL,                            /* domainMemoryStats */
3791 3792 3793
    NULL,                            /* domainBlockPeek */
    NULL,                            /* domainMemoryPeek */
    NULL,                            /* nodeGetCellsFreeMemory */
M
Matthias Bolte 已提交
3794
    esxNodeGetFreeMemory,            /* nodeGetFreeMemory */
3795 3796 3797 3798 3799 3800 3801
    NULL,                            /* domainEventRegister */
    NULL,                            /* domainEventDeregister */
    NULL,                            /* domainMigratePrepare2 */
    NULL,                            /* domainMigrateFinish2 */
    NULL,                            /* nodeDeviceDettach */
    NULL,                            /* nodeDeviceReAttach */
    NULL,                            /* nodeDeviceReset */
C
Chris Lalancette 已提交
3802
    NULL,                            /* domainMigratePrepareTunnel */
3803 3804 3805 3806
    esxIsEncrypted,                  /* isEncrypted */
    esxIsSecure,                     /* isSecure */
    esxDomainIsActive,               /* domainIsActive */
    esxDomainIsPersistent,           /* domainIsPersistent */
J
Jiri Denemark 已提交
3807
    NULL,                            /* cpuCompare */
3808
    NULL,                            /* cpuBaseline */
3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825
    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 */
3826 3827 3828 3829 3830 3831 3832
};



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

    return 0;
}